// ============================================================
// Saraya Events — Authentication layer
//
// Provides: AuthProvider, useAuth, AuthModal
// Depends on: window.SarayaDB (supabase.js), window.AuthContext (HTML bridge)
// Loaded before admin.jsx so AdminProvider can consume AuthContext.
//
// When Supabase is configured:
//   - Real email/password auth via Supabase Auth
//   - Profile.role drives Admin / Vendor / Customer access
// When Supabase is NOT configured:
//   - All auth state is 'guest'; the old admin passcode fallback still works
// ============================================================

const {
  useState: useStateAuth,
  useEffect: useEffectAuth,
  useCallback: useCallbackAuth,
  useContext: useContextAuth,
  useRef: useRefAuth,
} = React;

/* ---------- Vendor package options (used in registration flow) ---------- */
const VENDOR_PACKAGES_AUTH = [
  {
    id: 'starter', en: 'Starter Vendor', ar: 'مورد مبتدئ', price: 99,
    highlight: false, badge: null,
    features: {
      en: ['Basic vendor profile page', 'Display products & services', 'Receive customer inquiries', 'WhatsApp & contact button', 'Ideal for small & home businesses'],
      ar: ['صفحة ملف مورد أساسية', 'عرض المنتجات والخدمات', 'استقبال استفسارات العملاء', 'زر واتساب وتواصل', 'مثالي للأعمال الصغيرة والمنزلية'],
    },
    cta: { en: 'Continue with Starter', ar: 'المتابعة بالمبتدئ' },
  },
  {
    id: 'professional', en: 'Professional Vendor', ar: 'مورد احترافي', price: 299,
    highlight: true, badge: { en: 'Most popular', ar: 'الأكثر شيوعًا' },
    features: {
      en: ['Up to 50 listings (products, rentals, services)', 'Featured placement in category pages', 'Priority search ranking', 'Unlimited RFQ responses per month', 'Advanced analytics & revenue reports'],
      ar: ['حتى 50 قائمة (منتجات، إيجار، خدمات)', 'عرض مميز في صفحات الفئات', 'أولوية في ترتيب البحث', 'ردود غير محدودة على عروض الأسعار شهريًا', 'تحليلات متقدمة وتقارير إيرادات'],
    },
    cta: { en: 'Continue with Professional', ar: 'المتابعة بالاحترافي' },
  },
  {
    id: 'premium', en: 'Premium Vendor', ar: 'مورد مميز', price: 599,
    highlight: false, badge: null,
    features: {
      en: ['Unlimited listings', 'Homepage featured carousel slot', 'Top search ranking across all categories', 'Dedicated account manager', 'Co-marketing opportunities'],
      ar: ['قوائم غير محدودة', 'مكان مميز في كاروسيل الصفحة الرئيسية', 'أعلى ترتيب في جميع الفئات', 'مدير حساب مخصص', 'فرص تسويق مشترك'],
    },
    cta: { en: 'Continue with Premium', ar: 'المتابعة بالمميز' },
  },
];

/* ---------- hook ---------- */
function useAuth() {
  return useContextAuth(window.AuthContext);
}
window.useAuth = useAuth;

