﻿// Saraya Events — site chrome: Header, Footer, Floating WhatsApp,
// Quick-actions bar, and the inquiry Tray drawer.

const { useState: useStateC, useEffect: useEffectC, useContext: useContextC } = React;

function useNav() { return useContextC(window.NavContext); }
function useInquiry() { return useContextC(window.InquiryContext); }

/* Navigation source: when running inside WordPress, header.php emits
   window.__sarayaMenu from the live WP Main Menu (label/route/key) and the
   header renders exactly that — so add / remove / reorder / hide in WordPress
   controls the site header. Outside WordPress it falls back to the built-in nav. */
function navItems() {
  if (Array.isArray(window.__sarayaMenu) && window.__sarayaMenu.length) return window.__sarayaMenu;
  return window.SARAYA.NAV;
}
function navLabel(n, t) {
  // The WordPress menu title is the source of truth — show exactly what's typed.
  // Only when an item is left at its default (or has no label) do we use the
  // built-in bilingual EN/AR label so Arabic still localises.
  if (n.key) {
    var I = window.SARAYA && window.SARAYA.I18N;
    var defEn = (I && I.en) ? I.en['nav.' + n.key] : null;
    var loc = t('nav.' + n.key);
    var hasLoc = loc && loc !== 'nav.' + n.key;
    if (!n.label || n.label === defEn) return hasLoc ? loc : (n.label || n.route || '');
    return n.label; // user customised the menu label — honour it verbatim
  }
  return n.label || (n.route || '');
}

/* ---------- Language toggle ---------- */
function LangToggle({ onDark }) {
  const { lang, setLang } = useLang();
  const next = lang === 'en' ? 'ar' : 'en';
  const col = onDark ? 'var(--ivory)' : 'var(--fg-primary)';
  return (
    <button onClick={() => setLang(next)} aria-label="Switch language" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, background: 'transparent',
      border: '1px solid ' + (onDark ? 'rgba(250,246,240,0.4)' : 'var(--line-strong)'),
      borderRadius: 999, padding: '7px 13px', cursor: 'pointer', color: col,
      fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 500, letterSpacing: '0.04em',
    }}>
      <Icon name="languages" size={15} />
      {lang === 'en' ? 'العربية' : 'English'}
    </button>
  );
}

/* ---------- Header auth buttons ---------- */
function HeaderAuthButtons({ onDark, onClose }) {
  const { t } = useLang();
  const auth = window.useAuth ? window.useAuth() : null;
  if (!auth || !window.supabaseConfigured) return null;

  if (auth.user) {
    return <AuthTrigger />;
  }

  const h = 36; // uniform button height
  const btnBase = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    height: h, padding: '0 15px', borderRadius: 8, cursor: 'pointer',
    fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 500,
    transition: 'all 160ms', whiteSpace: 'nowrap',
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <button
        onClick={() => { auth.openAuthModal('login'); onClose && onClose(); }}
        style={{
          ...btnBase,
          background: 'transparent',
          border: '1.5px solid ' + (onDark ? 'rgba(250,246,240,0.45)' : 'rgba(110,90,70,0.35)'),
          color: onDark ? 'var(--ivory)' : 'var(--fg-primary)',
        }}
      >
        {t('cta.signIn')}
      </button>
      <button
        onClick={() => { auth.openAuthModal('signup'); onClose && onClose(); }}
        style={{
          ...btnBase,
          background: 'var(--gold)',
          color: 'var(--espresso)',
          fontWeight: 700,
          border: 'none',
        }}
      >
        {t('cta.createAccount')}
      </button>
    </div>
  );
}