/* ---------- AuthProvider ---------- */
function AuthProvider({ children }) {
  const db = window.SarayaDB;

  const [user, setUser]               = useStateAuth(null);
  const [profile, setProfile]         = useStateAuth(null);
  const [loading, setLoading]         = useStateAuth(true);
  const [authModalOpen, setAuthModalOpen] = useStateAuth(false);
  const [authMode, setAuthMode]       = useStateAuth('login');
  // Used when a vendor signs up and needs to complete vendor registration
  const [pendingVendorUserId, setPendingVendorUserId] = useStateAuth(null);

  const fetchProfile = useCallbackAuth(async (uid) => {
    if (!db) return null;
    const { data } = await db.from('profiles').select('*').eq('id', uid).single();
    return data || null;
  }, [db]);

  useEffectAuth(() => {
    if (!db) { setLoading(false); return; }

    // Check for an existing session on mount
    db.auth.getSession().then(async ({ data: { session } }) => {
      const u = session?.user ?? null;
      setUser(u);
      if (u) {
        const p = await fetchProfile(u.id);
        setProfile(p);
      }
      setLoading(false);
    });

    // Listen for login / logout / token refresh
    const { data: { subscription } } = db.auth.onAuthStateChange(async (event, session) => {
      const u = session?.user ?? null;
      setUser(u);
      if (u) {
        const p = await fetchProfile(u.id);
        setProfile(p);

        if (event === 'SIGNED_IN') {
          // Apply any marketing consent stored during registration
          const consentRaw = localStorage.getItem('saraya_consent_pending');
          if (consentRaw) {
            try {
              const c = JSON.parse(consentRaw);
              await db.from('profiles').update({
                marketing_consent: c.consent || false,
                marketing_consent_date: c.consent ? c.date : null,
                marketing_source: c.source || 'website',
              }).eq('id', u.id);
              localStorage.removeItem('saraya_consent_pending');
            } catch (_) {}
          }

          // First sign-in for a vendor: show business profile + package selection
          if (p?.role === 'vendor') {
            const { data: vp } = await db.from('vendor_profiles').select('id, status').eq('id', u.id).single();
            if (!vp) {
              // New vendor — collect business profile, then package
              setPendingVendorUserId(u.id);
              setAuthMode('vendor-register');
              setAuthModalOpen(true);
            } else if (vp.status === 'package_pending') {
              // Business profile saved but package not yet chosen
              setPendingVendorUserId(u.id);
              setAuthMode('vendor-package');
              setAuthModalOpen(true);
            } else {
              setAuthModalOpen(false);
            }
          } else {
            setAuthModalOpen(false);
          }
        }
      } else {
        setProfile(null);
        setPendingVendorUserId(null);
      }
    });

    return () => subscription.unsubscribe();
  }, [db, fetchProfile]);

  const signIn = useCallbackAuth(async ({ email, password }) => {
    if (!db) return { error: { message: 'Database not configured.' } };
    const { error } = await db.auth.signInWithPassword({ email, password });
    return { error };
  }, [db]);

  const signUp = useCallbackAuth(async ({ email, password, displayName, role, phone }) => {
    if (!db) return { error: { message: 'Database not configured.' } };
    const { error } = await db.auth.signUp({
      email,
      password,
      options: {
        data: {
          display_name: displayName || email.split('@')[0],
          role: role || 'customer',
          phone: phone || '',
        },
      },
    });
    return { error };
  }, [db]);

  const signInWithGoogle = useCallbackAuth(async () => {
    if (!db) return { error: { message: 'Database not configured.' } };
    const { error } = await db.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin + window.location.pathname },
    });
    return { error };
  }, [db]);

  const signOut = useCallbackAuth(async () => {
    if (!db) return;
    await db.auth.signOut();
    setUser(null);
    setProfile(null);
  }, [db]);

  const openAuthModal = useCallbackAuth((mode) => {
    setAuthMode(mode || 'login');
    setAuthModalOpen(true);
  }, []);

  const refreshProfile = useCallbackAuth(async () => {
    if (!user) return;
    const p = await fetchProfile(user.id);
    setProfile(p);
  }, [user, fetchProfile]);

  const role = profile?.role || 'guest';

  return (
    <window.AuthContext.Provider value={{
      user,
      profile,
      role,
      loading,
      isAdmin:    role === 'admin',
      isVendor:   role === 'vendor',
      isCustomer: role === 'customer',
      signIn,
      signUp,
      signOut,
      signInWithGoogle,
      refreshProfile,
      openAuthModal,
      closeAuthModal: () => setAuthModalOpen(false),
      authModalOpen,
      authMode,
    }}>
      {children}
      {authModalOpen && (
        <AuthModal
          mode={authMode}
          setMode={setAuthMode}
          onClose={() => setAuthModalOpen(false)}
          pendingVendorUserId={pendingVendorUserId}
          onVendorRegistered={() => { setPendingVendorUserId(null); setAuthModalOpen(false); }}
        />
      )}
    </window.AuthContext.Provider>
  );
}
window.AuthProvider = AuthProvider;

/* ============================================================
   AUTH MODAL — login / signup / vendor registration
   Matches the Saraya luxury design system exactly.
   ============================================================ */

const TAB_STYLE = (active) => ({
  flex: 1,
  padding: '11px 0',
  background: 'none',
  border: 'none',
  borderBottom: active ? '2px solid var(--gold)' : '2px solid transparent',
  color: active ? 'var(--fg-primary)' : 'var(--fg-secondary)',
  fontFamily: 'var(--font-body)',
  fontSize: 14,
  fontWeight: active ? 600 : 400,
  cursor: 'pointer',
  transition: 'color 160ms, border-color 160ms',
});

function AuthModal({ mode, setMode, onClose, pendingVendorUserId, onVendorRegistered }) {
  // mode: 'login' | 'signup' | 'vendor-register' | 'vendor-package'
  // tab: 'login' | 'choose-type' | 'signup'
  const [tab, setTab] = useStateAuth(mode === 'signup' ? 'choose-type' : 'login');
  const [form, setForm] = useStateAuth({
    email: '', password: '', confirmPassword: '',
    displayName: '', phone: '', role: 'customer',
    marketingConsent: false, termsAccepted: false,
  });
  const [busy, setBusy] = useStateAuth(false);
  const [error, setError] = useStateAuth('');
  const [success, setSuccess] = useStateAuth('');
  const { signIn, signUp, signInWithGoogle } = useAuth();
  const { lang } = useLang();
  const ar = lang === 'ar';

  const set = (k) => (e) => setForm((p) => ({ ...p, [k]: e.target.value }));

  const handleLogin = async (e) => {
    e.preventDefault();
    setError(''); setBusy(true);
    const { error: err } = await signIn({ email: form.email, password: form.password });
    setBusy(false);
    if (err) setError(err.message || err.error_description || 'Sign in failed. Please try again.');
  };

  const handleSignup = async (e) => {
    e.preventDefault();
    setError('');
    if (!form.termsAccepted) { setError(ar ? 'يجب الموافقة على شروط الاستخدام وسياسة الخصوصية للمتابعة' : 'You must agree to the Terms of Use and Privacy Policy to continue'); return; }
    if (form.password !== form.confirmPassword) { setError(ar ? 'كلمتا المرور غير متطابقتين' : 'Passwords do not match'); return; }
    if (form.password.length < 8) { setError(ar ? 'كلمة المرور يجب أن تكون 8 أحرف على الأقل' : 'Password must be at least 8 characters'); return; }
    setBusy(true);
    // Persist consent so onAuthStateChange can apply it to the profiles row
    try {
      localStorage.setItem('saraya_consent_pending', JSON.stringify({
        consent: form.marketingConsent,
        date: form.marketingConsent ? new Date().toISOString() : null,
        source: localStorage.getItem('saraya_mktg_source') || (location.hash.replace('#', '') || 'website'),
      }));
    } catch (_) {}
    const { error: err } = await signUp({
      email: form.email,
      password: form.password,
      displayName: form.displayName,
      role: form.role,
      phone: form.phone,
    });
    setBusy(false);
    if (err) { setError(err.message || err.error_description || err.msg || (typeof err === 'string' ? err : 'Sign up failed. Please try again.')); return; }
    setSuccess(ar
      ? 'تم إنشاء الحساب. يرجى التحقق من بريدك الإلكتروني.'
      : 'Account created! Check your email to confirm, or sign in if confirmation is disabled.');
  };

  const overlay = {
    position: 'fixed', inset: 0, zIndex: 400,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: '16px', background: 'rgba(42,31,26,0.55)',
    backdropFilter: 'blur(4px)',
  };
  const card = {
    position: 'relative', width: 'min(460px,100%)',
    maxHeight: '90vh', overflowY: 'auto',
    background: 'var(--bg-canvas)', borderRadius: 20,
    boxShadow: '0 24px 64px rgba(42,31,26,0.28)',
  };

  if (mode === 'vendor-package') {
    return (
      <div style={overlay} onClick={onClose}>
        <div style={{ ...card, width: 'min(760px,100%)' }} onClick={(e) => e.stopPropagation()}>
          <VendorPackageSelectStep
            uid={pendingVendorUserId}
            onDone={onVendorRegistered}
            ar={ar}
          />
          <button onClick={onClose} style={{ position: 'absolute', top: 16, insetInlineEnd: 16, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', display: 'flex', padding: 6, borderRadius: 8 }}>
            <Icon name="x" size={20} />
          </button>
        </div>
      </div>
    );
  }

  if (mode === 'vendor-register' || pendingVendorUserId) {
    return (
      <div style={overlay} onClick={onClose}>
        <div style={card} onClick={(e) => e.stopPropagation()}>
          <VendorRegisterStep
            vendorUserId={pendingVendorUserId}
            onDone={onVendorRegistered}
            ar={ar}
          />
        </div>
      </div>
    );
  }

  /* ---- Choose account type screen ---- */
  const ChooseTypeScreen = () => (
    <div>
      <div className="saraya-modal-body" style={{ padding: '28px 28px 0', textAlign: 'center' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <Logo height={38} />
        </div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500, color: 'var(--fg-primary)', marginBottom: 6 }}>
          {ar ? 'اختر نوع الحساب' : 'Choose Your Account Type'}
        </h2>
        <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
          {ar ? 'حدد الحساب المناسب لك' : 'Select the account that fits your needs'}
        </p>
      </div>

      <div style={{ padding: '24px 24px 28px', display: 'grid', gap: 14 }}>
        {/* Customer card */}
        <button
          type="button"
          onClick={() => { setForm((p) => ({ ...p, role: 'customer' })); setTab('signup'); setError(''); }}
          style={{
            display: 'flex', alignItems: 'flex-start', gap: 16, padding: '20px 18px',
            borderRadius: 14, border: '1.5px solid var(--line)', background: 'var(--white)',
            cursor: 'pointer', textAlign: 'start', transition: 'all 160ms',
          }}
        >
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="user" size={22} style={{ color: 'var(--gold-deep)' }} />
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 700, color: 'var(--fg-primary)', marginBottom: 5 }}>
              {ar ? 'حساب عميل' : 'Customer Account'}
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.55 }}>
              {ar
                ? 'لتصفح السوق، الطلب، حجز الخدمات، تأجير المنتجات، طلب عروض الأسعار، وتتبع الطلبات.'
                : 'Browse the marketplace, place orders, book services, rent items, request quotes, and track your orders.'}
            </div>
          </div>
          <Icon name="chevron-right" size={18} style={{ color: 'var(--fg-muted)', flexShrink: 0, marginTop: 2, transform: ar ? 'scaleX(-1)' : 'none' }} />
        </button>

        {/* Vendor card */}
        <button
          type="button"
          onClick={() => { setForm((p) => ({ ...p, role: 'vendor' })); setTab('signup'); setError(''); }}
          style={{
            display: 'flex', alignItems: 'flex-start', gap: 16, padding: '20px 18px',
            borderRadius: 14, border: '1.5px solid var(--line)', background: 'var(--white)',
            cursor: 'pointer', textAlign: 'start', transition: 'all 160ms',
          }}
        >
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="store" size={22} style={{ color: 'var(--gold-deep)' }} />
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 700, color: 'var(--fg-primary)', marginBottom: 5 }}>
              {ar ? 'حساب مورد / تاجر' : 'Vendor Account'}
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.55 }}>
              {ar
                ? 'لإضافة المنتجات، عرض معدات التأجير، تقديم الخدمات، استقبال الحجوزات، والرد على طلبات عروض الأسعار.'
                : 'List products, offer rental items, provide services, receive bookings, and respond to RFQ requests.'}
            </div>
          </div>
          <Icon name="chevron-right" size={18} style={{ color: 'var(--fg-muted)', flexShrink: 0, marginTop: 2, transform: ar ? 'scaleX(-1)' : 'none' }} />
        </button>

        <p style={{ textAlign: 'center', fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 4 }}>
          {ar ? 'لديك حساب بالفعل؟ ' : 'Already have an account? '}
          <button type="button" onClick={() => { setTab('login'); setError(''); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, padding: 0 }}>
            {ar ? 'تسجيل الدخول' : 'Sign In'}
          </button>
        </p>
      </div>
    </div>
  );

  return (
    <div style={overlay} onClick={onClose}>
      <div style={card} onClick={(e) => e.stopPropagation()}>

        {/* Choose account type — shown first when signing up */}
        {tab === 'choose-type' ? <ChooseTypeScreen /> : (
          <>
            {/* Header */}
            <div className="saraya-modal-body" style={{ padding: '28px 28px 0', textAlign: 'center' }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <Logo height={40} />
              </div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 500, color: 'var(--fg-primary)', marginBottom: 4 }}>
                {tab === 'login'
                  ? (ar ? 'أهلاً بعودتك' : 'Welcome Back')
                  : (ar ? 'إنشاء حساب' : 'Create Account')}
              </h2>
              <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
                {tab === 'login'
                  ? (ar ? 'تسجيل الدخول إلى حسابك في سرايا' : 'Sign in to your Saraya account')
                  : (form.role === 'vendor'
                    ? (ar ? 'إنشاء حساب مورد في سرايا' : 'Create your Saraya vendor account')
                    : (ar ? 'إنشاء حساب عميل في سرايا' : 'Create your Saraya customer account'))}
              </p>
            </div>

            {/* Tabs */}
            <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', margin: '20px 28px 0' }}>
              <button style={TAB_STYLE(tab === 'login')} onClick={() => { setTab('login'); setError(''); setSuccess(''); }}>
                {ar ? 'تسجيل الدخول' : 'Log In'}
              </button>
              <button style={TAB_STYLE(tab === 'signup')} onClick={() => { setTab('choose-type'); setError(''); setSuccess(''); }}>
                {ar ? 'حساب جديد' : 'Sign Up'}
              </button>
            </div>

            {/* Form body */}
            <div className="saraya-modal-body" style={{ padding: '24px 28px 28px' }}>
              {success ? (
                <div style={{ textAlign: 'center', padding: '28px 0' }}>
                  <Icon name="mail-check" size={44} style={{ color: 'var(--gold)' }} />
                  <p style={{ marginTop: 14, fontSize: 15, lineHeight: 1.6, color: 'var(--fg-secondary)' }}>{success}</p>
                  <Button variant="ghost" style={{ marginTop: 18 }} onClick={onClose}>{ar ? 'إغلاق' : 'Close'}</Button>
                </div>
              ) : tab === 'login' ? (
                <form onSubmit={handleLogin} style={{ display: 'grid', gap: 16 }}>
                  <Field label={ar ? 'البريد الإلكتروني' : 'Email'}>
                    <TextInput type="email" value={form.email} onChange={set('email')} required autoFocus />
                  </Field>
                  <Field label={ar ? 'كلمة المرور' : 'Password'}>
                    <PasswordInput value={form.password} onChange={set('password')} required />
                  </Field>
                  {error && <ErrorMsg>{error}</ErrorMsg>}
                  <Button variant="primary" full type="submit" loading={busy}>
                    {ar ? 'تسجيل الدخول' : 'Log In'}
                  </Button>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '4px 0' }}>
                    <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
                    <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{ar ? 'أو' : 'or'}</span>
                    <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
                  </div>
                  <button
                    type="button"
                    onClick={() => signInWithGoogle()}
                    style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, width: '100%', padding: '11px 16px', borderRadius: 10, border: '1.5px solid var(--line)', background: 'var(--white)', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, color: 'var(--fg-primary)', transition: 'border-color 160ms' }}
                  >
                    <svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg"><path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z" fill="#4285F4"/><path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" fill="#34A853"/><path d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/><path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 6.29C4.672 4.163 6.656 3.58 9 3.58z" fill="#EA4335"/></svg>
                    {ar ? 'المتابعة بـ Google' : 'Continue with Google'}
                  </button>
                </form>
              ) : (
                <form onSubmit={handleSignup} style={{ display: 'grid', gap: 16 }}>
                  {/* Role badge */}
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', borderRadius: 10, background: 'var(--cream)', marginBottom: 2 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Icon name={form.role === 'vendor' ? 'store' : 'user'} size={16} style={{ color: 'var(--gold-deep)' }} />
                      <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-primary)', fontFamily: 'var(--font-body)' }}>
                        {form.role === 'vendor'
                          ? (ar ? 'حساب مورد' : 'Vendor Account')
                          : (ar ? 'حساب عميل' : 'Customer Account')}
                      </span>
                    </div>
                    <button type="button" onClick={() => { setTab('choose-type'); setError(''); }} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12, color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontWeight: 600, padding: 0 }}>
                      {ar ? 'تغيير' : 'Change'}
                    </button>
                  </div>
                  <Field label={ar ? 'الاسم الكامل' : 'Full Name'}>
                    <TextInput value={form.displayName} onChange={set('displayName')} required autoFocus />
                  </Field>
                  <Field label={ar ? 'البريد الإلكتروني' : 'Email'}>
                    <TextInput type="email" value={form.email} onChange={set('email')} required />
                  </Field>
                  <Field label={ar ? 'رقم الهاتف' : 'Phone'} hint={ar ? 'اختياري' : 'Optional'}>
                    <TextInput type="tel" value={form.phone} onChange={set('phone')} placeholder="+971 5X XXX XXXX" />
                  </Field>
                  <Field label={ar ? 'كلمة المرور' : 'Password'}>
                    <PasswordInput value={form.password} onChange={set('password')} required />
                  </Field>
                  <Field label={ar ? 'تأكيد كلمة المرور' : 'Confirm Password'}>
                    <PasswordInput value={form.confirmPassword} onChange={set('confirmPassword')} required />
                  </Field>
                  {form.role === 'vendor' && (
                    <div style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(193,160,70,0.08)', fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.55, display: 'flex', gap: 8 }}>
                      <Icon name="info" size={15} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 1 }} />
                      {ar
                        ? 'بعد إنشاء الحساب ستُكمل ملف شركتك، تختار باقة الاشتراك، وتُرفع الوثائق التجارية للمراجعة.'
                        : 'After account creation you will complete your business profile, choose a subscription package, and upload trade documents for review.'}
                    </div>
                  )}
                  {/* Terms & Privacy — required */}
                  <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
                    <input
                      type="checkbox"
                      checked={form.termsAccepted}
                      onChange={(e) => setForm((p) => ({ ...p, termsAccepted: e.target.checked }))}
                      style={{ marginTop: 3, flexShrink: 0, accentColor: 'var(--gold-deep)', width: 15, height: 15 }}
                    />
                    <span style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
                      {ar ? 'أوافق على ' : 'I agree to the '}
                      <button type="button" onClick={() => { onClose(); location.hash = '#terms'; }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontSize: 12.5, fontFamily: 'var(--font-body)', fontWeight: 600, padding: 0 }}>
                        {ar ? 'شروط الاستخدام' : 'Terms of Use'}
                      </button>
                      {ar ? ' و' : ' and '}
                      <button type="button" onClick={() => { onClose(); location.hash = '#privacy'; }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontSize: 12.5, fontFamily: 'var(--font-body)', fontWeight: 600, padding: 0 }}>
                        {ar ? 'سياسة الخصوصية' : 'Privacy Policy'}
                      </button>
                      {ar ? ' *' : ' *'}
                    </span>
                  </label>
                  {/* Marketing consent — optional */}
                  <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
                    <input
                      type="checkbox"
                      checked={form.marketingConsent}
                      onChange={(e) => setForm((p) => ({ ...p, marketingConsent: e.target.checked }))}
                      style={{ marginTop: 3, flexShrink: 0, accentColor: 'var(--gold-deep)', width: 15, height: 15 }}
                    />
                    <span style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
                      {ar
                        ? 'أوافق على تلقي التحديثات والعروض والمراسلات التسويقية من سرايا للفعاليات. (اختياري)'
                        : 'I agree to receive updates, offers, and marketing communications from Saraya Events. (Optional)'}
                    </span>
                  </label>
                  {error && <ErrorMsg>{error}</ErrorMsg>}
                  <Button variant="primary" full type="submit" disabled={busy}>
                    {busy ? (ar ? 'جارٍ الإنشاء...' : 'Creating...') : (ar ? 'إنشاء الحساب' : 'Create Account')}
                  </Button>
                </form>
              )}

              {/* Footer note */}
              {!success && (
                <p style={{ marginTop: 18, fontSize: 12, color: 'var(--fg-muted)', textAlign: 'center', lineHeight: 1.55 }}>
                  {ar
                    ? 'بالمتابعة توافق على '
                    : 'By continuing you agree to our '}
                  <button type="button" onClick={() => { onClose(); location.hash = '#terms'; }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontSize: 12, fontFamily: 'var(--font-body)', padding: 0 }}>
                    {ar ? 'شروط الاستخدام' : 'Terms of Use'}
                  </button>
                  {ar ? ' و' : ' and '}
                  <button type="button" onClick={() => { onClose(); location.hash = '#privacy'; }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontSize: 12, fontFamily: 'var(--font-body)', padding: 0 }}>
                    {ar ? 'سياسة الخصوصية' : 'Privacy Policy'}
                  </button>
                  {ar ? '. بياناتك تُستخدم فقط لتشغيل الحساب والتواصل معك.' : '. Your data is used only for account operation, order updates, and support.'}
                </p>
              )}
            </div>
          </>
        )}

        {/* Close */}
        <button onClick={onClose} style={{
          position: 'absolute', top: 16, insetInlineEnd: 16,
          background: 'none', border: 'none', cursor: 'pointer',
          color: 'var(--fg-secondary)', display: 'flex', padding: 6, borderRadius: 8,
        }}>
          <Icon name="x" size={20} />
        </button>
      </div>
    </div>
  );
}