/* ---------- Header ---------- */
function Header() {
  const { t, lang } = useLang();
  const { route, go } = useNav();
  const { count, openTray } = useInquiry();
  const [scrolled, setScrolled] = useStateC(false);
  const [menu, setMenu] = useStateC(false);
  const auth = window.useAuth ? window.useAuth() : null;
  const ar = lang === 'ar';
  const overHero = route === 'home';

  useEffectC(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll(); window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffectC(() => { setMenu(false); }, [route]);

  const solid = scrolled || !overHero || menu;
  const linkColor = solid ? 'var(--fg-primary)' : 'var(--ivory)';
  const iconColor = solid ? 'var(--fg-secondary)' : 'rgba(250,246,240,0.85)';

  return (
    <>
      <header style={{
        position: 'fixed', top: 0, insetInline: 0, zIndex: 90,
        transition: 'background 300ms var(--ease-out), box-shadow 300ms var(--ease-out)',
        background: solid ? 'rgba(250,246,240,0.95)' : 'transparent',
        backdropFilter: solid ? 'blur(20px)' : 'none', WebkitBackdropFilter: solid ? 'blur(20px)' : 'none',
        borderBottom: solid ? '1px solid rgba(110,90,70,0.12)' : '1px solid transparent',
        boxShadow: solid ? '0 2px 20px rgba(42,31,26,0.06)' : 'none',
      }}>
        <Container wide style={{ display: 'flex', alignItems: 'center', gap: 0, height: 72 }}>

          {/* Logo */}
          <button onClick={() => go('home')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', flexShrink: 0, marginInlineEnd: 32 }}>
            <span style={{ filter: solid ? 'none' : 'brightness(0) invert(1)', transition: 'filter 300ms' }}>
              <Logo height={44} />
            </span>
          </button>

          {/* Desktop nav — center */}
          <nav className="saraya-desktop-nav" style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 2, justifyContent: 'center' }}>
            {navItems().map((n, i) => {
              const active = route === n.route
                || (n.route === 'services' && route.startsWith('service-'))
                || route.startsWith(n.route + '/');
              return (
                <button key={(n.route || n.key || '') + i} onClick={() => go(n.route)} className="saraya-navlink" style={{
                  background: 'none', border: 'none', cursor: 'pointer', padding: '8px 11px',
                  fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: active ? 600 : 400,
                  color: linkColor, position: 'relative', letterSpacing: '0.01em', whiteSpace: 'nowrap',
                }}>
                  {navLabel(n, t)}
                  <span style={{
                    position: 'absolute', insetInline: 11, bottom: 3, height: 1.5,
                    background: 'var(--gold)', borderRadius: 2,
                    transform: active ? 'scaleX(1)' : 'scaleX(0)',
                    transformOrigin: 'center', transition: 'transform 220ms var(--ease-out)',
                  }} />
                </button>
              );
            })}
          </nav>

          {/* Desktop right controls */}
          <div className="saraya-desktop-nav" style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, marginInlineStart: 20 }}>
            <LangToggle onDark={!solid} />
            {count > 0 && (
              <button onClick={openTray} aria-label="Inquiry list" style={{
                position: 'relative', background: 'none', border: 'none', cursor: 'pointer',
                color: iconColor, display: 'flex', alignItems: 'center', padding: '6px 8px', borderRadius: 8,
              }}>
                <Icon name="clipboard-list" size={20} />
                <span style={{ position: 'absolute', top: 2, insetInlineEnd: 2, minWidth: 16, height: 16, padding: '0 3px', borderRadius: 999, background: 'var(--gold)', color: 'var(--espresso)', fontSize: 10, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{count}</span>
              </button>
            )}
            <CartButton onDark={!solid} />
            {auth && auth.user && window.NotificationBell && <window.NotificationBell />}
            <div style={{ width: 1, height: 22, background: solid ? 'rgba(110,90,70,0.18)' : 'rgba(250,246,240,0.25)', marginInline: 2 }} />
            <HeaderAuthButtons onDark={!solid} />
          </div>

          {/* Mobile controls */}
          <div className="saraya-mobile-nav" style={{ marginInlineStart: 'auto', alignItems: 'center', gap: 4 }}>
            <CartButton onDark={!solid} />
            {count > 0 && (
              <button onClick={openTray} aria-label="Inquiry list" style={{ position: 'relative', background: 'none', border: 'none', cursor: 'pointer', color: iconColor, display: 'flex', padding: '6px 7px' }}>
                <Icon name="clipboard-list" size={22} />
                <span style={{ position: 'absolute', top: 2, insetInlineEnd: 1, minWidth: 15, height: 15, borderRadius: 999, background: 'var(--gold)', color: 'var(--espresso)', fontSize: 9.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{count}</span>
              </button>
            )}
            <button onClick={() => setMenu(!menu)} aria-label={menu ? 'Close menu' : 'Open menu'} style={{ background: 'none', border: 'none', cursor: 'pointer', color: linkColor, display: 'flex', padding: '6px 4px' }}>
              <Icon name={menu ? 'x' : 'menu'} size={26} />
            </button>
          </div>

        </Container>
      </header>

      {/* Mobile drawer */}
      {menu && (
        <div className="saraya-mobile-nav" style={{
          position: 'fixed', inset: '72px 0 0', zIndex: 89,
          background: 'var(--bg-canvas)', overflowY: 'auto', flexDirection: 'column',
        }}>
          {/* Nav links */}
          <nav style={{ borderBottom: '1px solid var(--line)' }}>
            {navItems().map((n, i) => (
              <button key={(n.route || n.key || '') + i} onClick={() => go(n.route)} style={{
                display: 'flex', alignItems: 'center', width: '100%',
                background: 'none', border: 'none', borderBottom: '1px solid var(--line)',
                textAlign: 'start', cursor: 'pointer', padding: '16px var(--page-gutter)',
                fontFamily: 'var(--font-display)', fontSize: 22,
                color: route === n.route ? 'var(--gold-deep)' : 'var(--fg-primary)',
              }}>
                {navLabel(n, t)}
              </button>
            ))}
            {/* Request Quote in mobile nav */}
            <button onClick={() => go('design')} style={{
              display: 'flex', alignItems: 'center', gap: 10, width: '100%',
              background: 'none', border: 'none', borderBottom: '1px solid var(--line)',
              textAlign: 'start', cursor: 'pointer', padding: '16px var(--page-gutter)',
              fontFamily: 'var(--font-display)', fontSize: 22,
              color: route === 'design' ? 'var(--gold-deep)' : 'var(--fg-primary)',
            }}>
              {ar ? 'اطلب عرض سعر' : 'Request Quote'}
            </button>
            {/* Contact in mobile nav */}
            <button onClick={() => go('contact')} style={{
              display: 'flex', alignItems: 'center', gap: 10, width: '100%',
              background: 'none', border: 'none', borderBottom: '1px solid var(--line)',
              textAlign: 'start', cursor: 'pointer', padding: '16px var(--page-gutter)',
              fontFamily: 'var(--font-display)', fontSize: 22,
              color: route === 'contact' ? 'var(--gold-deep)' : 'var(--fg-primary)',
            }}>
              {ar ? 'اتصل بنا' : 'Contact'}
            </button>
          </nav>

          {/* Auth CTA area */}
          <div style={{ padding: '20px var(--page-gutter)' }}>
            {auth && window.supabaseConfigured ? (
              auth.user ? (
                <div style={{ padding: '4px 0 8px' }}>
                  <AuthTrigger />
                </div>
              ) : (
                <div style={{ display: 'grid', gap: 10 }}>
                  <button onClick={() => { auth.openAuthModal('signup'); setMenu(false); }} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    padding: '14px 20px', borderRadius: 10, background: 'var(--gold)',
                    color: 'var(--espresso)', fontFamily: 'var(--font-body)', fontSize: 15,
                    fontWeight: 700, border: 'none', cursor: 'pointer',
                  }}>
                    <Icon name="user-plus" size={17} />
                    {t('cta.createAccount')}
                  </button>
                  <button onClick={() => { auth.openAuthModal('login'); setMenu(false); }} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    padding: '13px 20px', borderRadius: 10, background: 'transparent',
                    color: 'var(--fg-primary)', fontFamily: 'var(--font-body)', fontSize: 15,
                    fontWeight: 500, border: '1.5px solid var(--line-strong)', cursor: 'pointer',
                  }}>
                    <Icon name="log-in" size={17} />
                    {t('cta.signIn')}
                  </button>
                </div>
              )
            ) : null}
          </div>

          {/* Bottom bar */}
          <div style={{ padding: '0 var(--page-gutter) 32px', display: 'flex', gap: 10 }}>
            <Button variant="whatsapp" icon="message-circle" full href={window.SARAYA.waLink("Hello Saraya Events, I'd like to enquire.")}>{t('cta.whatsapp')}</Button>
            <LangToggle />
          </div>
        </div>
      )}
    </>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const { t, lang } = useLang();
  const { go } = useNav();
  const C = window.SARAYA.CONTACT;
  const auth = window.useAuth ? window.useAuth() : null;
  const ar = lang === 'ar';

  const openAuth = (mode) => auth && window.supabaseConfigured ? auth.openAuthModal(mode) : go('home');

  return (
    <footer style={{ background: 'var(--espresso)', color: 'var(--ivory)', paddingBlock: '72px 36px' }}>
      <Container wide>
        <div className="saraya-footer-grid" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit,minmax(190px,1fr))',
          gap: '40px 28px', alignItems: 'start',
        }}>

          {/* Col 1 — Brand */}
          <div>
            <span style={{ filter: 'brightness(0) invert(1)', display: 'inline-block' }}><Logo height={52} /></span>
            <p style={{ marginTop: 16, fontSize: 14, lineHeight: 1.75, color: 'rgba(250,246,240,0.68)', maxWidth: 240 }}>
              {ar
                ? 'منصة سرايا الفاخرة للمناسبات والخدمات والتأجير في الإمارات.'
                : 'Luxury event marketplace across the UAE.'}
            </p>
            <div style={{ marginTop: 20 }}><OrnamentRule width={100} /></div>
            {/* Social */}
            <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
              <a href={'https://wa.me/' + C.phoneIntl} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, borderRadius: 8, background: 'rgba(250,246,240,0.08)', color: 'rgba(250,246,240,0.75)', textDecoration: 'none', transition: 'background 160ms' }}>
                <Icon name="message-circle" size={17} />
              </a>
              <a href={'mailto:' + C.email} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, borderRadius: 8, background: 'rgba(250,246,240,0.08)', color: 'rgba(250,246,240,0.75)', textDecoration: 'none', transition: 'background 160ms' }}>
                <Icon name="mail" size={17} />
              </a>
              <a href="https://www.instagram.com/saraya.evt/" target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, borderRadius: 8, background: 'rgba(250,246,240,0.08)', color: 'rgba(250,246,240,0.75)', textDecoration: 'none', transition: 'background 160ms' }}>
                <span style={{ display: 'inline-flex', width: 17, height: 17, color: 'inherit' }}><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line></svg></span>
              </a>
            </div>
          </div>

          {/* Col 2 — Marketplace */}
          <div>
            <FooterHead>{ar ? 'السوق' : 'Marketplace'}</FooterHead>
            <FooterLink onClick={() => go('home')}>{ar ? 'الرئيسية' : 'Home'}</FooterLink>
            <FooterLink onClick={() => go('store')}>{ar ? 'السوق' : 'Marketplace'}</FooterLink>
            <FooterLink onClick={() => go('rental')}>{ar ? 'التأجير' : 'Rentals'}</FooterLink>
            <FooterLink onClick={() => go('services')}>{ar ? 'الخدمات' : 'Services'}</FooterLink>
                        <FooterLink onClick={() => go('design')} icon="pen-line">{ar ? 'اطلب عرض سعر' : 'Request Quote'}</FooterLink>
          </div>

          {/* Col 3 — Vendors & Account */}
          <div>
            <FooterHead>{ar ? 'الموردون' : 'Vendors'}</FooterHead>
            <FooterLink icon="store" onClick={() => window.openJoinVendorModal ? window.openJoinVendorModal() : go('partner')}>{ar ? 'انضم كمورد' : 'Join as Vendor'}</FooterLink>
            <FooterLink icon="layout-panel-left" onClick={() => go('showroom')}>{ar ? 'المعرض الرقمي' : 'Virtual Showroom'}</FooterLink>
            <FooterLink icon="log-in" onClick={() => openAuth('login')}>{ar ? 'دخول الموردين' : 'Vendor Login'}</FooterLink>
            <FooterLink icon="layout-dashboard" onClick={() => go('vendor-dashboard')}>{ar ? 'لوحة التحكم' : 'Vendor Dashboard'}</FooterLink>
            <FooterLink icon="briefcase" onClick={() => go('vendor-packages')}>{ar ? 'باقات الموردين' : 'Vendor Packages'}</FooterLink>
            <FooterLink icon="handshake" onClick={() => go('vendor-agreement')}>{ar ? 'اتفاقية الموردين' : 'Vendor Agreement'}</FooterLink>
            <div style={{ height: 16 }} />
            <FooterHead>{ar ? 'حسابي' : 'Account'}</FooterHead>
            {auth && window.supabaseConfigured && auth.user ? (
              <>
                {auth.isAdmin && <FooterLink icon="shield" onClick={() => go('admin-dashboard')}>{ar ? 'لوحة الإدارة' : 'Admin Dashboard'}</FooterLink>}
                <FooterLink icon="package" onClick={() => go('my-orders')}>{ar ? 'طلباتي' : 'My Orders'}</FooterLink>
                <FooterLink icon="log-out" onClick={() => auth.signOut()}>{ar ? 'تسجيل الخروج' : 'Sign Out'}</FooterLink>
              </>
            ) : (
              <>
                <FooterLink icon="log-in" onClick={() => openAuth('login')}>{ar ? 'تسجيل الدخول' : 'Customer Login'}</FooterLink>
                <FooterLink icon="user-plus" onClick={() => openAuth('signup')}>{ar ? 'إنشاء حساب' : 'Create Account'}</FooterLink>
              </>
            )}
          </div>

          {/* Col 4 — Legal & Contact */}
          <div>
            <FooterHead>{ar ? 'قانوني' : 'Legal'}</FooterHead>
            <FooterLink icon="file-text" onClick={() => go('terms')}>{ar ? 'شروط الاستخدام' : 'Terms & Conditions'}</FooterLink>
            <FooterLink icon="shield-check" onClick={() => go('privacy')}>{ar ? 'سياسة الخصوصية' : 'Privacy Policy'}</FooterLink>
            <FooterLink icon="rotate-ccw" onClick={() => go('cancellation-refund')}>{ar ? 'سياسة الإلغاء والاسترداد' : 'Cancellation & Refund Policy'}</FooterLink>
            <FooterLink icon="message-square-warning" onClick={() => go('complaints')}>{ar ? 'الشكاوى والنزاعات' : 'Complaints & Disputes'}</FooterLink>
            <FooterLink icon="store" onClick={() => go('vendor-terms')}>{ar ? 'شروط الموردين' : 'Vendor Terms'}</FooterLink>
            <FooterLink icon="user" onClick={() => go('customer-terms')}>{ar ? 'شروط العملاء' : 'Customer Terms'}</FooterLink>
            <div style={{ height: 16 }} />
            <FooterHead>{ar ? 'تواصل' : 'Contact'}</FooterHead>
            <FooterLink icon="map-pin">{C.city}</FooterLink>
            <FooterLink href={window.SARAYA.waLink('Hello Saraya Events')} icon="message-circle">{ar ? 'واتساب' : 'WhatsApp'}</FooterLink>
            <FooterLink href={'mailto:' + C.email} icon="mail">{C.email}</FooterLink>
            <FooterLink icon="headset" href={'mailto:' + C.email}>{ar ? 'دعم العملاء' : 'Contact Support'}</FooterLink>
          </div>

        </div>

        {/* Bottom bar */}
        <div style={{ marginTop: 52, paddingTop: 20, borderTop: '1px solid rgba(250,246,240,0.12)', display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, color: 'rgba(250,246,240,0.48)' }}>
          <span>{'© ' + new Date().getFullYear() + ' Saraya Events · سرايا للفعاليات. ' + t('footer.rights')}</span>
          <span style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
            <span>{C.city}</span>
            <AdminFooterLink />
          </span>
        </div>
      </Container>
    </footer>
  );
}
function FooterHead({ children }) {
  return <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--gold-light)', marginBottom: 16 }}>{children}</div>;
}
/* Discreet admin access — opens the login (or jumps straight in if already logged in). */
function AdminFooterLink() {
  const admin = window.useAdmin ? window.useAdmin() : null;
  if (!admin) return null;
  return (
    <button onClick={() => (admin.isAdmin ? admin.setEditMode(true) : admin.openLogin())} className="saraya-admin-access"
      style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(250,246,240,0.55)', fontFamily: 'var(--font-body)', fontSize: 12.5 }}>
      <Icon name="lock" size={12} /> {admin.isAdmin ? 'Editor' : 'Site editor'}
    </button>
  );
}
function FooterLink({ children, onClick, href, icon }) {
  const Comp = href ? 'a' : 'button';
  return (
    <Comp href={href} onClick={onClick} className="saraya-footlink" style={{
      display: 'flex', alignItems: 'center', gap: 9, background: 'none', border: 'none', cursor: 'pointer',
      textAlign: 'start', padding: '6px 0', fontFamily: 'var(--font-body)', fontSize: 14,
      color: 'rgba(250,246,240,0.75)', textDecoration: 'none', width: '100%',
    }}>
      {icon && <Icon name={icon} size={15} style={{ color: 'var(--gold-light)', flexShrink: 0 }} />}
      <span>{children}</span>
    </Comp>
  );
}