/* -------- Password input with show/hide toggle -------- */
function PasswordInput({ value, onChange, required }) {
  const [show, setShow] = useStateAuth(false);
  return (
    <div style={{ position: 'relative' }}>
      <TextInput
        type={show ? 'text' : 'password'}
        value={value}
        onChange={onChange}
        required={required}
        style={{ paddingInlineEnd: 44 }}
      />
      <button
        type="button"
        onClick={() => setShow((p) => !p)}
        style={{
          position: 'absolute', insetInlineEnd: 12, top: '50%', transform: 'translateY(-50%)',
          background: 'none', border: 'none', cursor: 'pointer',
          color: 'var(--fg-secondary)', display: 'flex', padding: 4,
        }}
      >
        <Icon name={show ? 'eye-off' : 'eye'} size={17} />
      </button>
    </div>
  );
}

/* -------- Inline error message -------- */
function ErrorMsg({ children }) {
  return (
    <div style={{
      display: 'flex', gap: 8, alignItems: 'flex-start', padding: '10px 12px',
      borderRadius: 8, background: '#FEF2F2', color: '#B91C1C', fontSize: 13, lineHeight: 1.5,
    }}>
      <Icon name="alert-circle" size={15} style={{ flexShrink: 0, marginTop: 1 }} />
      {children}
    </div>
  );
}
window.ErrorMsg = ErrorMsg;

/* ============================================================
   VENDOR REGISTRATION STEP
   Shown after a vendor signs up — collects trade name and kicks off
   the document submission flow. Minimal for Phase 1.
   ============================================================ */
function VendorRegisterStep({ vendorUserId, onDone, ar }) {
  const db = window.SarayaDB;
  const [step, setStep] = useStateAuth('profile'); // 'profile' | 'package'
  const [savedUid, setSavedUid] = useStateAuth(null);
  const [form, setForm] = useStateAuth({ tradeName: '', tradeNameAr: '', phone: '', city: '' });
  const [busy, setBusy] = useStateAuth(false);
  const [error, setError] = useStateAuth('');
  const set = (k) => (e) => setForm((p) => ({ ...p, [k]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.tradeName.trim()) { setError(ar ? 'اسم الشركة مطلوب' : 'Business name is required'); return; }
    setBusy(true); setError('');
    const uid = vendorUserId || (db && (await db.auth.getUser()).data?.user?.id);
    if (!uid) { setError('Session expired — please log in again.'); setBusy(false); return; }
    const { error: err } = await db.from('vendor_profiles').insert({
      id: uid,
      trade_name: form.tradeName.trim(),
      trade_name_ar: form.tradeNameAr.trim() || null,
      whatsapp: form.phone.trim() || null,
      city: form.city.trim() || null,
      status: 'package_pending',
    });
    setBusy(false);
    if (err) { setError(err.message); return; }
    setSavedUid(uid);
    setStep('package');
  };

  if (step === 'package') {
    return <VendorPackageSelectStep uid={savedUid || vendorUserId} onDone={onDone} ar={ar} />;
  }

  return (
    <div style={{ padding: '32px 28px' }}>
      {/* Step indicator */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
        {[{ n: 1, label: ar ? 'ملف الشركة' : 'Business Profile' }, { n: 2, label: ar ? 'الباقة' : 'Package' }, { n: 3, label: ar ? 'الدفع' : 'Payment' }].map((s, i) => (
          <React.Fragment key={s.n}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: s.n === 1 ? 'var(--gold)' : 'var(--line)', color: s.n === 1 ? 'var(--espresso)' : 'var(--fg-muted)', fontSize: 12, fontWeight: 700 }}>{s.n}</div>
              <span style={{ fontSize: 10.5, color: s.n === 1 ? 'var(--gold-deep)' : 'var(--fg-muted)', fontWeight: s.n === 1 ? 700 : 400, whiteSpace: 'nowrap' }}>{s.label}</span>
            </div>
            {i < 2 && <div style={{ flex: 1, height: 1, background: 'var(--line)', marginBottom: 18 }} />}
          </React.Fragment>
        ))}
      </div>

      <div style={{ textAlign: 'center', marginBottom: 22 }}>
        <span style={{ display: 'inline-flex', width: 52, height: 52, borderRadius: 14, background: 'var(--cream)', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>
          <Icon name="store" size={26} style={{ color: 'var(--gold-deep)' }} />
        </span>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginBottom: 4 }}>
          {ar ? 'أخبرنا عن شركتك' : 'Tell Us About Your Business'}
        </h2>
        <p style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
          {ar ? 'يمكنك إضافة مزيد من التفاصيل لاحقاً.' : 'You can add more details from your dashboard later.'}
        </p>
      </div>
      <form onSubmit={handleSubmit} style={{ display: 'grid', gap: 14 }}>
        <Field label={ar ? 'اسم الشركة (إنجليزي)' : 'Business Name (English)'}>
          <TextInput value={form.tradeName} onChange={set('tradeName')} required autoFocus placeholder="e.g. Al Noor Flowers" />
        </Field>
        <Field label={ar ? 'اسم الشركة (عربي)' : 'Business Name (Arabic)'} hint={ar ? 'اختياري' : 'Optional'}>
          <TextInput value={form.tradeNameAr} onChange={set('tradeNameAr')} placeholder="مثال: زهور النور" dir="rtl" />
        </Field>
        <Field label={ar ? 'رقم واتساب للتواصل' : 'WhatsApp Number'}>
          <TextInput type="tel" value={form.phone} onChange={set('phone')} placeholder="+971 5X XXX XXXX" />
        </Field>
        <Field label={ar ? 'المدينة' : 'City'}>
          <TextInput value={form.city} onChange={set('city')} placeholder="Abu Dhabi" />
        </Field>
        {error && <ErrorMsg>{error}</ErrorMsg>}
        <Button variant="primary" full type="submit" disabled={busy}>
          {busy ? (ar ? 'جارٍ الحفظ...' : 'Saving...') : (ar ? 'التالي — اختر الباقة' : 'Next — Choose Package')}
        </Button>
      </form>
    </div>
  );
}