/* ---------- Floating WhatsApp + quick actions ---------- */
function FloatingWhatsApp() {
  const { t } = useLang();
  const [open, setOpen] = useStateC(false);
  const C = window.SARAYA.CONTACT;
  const actions = [
    { icon: 'calendar-check', label: t('cta.consult'), msg: "Hello Saraya Events, I'd like to book a consultation for my event." },
    { icon: 'tag', label: t('cta.price'), msg: 'Hello Saraya Events, could you share pricing for my event?' },
    { icon: 'image', label: t('cta.inspo'), msg: "Hello Saraya Events, I'd like to share some inspiration photos for my event." },
    { icon: 'gift', label: t('cta.package'), msg: 'Hello Saraya Events, which package would suit my event?' },
  ];
  return (
    <div style={{ position: 'fixed', insetInlineEnd: 18, bottom: 18, zIndex: 80, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 12 }}>
      {open && actions.map((a, i) => (
        <a key={i} href={window.SARAYA.waLink(a.msg)} target="_blank" rel="noopener" style={{
          display: 'inline-flex', alignItems: 'center', gap: 10, background: 'var(--white)', color: 'var(--fg-primary)',
          padding: '10px 16px', borderRadius: 999, boxShadow: 'var(--shadow-lift)', textDecoration: 'none',
          fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 500, border: '1px solid var(--line)',
          animation: 'sarayaPop 280ms var(--ease-out) backwards', animationDelay: (i * 45) + 'ms',
        }}>
          <Icon name={a.icon} size={17} style={{ color: 'var(--gold-deep)' }} />{a.label}
        </a>
      ))}
      <button onClick={() => setOpen(!open)} aria-label="WhatsApp" style={{
        width: 60, height: 60, borderRadius: 999, border: 'none', cursor: 'pointer', background: '#1FA855',
        color: '#fff', boxShadow: '0 8px 24px rgba(31,168,85,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'transform 200ms var(--ease-out)', transform: open ? 'rotate(90deg)' : 'none',
      }}>
        <Icon name={open ? 'x' : 'message-circle'} size={28} stroke={2} />
      </button>
    </div>
  );
}

/* ---------- Inquiry Tray drawer ---------- */
function InquiryTray() {
  const { t, lang } = useLang();
  const { items, remove, clear, isOpen, closeTray } = useInquiry();
  const ar = lang === 'ar';
  if (!isOpen) return null;
  const lines = items.map((it) => `• ${it.name[lang] || it.name.en}`).join('\n');
  const msg = `Hello Saraya Events, I'd like to enquire about these pieces:\n${lines}\n\nPlease share availability and pricing.`;
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 120, display: 'flex', justifyContent: lang === 'ar' ? 'flex-start' : 'flex-end' }}>
      <div onClick={closeTray} style={{ position: 'absolute', inset: 0, background: 'var(--scrim)', animation: 'sarayaFade 200ms ease' }} />
      <aside style={{ position: 'relative', width: 'min(420px,100%)', height: '100%', background: 'var(--bg-canvas)', boxShadow: 'var(--shadow-deep)', display: 'flex', flexDirection: 'column', animation: 'sarayaSlideIn 320ms var(--ease-out)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '22px 24px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>{t('tray.title')}</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>{items.length} {t('tray.items')}</div>
          </div>
          <button onClick={closeTray} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', display: 'flex', padding: 4 }}><Icon name="x" size={24} /></button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 24px' }}>
          {items.length === 0 ? (
            <p style={{ color: 'var(--fg-muted)', fontSize: 14.5, marginTop: 24, textAlign: 'center' }}>{t('tray.empty')}</p>
          ) : items.map((it) => (
            <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderBottom: '1px solid var(--line)' }}>
              <Img tone={it.tone} icon="sparkles" ratio="1/1" radius={10} label="" style={{ width: 56, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 17, fontWeight: 500 }}>{it.name[lang] || it.name.en}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{it.categoryName ? (it.categoryName[lang] || it.categoryName.en) : ''}</div>
              </div>
              <button onClick={() => remove(it.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', padding: 4 }}><Icon name="trash-2" size={17} /></button>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div style={{ padding: '18px 24px', borderTop: '1px solid var(--line)', display: 'grid', gap: 10 }}>
            <Button variant="whatsapp" icon="message-circle" full href={window.SARAYA.waLink(msg)} target="_blank">{t('tray.cta')}</Button>
            <button onClick={clear} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', fontFamily: 'var(--font-body)', fontSize: 13 }}>{ar ? 'مسح القائمة' : 'Clear list'}</button>
          </div>
        )}
      </aside>
    </div>
  );
}