/* ============================================================
   VENDOR PACKAGE SELECT STEP
   Shown after business profile is saved (status: package_pending).
   Updates DB to payment_pending, adds to cart, routes to checkout.
   ============================================================ */
function VendorPackageSelectStep({ uid, onDone, ar }) {
  const db = window.SarayaDB;
  const cart = window.useCart ? window.useCart() : null;
  const [busy, setBusy] = useStateAuth(false);
  const [error, setError] = useStateAuth('');

  const selectPackage = async (pkg) => {
    setBusy(true); setError('');
    if (db && uid) {
      const { error: err } = await db.from('vendor_profiles').update({
        selected_package: pkg.id,
        selected_package_price: pkg.price,
        status: 'payment_pending',
      }).eq('id', uid);
      if (err) { setError(err.message); setBusy(false); return; }
    }
    // Add to cart so vendor lands on checkout ready to pay
    if (cart) {
      cart.add({
        id: 'showroom-plan-' + pkg.id,
        isSubscription: true,
        digital: true,
        category: 'subscription',
        price: pkg.price,
        tone: 'champagne',
        name: {
          en: 'Virtual Showroom — ' + pkg.en + ' (AED ' + pkg.price + '/mo)',
          ar: 'المعرض الرقمي — ' + pkg.ar + ' (' + pkg.price + ' درهم/شهر)',
        },
      }, 1, null);
    }
    try { localStorage.setItem('saraya_pending_pkg', JSON.stringify(pkg)); } catch (_) {}
    setBusy(false);
    onDone && onDone();
    setTimeout(() => { location.hash = '#checkout'; }, 120);
  };

  return (
    <div className="saraya-modal-body" style={{ padding: '28px 28px 24px' }}>
      {/* Step indicator */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
        {[{ n: 1, label: ar ? 'ملف الشركة' : 'Business Profile' }, { n: 2, label: ar ? 'الباقة' : 'Package' }, { n: 3, label: ar ? 'الدفع' : 'Payment' }].map((s, i) => (
          <React.Fragment key={s.n}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: s.n === 1 ? 'var(--gold)' : s.n === 2 ? 'var(--gold)' : 'var(--line)', color: s.n <= 2 ? 'var(--espresso)' : 'var(--fg-muted)', fontSize: 12, fontWeight: 700 }}>
                {s.n === 1 ? <Icon name="check" size={14} /> : s.n}
              </div>
              <span style={{ fontSize: 10.5, color: s.n === 2 ? 'var(--gold-deep)' : 'var(--fg-muted)', fontWeight: s.n === 2 ? 700 : 400, whiteSpace: 'nowrap' }}>{s.label}</span>
            </div>
            {i < 2 && <div style={{ flex: 1, height: 1, background: i === 0 ? 'var(--gold)' : 'var(--line)', marginBottom: 18 }} />}
          </React.Fragment>
        ))}
      </div>

      <div style={{ textAlign: 'center', marginBottom: 20 }}>
        <span style={{ display: 'inline-flex', width: 48, height: 48, borderRadius: 13, background: 'var(--gold-tint)', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>
          <Icon name="briefcase" size={24} style={{ color: 'var(--gold-deep)' }} />
        </span>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginBottom: 4 }}>
          {ar ? 'اختر باقة الموردين' : 'Choose Your Vendor Package'}
        </h2>
        <p style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>
          {ar ? 'اختر الباقة المناسبة. يمكنك التغيير لاحقًا.' : 'Select the package that fits your business. You can change later.'}
        </p>
      </div>

      <div style={{ display: 'grid', gap: 11 }}>
        {VENDOR_PACKAGES_AUTH.map((pkg) => (
          <button key={pkg.id} onClick={() => !busy && selectPackage(pkg)} disabled={busy} style={{
            display: 'flex', alignItems: 'center', gap: 14, width: '100%', position: 'relative',
            padding: '14px 16px', borderRadius: 12, textAlign: 'start', cursor: busy ? 'default' : 'pointer',
            border: pkg.highlight ? '2px solid var(--gold)' : '1.5px solid var(--line)',
            background: pkg.highlight ? 'rgba(201,169,97,0.06)' : 'var(--white)',
            fontFamily: 'var(--font-body)', transition: 'box-shadow 140ms',
          }}>
            {pkg.badge && (
              <span style={{ position: 'absolute', top: -11, insetInlineEnd: 14, background: 'var(--gold)', color: 'var(--espresso)', padding: '2px 10px', borderRadius: 20, fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                {ar ? pkg.badge.ar : pkg.badge.en}
              </span>
            )}
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 5 }}>
                <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--fg-primary)' }}>{ar ? pkg.ar : pkg.en}</span>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, color: 'var(--gold-deep)' }}>
                  AED {pkg.price}<span style={{ fontSize: 11, fontWeight: 400, color: 'var(--fg-muted)' }}>/mo</span>
                </span>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px 14px' }}>
                {(ar ? pkg.features.ar : pkg.features.en).slice(0, 3).map((f, i) => (
                  <span key={i} style={{ fontSize: 12, color: 'var(--fg-secondary)' }}>• {f}</span>
                ))}
              </div>
            </div>
            <Icon name="chevron-right" size={17} style={{ color: 'var(--fg-muted)', flexShrink: 0, transform: ar ? 'scaleX(-1)' : 'none' }} />
          </button>
        ))}
      </div>

      {error && <ErrorMsg style={{ marginTop: 12 }}>{error}</ErrorMsg>}
      <p style={{ marginTop: 14, fontSize: 12, color: 'var(--fg-muted)', textAlign: 'center', lineHeight: 1.55 }}>
        {ar
          ? 'يمكن تغيير الباقة لاحقًا من لوحة الموردين، وفقًا لشروط الفوترة.'
          : 'Package can be changed later from your vendor dashboard, subject to billing terms.'}
      </p>
    </div>
  );
}