/* ---------- Join as Vendor Modal ---------- */
function JoinVendorModal() {
  const [open, setOpen] = useStateC(false);
  const { go } = useNav();
  const { lang } = useLang();
  const auth = window.useAuth ? window.useAuth() : null;
  const ar = lang === 'ar';
  const C = window.SARAYA.CONTACT;

  useEffectC(() => {
    window.openJoinVendorModal = () => setOpen(true);
    return () => { window.openJoinVendorModal = null; };
  }, []);

  if (!open) return null;

  const close = () => setOpen(false);
  const handle = (fn) => { close(); fn(); };

  const options = [
    {
      icon: 'user-plus',
      color: 'var(--gold)',
      en: 'Create Your Account',
      ar: 'إنشاء حسابك',
      sub: { en: 'Sign up as a vendor and start listing', ar: 'سجّل كمورد وابدأ بالإدراج' },
      action: () => {
        if (auth && window.supabaseConfigured) auth.openAuthModal('signup');
        else go('partner');
      },
    },
    {
      icon: 'briefcase',
      color: 'var(--rose-deep)',
      en: 'View Vendor Packages',
      ar: 'عرض باقات الموردين',
      sub: { en: 'Compare Starter, Pro & Premium tiers', ar: 'قارن بين الباقات الثلاث' },
      action: () => go('vendor-packages'),
    },
    {
      icon: 'layout-panel-left',
      color: 'var(--fg-secondary)',
      en: 'Virtual Showroom',
      ar: 'المعرض الرقمي',
      sub: { en: 'See how your store page looks', ar: 'شاهد كيف تبدو صفحة معرضك' },
      action: () => go('showroom'),
    },
    {
      icon: 'message-circle',
      color: '#1FA855',
      en: 'Contact Our Team',
      ar: 'تواصل مع فريقنا',
      sub: { en: 'Chat with us on WhatsApp', ar: 'تحدث معنا عبر واتساب' },
      action: () => window.open(window.SARAYA.waLink('Hello Saraya Events, I am interested in joining as a vendor.'), '_blank'),
    },
  ];

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'var(--scrim)', animation: 'sarayaFade 200ms ease' }} />
      <div style={{
        position: 'relative', background: 'var(--bg-canvas)', borderRadius: 20,
        boxShadow: 'var(--shadow-deep)', padding: '36px 32px', width: '100%', maxWidth: 500,
        animation: 'sarayaPop 260ms var(--ease-out)',
      }}>
        <button onClick={close} style={{ position: 'absolute', top: 16, insetInlineEnd: 16, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', display: 'flex', padding: 6 }}>
          <Icon name="x" size={20} />
        </button>

        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ display: 'inline-flex', width: 52, height: 52, borderRadius: 14, background: 'var(--gold-tint)', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
            <Icon name="store" size={26} style={{ color: 'var(--gold-deep)' }} />
          </div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 500, margin: 0 }}>
            {ar ? 'انضم كمورد في سرايا' : 'Join as a Vendor'}
          </h2>
          <p style={{ fontSize: 14, color: 'var(--fg-muted)', marginTop: 6 }}>
            {ar ? 'اختر كيف تريد البدء' : 'Choose how you would like to get started'}
          </p>
        </div>

        <div style={{ display: 'grid', gap: 12 }}>
          {options.map((opt, i) => (
            <button key={i} onClick={() => handle(opt.action)} style={{
              display: 'flex', alignItems: 'center', gap: 16, width: '100%',
              background: 'var(--white)', border: '1.5px solid var(--line)',
              borderRadius: 14, padding: '16px 18px', cursor: 'pointer', textAlign: 'start',
              fontFamily: 'var(--font-body)', transition: 'border-color 160ms, box-shadow 160ms',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = opt.color; e.currentTarget.style.boxShadow = 'var(--shadow-soft)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; }}>
              <span style={{ display: 'inline-flex', width: 44, height: 44, borderRadius: 11, background: 'rgba(0,0,0,0.05)', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={opt.icon} size={22} style={{ color: opt.color }} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-primary)' }}>{ar ? opt.ar : opt.en}</div>
                <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 2 }}>{ar ? opt.sub.ar : opt.sub.en}</div>
              </div>
              <Icon name="chevron-right" size={18} style={{ color: 'var(--fg-muted)', flexShrink: 0 }} />
            </button>
          ))}
        </div>

        <p style={{ textAlign: 'center', fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 20, marginBottom: 0 }}>
          {ar ? 'لديك حساب بالفعل؟ ' : 'Already have an account? '}
          <button onClick={() => handle(() => auth && window.supabaseConfigured ? auth.openAuthModal('login') : go('vendor-dashboard'))} 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>
  );
}

Object.assign(window, { useNav, useInquiry, LangToggle, Header, Footer, FloatingWhatsApp, InquiryTray, JoinVendorModal });