/* -------- Auth trigger button (used in header) -------- */
function AuthTrigger({ style }) {
  const { user, signOut, openAuthModal, role } = useAuth();
  const { lang } = useLang();
  const ar = lang === 'ar';
  const { go } = useNav();
  const [open, setOpen] = useStateAuth(false);
  const ref = useRefAuth(null);

  useEffectAuth(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  if (!window.supabaseConfigured) {
    return (
      <button disabled style={{
        display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 16px',
        borderRadius: 8, border: '1.5px solid var(--line)', background: 'transparent',
        color: 'var(--fg-muted)', fontFamily: 'var(--font-body)', fontSize: 13.5,
        fontWeight: 600, cursor: 'not-allowed', opacity: 0.5, ...style,
      }} title="Supabase not configured">
        <Icon name="log-in" size={15} />
        {ar ? 'دخول' : 'Sign In'}
      </button>
    );
  }

  if (!user) {
    return (
      <button onClick={() => openAuthModal('login')} style={{
        display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 16px',
        borderRadius: 8, border: '1.5px solid var(--gold)', background: 'transparent',
        color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontSize: 13.5,
        fontWeight: 600, cursor: 'pointer', transition: 'background 160ms', ...style,
      }}>
        <Icon name="log-in" size={15} />
        {ar ? 'دخول' : 'Sign In'}
      </button>
    );
  }

  const initials = (user.email || 'U')[0].toUpperCase();

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen((p) => !p)}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          background: 'var(--cream)', border: '1.5px solid var(--line)',
          borderRadius: 22, padding: '5px 12px 5px 5px', cursor: 'pointer',
          fontFamily: 'var(--font-body)', fontSize: 13.5, ...style,
        }}
      >
        <span style={{
          display: 'inline-flex', width: 30, height: 30, borderRadius: '50%',
          alignItems: 'center', justifyContent: 'center',
          background: 'var(--gold)', color: 'var(--white)',
          fontWeight: 700, fontSize: 13,
        }}>{initials}</span>
        <Icon name="chevron-down" size={14} style={{ color: 'var(--fg-secondary)' }} />
      </button>

      {open && (
        <div style={{
          position: 'absolute', insetInlineEnd: 0, top: 'calc(100% + 8px)',
          background: 'var(--white)', borderRadius: 12, border: '1px solid var(--line)',
          boxShadow: 'var(--shadow-deep)', minWidth: 200, zIndex: 250, overflow: 'hidden',
        }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line)' }}>
            <p style={{ fontWeight: 600, fontSize: 13.5, margin: 0 }}>{user.email}</p>
            <p style={{ fontSize: 12, color: 'var(--fg-secondary)', margin: '2px 0 0', textTransform: 'capitalize' }}>{role}</p>
          </div>
          {(role === 'vendor') && (
            <MenuLink icon="layout-dashboard" label={ar ? 'لوحة البائع' : 'Vendor Dashboard'} onClick={() => { go('vendor-dashboard'); setOpen(false); }} />
          )}
          {(role === 'admin') && (
            <MenuLink icon="shield" label={ar ? 'لوحة الإدارة' : 'Admin Dashboard'} onClick={() => { go('admin-dashboard'); setOpen(false); }} />
          )}
          <MenuLink icon="package" label={ar ? 'طلباتي' : 'My Orders'} onClick={() => { go('my-orders'); setOpen(false); }} />
          <div style={{ borderTop: '1px solid var(--line)' }}>
            <MenuLink icon="log-out" label={ar ? 'خروج' : 'Sign Out'} onClick={() => { signOut(); setOpen(false); }} danger />
          </div>
        </div>
      )}
    </div>
  );
}
window.AuthTrigger = AuthTrigger;

function MenuLink({ icon, label, onClick, danger }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10,
      width: '100%', padding: '11px 16px', background: 'none', border: 'none',
      cursor: 'pointer', textAlign: 'start', fontSize: 13.5,
      fontFamily: 'var(--font-body)',
      color: danger ? '#B91C1C' : 'var(--fg-primary)',
      transition: 'background 120ms',
    }}
    onMouseEnter={(e) => { e.currentTarget.style.background = danger ? '#FEF2F2' : 'var(--bg-tint)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.background = 'none'; }}
    >
      <Icon name={icon} size={16} style={{ flexShrink: 0 }} />
      {label}
    </button>
  );
}
