// Saraya Events — Virtual Showroom: a subscription service (AED 99/month) that
// lets businesses display their products & services in an online showroom.
// Native part of the site: same chrome, tokens, fonts, PageHero, Reveal, etc.
// Signup opens WhatsApp (per request). Admin can manage subscriptions.

const { useState: useStateShow, useEffect: useEffectShow } = React;

const SHOWROOM_WA = '971529692965';
const SHOWROOM_PRICE = window.VENDOR_PACKAGES_BY_ID.starter.price;

const showroomWa = (msg) => `https://wa.me/${SHOWROOM_WA}?text=${encodeURIComponent(msg)}`;

/* ---- Package options shown in the selection modal ---- */
const SHOWROOM_PACKAGES = [
  {
    id: 'starter',
    en: 'Starter Vendor',
    ar: 'مورد مبتدئ',
            price: window.VENDOR_PACKAGES_BY_ID.starter.price,
    highlight: false,
    badge: null,
    tagline: { en: 'For small vendors starting online', ar: 'للموردين الصغار الذين يبدأون أونلاين' },
    features: {
      en: [
        'Basic vendor profile page',
        'Display products and services',
        'Receive customer inquiries',
        'WhatsApp & contact button',
        'Suitable for small & home businesses',
      ],
      ar: [
        'صفحة مورد أساسية',
        'عرض المنتجات والخدمات',
        'استقبال استفسارات العملاء',
        'زر واتساب وتواصل',
        'مناسب للأعمال الصغيرة والمنزلية',
      ],
    },
    cta: { en: 'Continue with Starter', ar: 'المتابعة بالمبتدئ' },
  },
  {
    id: 'growth',
    en: 'Growth Vendor',
    ar: 'مورد النمو',
        price: window.VENDOR_PACKAGES_BY_ID.growth.price,
    highlight: true,
    badge: { en: 'Recommended', ar: 'موصى به' },
    tagline: { en: 'For active vendors wanting more visibility', ar: 'للموردين النشطين الذين يريدون مزيدًا من الظهور' },
    features: {
      en: [
        'More product & service listings',
        'Rental and service listing support',
        'RFQ access — receive quote requests',
        'Better marketplace visibility',
        'Basic performance insights',
      ],
      ar: [
        'قوائم منتجات وخدمات أكثر',
        'دعم قوائم الإيجار والخدمات',
        'وصول لطلبات عروض الأسعار',
        'ظهور أفضل في السوق',
        'إحصاءات أداء أساسية',
      ],
    },
    cta: { en: 'Continue with Growth', ar: 'المتابعة بالنمو' },
  },
  {
    id: 'premium',
    en: 'Premium Vendor',
    ar: 'مورد مميز',
        price: window.VENDOR_PACKAGES_BY_ID.premium.price,
    highlight: false,
    badge: null,
    tagline: { en: 'For larger vendors wanting maximum exposure', ar: 'للموردين الكبار الذين يريدون أقصى ظهور' },
    features: {
      en: [
        'Premium vendor profile with branding',
        'Featured placement eligibility',
        'Higher listing limits',
        'RFQ priority access',
        'Advanced visibility & dedicated support',
      ],
      ar: [
        'صفحة مورد مميزة مع هوية بصرية',
        'أهلية العرض المميز',
        'حدود قوائم أعلى',
        'أولوية في طلبات عروض الأسعار',
        'ظهور متقدم ودعم مخصص',
      ],
    },
    cta: { en: 'Continue with Premium', ar: 'المتابعة بالمميز' },
  },
];

/* ---- subscriptions store (localStorage) ---- */
const SUBS_KEY = 'saraya_subscriptions_v1';
const SubsAPI = {
  list() { try { return JSON.parse(localStorage.getItem(SUBS_KEY) || '[]'); } catch (e) { return []; } },
  _save(a) { localStorage.setItem(SUBS_KEY, JSON.stringify(a)); },
  create(s) {
    const a = SubsAPI.list();
    const full = Object.assign({ id: 'sub' + Date.now().toString(36), createdAt: new Date().toISOString(), status: 'active', payment: 'pending' }, s);
    a.unshift(full); SubsAPI._save(a); return full;
  },
  setStatus(id, status) { const a = SubsAPI.list(); const s = a.find((x) => x.id === id); if (s) { s.status = status; SubsAPI._save(a); } return s; },
  setPayment(id, payment) { const a = SubsAPI.list(); const s = a.find((x) => x.id === id); if (s) { s.payment = payment; SubsAPI._save(a); } return s; },
};
window.SubsAPI = SubsAPI;

/* ============================ PAGE ============================ */
function ShowroomPage() {
  const { t, lang } = useLang();
  const { go } = useNav();
  const admin = useAdmin();
  const cart = useCart();
  const auth = window.useAuth ? window.useAuth() : null;
  const ar = lang === 'ar';
  const formRef = React.useRef(null);
  const howRef = React.useRef(null);
  const [demoOpen, setDemoOpen] = useStateShow(false);
  const [pkgModalOpen, setPkgModalOpen] = useStateShow(false);
  const scrollTo = (ref) => { if (ref.current) { const y = ref.current.getBoundingClientRect().top + window.scrollY - 80; window.scrollTo({ top: y, behavior: 'smooth' }); } };

  // Subscribe with a selected package — adds to cart then routes to checkout (or signup if not logged in).
  const subscribe = (pkg) => {
    const plan = pkg || SHOWROOM_PACKAGES[0];
    localStorage.setItem('saraya_pending_pkg', JSON.stringify(plan));
    cart.add({
      id: 'showroom-plan-' + plan.id,
      isSubscription: true,
      digital: true,
      category: 'subscription',
      price: plan.price,
      tone: 'champagne',
      name: {
        en: 'Virtual Showroom — ' + plan.en + ' (AED ' + plan.price + '/mo)',
        ar: 'المعرض الرقمي — ' + plan.ar + ' (' + plan.price + ' درهم/شهر)',
      },
    }, 1, null);
    if (auth && auth.user) {
      go('checkout');
    } else if (auth && window.supabaseConfigured) {
      auth.openAuthModal('signup');
    } else {
      go('partner');
    }
  };

  return (
    <main>
      {/* ===== 1. HERO ===== */}
      <section style={{ position: 'relative', paddingTop: 132, paddingBottom: 'clamp(48px,6vw,80px)', background: 'var(--cream)', overflow: 'hidden' }}>
        <Img tone="champagne" icon="store" ratio="auto" radius={0} plain slot="showroom-hero" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.4 }} />
        <span style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, var(--bg-canvas) 4%, rgba(243,237,227,0.35) 100%)' }} />
        <Container wide style={{ position: 'relative' }}>
          <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'center' }}>
            <Reveal>
              <Badge tone="gold">{ar ? 'سوق الفعاليات الرقمي' : 'Event’s Digital Marketplace'}</Badge>
              <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(34px,5vw,60px)', lineHeight: 1.04, fontWeight: 500, letterSpacing: '-0.01em', marginTop: 18 }}>
                {ar ? 'عملك، أونلاين. مرئي. ويبيع.' : 'Your Business, Online. Visible. Selling.'}
              </h1>
              <p style={{ fontSize: 'clamp(16px,1.7vw,19px)', lineHeight: 1.6, color: 'var(--fg-secondary)', marginTop: 16, maxWidth: 520 }}>
                {ar ? 'اعرض منتجاتك وخدماتك في معرض رقمي أنيق ضمن منصة سرايا، واستقبل عملاءك عبر واتساب أو الطلب أونلاين.' : 'Display your products and services in an elegant online showroom on the Saraya platform — and receive customers via WhatsApp or online orders.'}
              </p>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 24, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-muted)', alignSelf: 'center' }}>{ar ? 'يبدأ من' : 'from'}</span>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(40px,6vw,60px)', fontWeight: 600, color: 'var(--gold-deep)', lineHeight: 1.05, whiteSpace: 'nowrap' }}>AED 99</span>
                <span style={{ fontSize: 18, color: 'var(--fg-secondary)' }}>/ {ar ? 'شهريًا' : 'month'}</span>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 24 }}>
                <Button variant="primary" size="lg" icon="rocket" onClick={() => setPkgModalOpen(true)}>{ar ? 'ابدأ العرض الآن' : 'Start Displaying Now'}</Button>
                <Button variant="secondary" size="lg" icon="briefcase" onClick={() => go('vendor-packages')}>{ar ? 'عرض الباقات' : 'View All Packages'}</Button>
              </div>
              <button onClick={() => window.openJoinVendorModal ? window.openJoinVendorModal() : go('partner')} style={{ marginTop: 14, display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--fg-secondary)', textDecoration: 'underline', textUnderlineOffset: 3, padding: 0 }}>
                <Icon name="store" size={14} />
                {ar ? 'انضم كمورد' : 'Join as Vendor'}
              </button>
            </Reveal>
            <Reveal delay={120}>
              <BrowserMock ar={ar} />
            </Reveal>
          </div>
        </Container>
      </section>

      {/* ===== VENDOR ECOSYSTEM BANNER ===== */}
      <Section bg="canvas">
        <Container wide>
          <Reveal>
            <div style={{ background: 'linear-gradient(135deg, var(--espresso) 0%, #3d2b1f 100%)', borderRadius: 20, padding: 'clamp(28px,4vw,48px) clamp(24px,4vw,48px)', color: 'var(--ivory)' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ maxWidth: 520 }}>
                  <Badge tone="gold" style={{ marginBottom: 12 }}>{ar ? 'جزء من منظومة الموردين' : 'Part of the Vendor Ecosystem'}</Badge>
                                    <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(22px,3vw,34px)', fontWeight: 500, margin: '12px 0 10px', color: 'var(--white)' }}>
                    {ar ? 'المعرض الرقمي + باقات الموردين = نمو حقيقي' : 'Virtual Showroom + Vendor Package = Real Growth'}
                  </h2>
                  <p style={{ fontSize: 14.5, color: 'rgba(250,246,240,0.75)', lineHeight: 1.65, marginBottom: 0 }}>
                    {ar
                      ? 'المعرض الرقمي هو صفحتك الشخصية داخل سوق سرايا. اختر الباقة التي تناسبك — سواء كنت مبتدئًا أو نمو أو مميزًا — وستحصل على إمكانية الوصول إلى السوق، والتأجير، والخدمات، وطلبات عروض الأسعار.'
                      : 'The Virtual Showroom is your personal page inside the Saraya marketplace. Pick the vendor package that fits your business — Starter, Growth, or Premium — and unlock access to Marketplace, Rentals, Services, and RFQ leads.'}
                  </p>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12, flexShrink: 0 }}>
                  <button onClick={() => go('vendor-packages')} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '13px 22px', borderRadius: 10, background: 'var(--gold)', color: 'var(--espresso)', fontFamily: 'var(--font-body)', fontSize: 14.5, fontWeight: 700, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                    <Icon name="briefcase" size={17} />
                    {ar ? 'عرض باقات الموردين' : 'View Vendor Packages'}
                  </button>
                  <button onClick={() => window.openJoinVendorModal ? window.openJoinVendorModal() : go('partner')} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '12px 22px', borderRadius: 10, background: 'transparent', color: 'var(--ivory)', fontFamily: 'var(--font-body)', fontSize: 14.5, fontWeight: 500, border: '1.5px solid rgba(250,246,240,0.35)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                    <Icon name="user-plus" size={17} />
                    {ar ? 'انضم كمورد' : 'Join as Vendor'}
                  </button>
                </div>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginTop: 24, paddingTop: 20, borderTop: '1px solid rgba(250,246,240,0.12)' }}>
                {[
                  { icon: 'shopping-bag', en: 'Marketplace listing', ar: 'قائمة في السوق' },
                  { icon: 'package', en: 'Rental catalogue', ar: 'كتالوج التأجير' },
                  { icon: 'sparkles', en: 'Services directory', ar: 'دليل الخدمات' },
                  { icon: 'file-text', en: 'RFQ leads', ar: 'طلبات عروض الأسعار' },
                  { icon: 'layout-panel-left', en: 'Virtual Showroom page', ar: 'صفحة المعرض الرقمي' },
                ].map((item, i) => (
                  <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 14px', background: 'rgba(250,246,240,0.09)', borderRadius: 999, fontSize: 13, color: 'rgba(250,246,240,0.85)' }}>
                    <Icon name={item.icon} size={14} style={{ color: 'var(--gold-light)' }} />
                    {ar ? item.ar : item.en}
                  </span>
                ))}
              </div>
            </div>
          </Reveal>
        </Container>
      </Section>

      {/* ===== 2. ARABIC BANNER ===== */}
      <div style={{ background: 'var(--espresso)', color: 'var(--ivory)', textAlign: 'center', padding: 'clamp(32px,5vw,56px) 24px' }}>
        <Container>
          <Reveal>
            <p style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(26px,4vw,42px)', fontWeight: 500, direction: 'rtl', lineHeight: 1.3 }}>اعرض منتجاتك وخدماتك أمام آلاف العملاء</p>
            <p style={{ fontSize: 'clamp(15px,1.6vw,18px)', color: 'rgba(250,246,240,0.7)', marginTop: 10 }}>Display your products and services to thousands of customers.</p>
          </Reveal>
        </Container>
      </div>

      {/* ===== 3. HOW IT WORKS ===== */}
      <Section bg="canvas">
        <div ref={howRef} />
        <Container wide>
          <Reveal><SectionHead center eyebrow={ar ? 'كيف تعمل' : 'How it works'} title={ar ? 'أربع خطوات للانطلاق' : 'Live in four simple steps'} /></Reveal>
          <div className="saraya-grid-4" style={{ marginTop: 48 }}>
            {[
              { icon: 'mouse-pointer-click', en: 'Subscribe online', ar: 'اشترك أونلاين', den: 'Choose AED 99/month and join in minutes.', dar: 'اختر باقة ٩٩ درهم شهريًا وانضم خلال دقائق.' },
              { icon: 'key-round', en: 'Receive your login', ar: 'استلم بياناتك', den: 'We send your username and password.', dar: 'نرسل لك اسم المستخدم وكلمة المرور.' },
              { icon: 'upload-cloud', en: 'Build your showroom', ar: 'جهّز معرضك', den: 'Upload your products and services.', dar: 'ارفع منتجاتك وخدماتك وأدِر صفحتك.' },
              { icon: 'store', en: 'Go live & sell', ar: 'انطلق واستقبل', den: 'Receive customers via WhatsApp or online orders.', dar: 'استقبل العملاء عبر واتساب أو الطلب أونلاين.' },
            ].map((s, i) => (
              <Reveal key={i} delay={(i % 4) * 70}>
                <div style={{ position: 'relative', background: 'var(--white)', borderRadius: 16, padding: '26px 22px', border: '1px solid var(--line)', boxShadow: 'var(--shadow-soft)', height: '100%' }}>
                  <span style={{ position: 'absolute', top: 18, insetInlineEnd: 20, fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 600, color: 'var(--gold-tint)' }}>{i + 1}</span>
                  <span style={{ display: 'inline-flex', width: 50, height: 50, borderRadius: 13, alignItems: 'center', justifyContent: 'center', background: 'var(--gold-tint)', color: 'var(--gold-deep)' }}><Icon name={s.icon} size={24} /></span>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 500, marginTop: 16 }}>{ar ? s.ar : s.en}</h3>
                  <p style={{ fontSize: 13.5, lineHeight: 1.55, color: 'var(--fg-secondary)', marginTop: 7 }}>{ar ? s.dar : s.den}</p>
                </div>
              </Reveal>
            ))}
          </div>
          {/* notes */}
          <Reveal>
            <div style={{ marginTop: 32, display: 'grid', gap: 12, maxWidth: 880, marginInline: 'auto' }}>
              {[
                { icon: 'message-circle', en: 'Each product or service can be linked to WhatsApp orders.', ar: 'يمكن ربط كل منتج أو خدمة بطلبات واتساب.' },
                { icon: 'credit-card', en: 'Add an online payment option for instant checkout.', ar: 'أضف خيار الدفع أونلاين للشراء الفوري.' },
                { icon: 'wallet', en: 'When customers pay online, Saraya charges no separate service fee — commission applies only based on your vendor package (Starter 2%, Growth 1%, Premium 0.5%) on confirmed transactions.', ar: 'عند الدفع أونلاين، تُحتسب العمولة على المعاملات المؤكدة فقط حسب باقتك: الأساسية 2%، النمو 1%، المميزة 0.5%. لا توجد رسوم خدمة منفصلة.' },
              ].map((n, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '14px 18px', background: 'var(--bg-tint)', borderRadius: 12, fontSize: 14, color: 'var(--fg-primary)' }}>
                  <Icon name={n.icon} size={18} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 1 }} />{ar ? n.ar : n.en}
                </div>
              ))}
            </div>
          </Reveal>
        </Container>
      </Section>

      {/* ===== 4. FEATURES GRID (9) ===== */}
      <Section bg="muted">
        <Container wide>
          <Reveal><SectionHead center eyebrow={ar ? 'المزايا' : 'Features'} title={ar ? 'كل ما تحتاجه صفحتك' : 'Everything your page needs'} /></Reveal>
          <div className="saraya-grid-3" style={{ marginTop: 44 }}>
            {[
              { icon: 'layout-panel-left', en: 'Own showroom page', ar: 'صفحة معرض خاصة' },
              { icon: 'package', en: 'Up to 25 products / services', ar: 'حتى ٢٥ منتجًا أو خدمة' },
              { icon: 'message-circle', en: 'WhatsApp & contact button', ar: 'زر واتساب وتواصل' },
              { icon: 'search', en: 'Search & category listing', ar: 'بحث وتصنيف بالفئات' },
              { icon: 'bar-chart-3', en: 'Monthly analytics', ar: 'تحليلات شهرية' },
              { icon: 'languages', en: 'Arabic & English support', ar: 'دعم عربي وإنجليزي' },
              { icon: 'map-pin', en: 'Location map pin', ar: 'موقع على الخريطة' },
              { icon: 'star', en: 'Customer reviews', ar: 'تقييمات العملاء' },
              { icon: 'megaphone', en: 'Event & offer banners', ar: 'لافتات العروض والفعاليات' },
            ].map((fz, i) => (
              <Reveal key={i} delay={(i % 3) * 60}>
                <div className="saraya-lift" style={{ display: 'flex', alignItems: 'center', gap: 15, padding: '20px 22px', background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', boxShadow: 'var(--shadow-soft)', height: '100%' }}>
                  <span style={{ flexShrink: 0, display: 'inline-flex', width: 46, height: 46, borderRadius: 12, alignItems: 'center', justifyContent: 'center', background: 'var(--rose-tint)', color: 'var(--rose-deep)' }}><Icon name={fz.icon} size={22} /></span>
                  <span style={{ fontSize: 15.5, fontWeight: 500 }}>{ar ? fz.ar : fz.en}</span>
                </div>
              </Reveal>
            ))}
          </div>
        </Container>
      </Section>

      {/* ===== 5. WHO IT'S FOR ===== */}
      <Section bg="canvas">
        <Container wide>
          <Reveal><SectionHead center eyebrow={ar ? 'لمن' : 'Who it’s for'} title={ar ? 'مثالي للأعمال الصغيرة والمنزلية' : 'Perfect for small & home businesses'}
            intro={ar ? 'إن كنت تبيع جمالًا أو طعامًا أو هدايا أو تجربة — مكانك هنا.' : 'If you sell something beautiful, delicious, or memorable — you belong here.'} /></Reveal>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'center', marginTop: 40 }}>
            {[
              { icon: 'home', en: 'Small & home businesses', ar: 'أعمال صغيرة ومنزلية' },
              { icon: 'utensils', en: 'Food & catering', ar: 'طعام وتموين' },
              { icon: 'sparkles', en: 'Beauty & salons', ar: 'تجميل وصالونات' },
              { icon: 'palette', en: 'Events & artisans', ar: 'فعاليات وحرفيون' },
              { icon: 'flower-2', en: 'Florists', ar: 'محلات الزهور' },
              { icon: 'candy', en: 'Chocolate & sweets', ar: 'شوكولاتة وحلويات' },
              { icon: 'coffee', en: 'Coffee / mini café', ar: 'قهوة ومقاهٍ صغيرة' },
              { icon: 'printer', en: 'Printing & stationery', ar: 'طباعة وقرطاسية' },
              { icon: 'gift', en: 'Gifts', ar: 'هدايا' },
              { icon: 'baby', en: 'Kids entertainment', ar: 'ترفيه أطفال' },
              { icon: 'camera', en: 'Event photography', ar: 'تصوير المناسبات' },
              { icon: 'wind', en: 'Perfume & luxury gifting', ar: 'عطور وهدايا فاخرة' },
            ].map((w, i) => (
              <Reveal key={i} delay={(i % 6) * 40}>
                <div className="saraya-lift" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '11px 18px', background: 'var(--white)', borderRadius: 999, border: '1px solid var(--line-strong)', fontSize: 14, fontWeight: 500 }}>
                  <Icon name={w.icon} size={17} style={{ color: 'var(--gold-deep)' }} />{ar ? w.ar : w.en}
                </div>
              </Reveal>
            ))}
          </div>
        </Container>
      </Section>

      {/* ===== 6/7. PRICING ===== */}
      <Section bg="muted">
        <div ref={formRef} />
        <Container>
          <div style={{ maxWidth: 520, margin: '0 auto' }}>
            <Reveal><PricingCard ar={ar} onSubscribe={() => setPkgModalOpen(true)} /></Reveal>
          </div>
        </Container>
      </Section>


      {/* ===== 9. CTA BAND ===== */}
      <div style={{ background: 'var(--gold)', color: 'var(--espresso)', textAlign: 'center', padding: 'clamp(48px,7vw,84px) 24px' }}>
        <Container>
          <Reveal>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(30px,5vw,52px)', fontWeight: 500 }}>{ar ? 'جاهز للانطلاق رقميًا؟' : 'Ready to Go Digital?'}</h2>
            <p style={{ fontSize: 'clamp(15px,1.7vw,18px)', marginTop: 12, color: 'var(--espresso-soft)', maxWidth: 540, marginInline: 'auto' }}>{ar ? 'انضم إلى المعرض الرقمي من سرايا وابدأ باستقبال العملاء اليوم.' : 'Join Saraya’s virtual showroom and start receiving customers today.'}</p>
            <div style={{ marginTop: 26 }}>
              <Button variant="primary" size="lg" icon="message-circle" href={showroomWa('Hello Saraya Events, I’d like to join the Virtual Showroom (AED 99/month).')} target="_blank">{ar ? 'تواصل عبر واتساب' : 'Chat on WhatsApp'}</Button>
            </div>
          </Reveal>
        </Container>
      </div>

      {/* ===== 8. ADMIN (subtle) ===== */}
      <div style={{ textAlign: 'center', padding: '22px 24px', background: 'var(--bg-canvas)' }}>
        <button onClick={() => (admin.isAdmin ? admin.openSubs() : admin.openLogin())} className="saraya-admin-access"
          style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', fontFamily: 'var(--font-body)', fontSize: 12.5 }}>
          <Icon name="shield" size={13} />{ar ? 'إدارة الاشتراكات' : 'Admin / Manage Subscriptions'}
        </button>
      </div>
      {demoOpen && <ShowroomDemoModal onClose={() => setDemoOpen(false)} />}
      {pkgModalOpen && <VendorPackageSelectModal ar={ar} onClose={() => setPkgModalOpen(false)} onSelect={(pkg) => { setPkgModalOpen(false); subscribe(pkg); }} />}
    </main>
  );
}

/* ---------------- Package Selection Modal ---------------- */
function VendorPackageSelectModal({ ar, onClose, onSelect }) {
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 210, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px 16px' }}>
      <div onClick={onClose} 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)', width: '100%', maxWidth: 780,
        maxHeight: '92vh', overflowY: 'auto',
        animation: 'sarayaPop 260ms var(--ease-out)',
      }}>
        {/* Header */}
        <div style={{ padding: '32px 32px 24px', borderBottom: '1px solid var(--line)', position: 'sticky', top: 0, background: 'var(--bg-canvas)', zIndex: 1 }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 20, insetInlineEnd: 20, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', display: 'flex', padding: 6, borderRadius: 8 }}>
            <Icon name="x" size={20} />
          </button>
          <div style={{ display: 'inline-flex', width: 48, height: 48, borderRadius: 13, background: 'var(--gold-tint)', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
            <Icon name="layout-panel-left" size={24} style={{ color: 'var(--gold-deep)' }} />
          </div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(22px,4vw,30px)', fontWeight: 500, margin: '0 0 8px' }}>
            {ar ? 'اختر باقة الموردين' : 'Choose Your Vendor Package'}
          </h2>
          <p style={{ fontSize: 14.5, color: 'var(--fg-muted)', margin: 0, maxWidth: 520 }}>
            {ar
              ? 'اختر الباقة الأنسب لعملك قبل بدء معرضك على سرايا.'
              : 'Select the package that best fits your business before starting your Saraya Events showroom.'}
          </p>
        </div>

        {/* Package cards */}
        <div style={{ padding: '24px 32px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(210px,1fr))', gap: 18 }}>
          {SHOWROOM_PACKAGES.map((pkg, i) => (
            <div key={pkg.id} style={{
              borderRadius: 16,
              border: pkg.highlight ? '2px solid var(--gold)' : '1.5px solid var(--line)',
              background: pkg.highlight ? 'var(--espresso)' : 'var(--white)',
              color: pkg.highlight ? 'var(--ivory)' : 'var(--fg-primary)',
              padding: '24px 22px',
              display: 'flex', flexDirection: 'column',
              position: 'relative',
              boxShadow: pkg.highlight ? 'var(--shadow-lift)' : 'none',
              animation: 'sarayaPop 260ms var(--ease-out) backwards',
              animationDelay: (i * 60) + 'ms',
            }}>
              {pkg.badge && (
                <span style={{ position: 'absolute', top: -13, left: '50%', transform: 'translateX(-50%)', background: 'var(--gold)', color: 'var(--espresso)', padding: '3px 14px', borderRadius: 20, fontSize: 11.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
                  {ar ? pkg.badge.ar : pkg.badge.en}
                </span>
              )}

              <div style={{ marginBottom: 16 }}>
                <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.65, margin: '0 0 6px' }}>
                  {ar ? pkg.ar : pkg.en}
                </p>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 38, fontWeight: 500, lineHeight: 1 }}>AED {pkg.price}</span>
                  <span style={{ fontSize: 13, opacity: 0.6 }}>{ar ? '/شهر' : '/mo'}</span>
                </div>
                <p style={{ fontSize: 12.5, opacity: 0.6, margin: '5px 0 0' }}>
                  {ar ? pkg.tagline.ar : pkg.tagline.en}
                </p>
              </div>

              <div style={{ flex: 1, display: 'grid', gap: 8, marginBottom: 20 }}>
                {(ar ? pkg.features.ar : pkg.features.en).map((f, fi) => (
                  <div key={fi} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                    <Icon name="check" size={14} style={{ color: pkg.highlight ? 'var(--gold-light)' : 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />
                    <span style={{ fontSize: 13, lineHeight: 1.5, opacity: 0.88 }}>{f}</span>
                  </div>
                ))}
              </div>

              <button onClick={() => onSelect(pkg)} style={{
                width: '100%', padding: '12px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
                fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700,
                background: pkg.highlight ? 'var(--gold)' : 'var(--espresso)',
                color: pkg.highlight ? 'var(--espresso)' : 'var(--ivory)',
                transition: 'opacity 140ms',
              }}>
                {ar ? pkg.cta.ar : pkg.cta.en}
              </button>
            </div>
          ))}
        </div>

        {/* Footer note */}
        <div style={{ padding: '0 32px 28px', textAlign: 'center' }}>
          <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', margin: 0 }}>
            {ar
              ? 'يمكن تغيير الباقة لاحقًا من حساب المورد، وفقًا لشروط الفوترة والموافقة.'
              : 'Packages can be changed later from your vendor account, subject to platform approval and billing terms.'}
          </p>
          <button onClick={() => { onClose(); window.location.hash = '#vendor-packages'; }} style={{ marginTop: 10, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--gold-deep)', fontWeight: 600, textDecoration: 'underline', textUnderlineOffset: 3 }}>
            {ar ? 'مقارنة كاملة للباقات' : 'Full package comparison'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Browser mockup — shows real approved vendors, falls back to placeholders ---------------- */
const BROWSER_MOCK_FALLBACK = [
  { name: 'Lina Fashion', name_ar: 'لينا للأزياء', sub: 'Modest wear · Abu Dhabi', sub_ar: 'أزياء محتشمة · أبوظبي', icon: 'shirt', whatsapp: null },
  { name: 'Date & Crumb', name_ar: 'تمر وفتات', sub: 'Home bakery', sub_ar: 'مخبز منزلي', icon: 'croissant', whatsapp: null },
  { name: 'Green Majlis', name_ar: 'مجلس أخضر', sub: 'Plants & landscaping', sub_ar: 'نباتات وتنسيق حدائق', icon: 'sprout', whatsapp: null },
];
const MOCK_ICONS = ['store', 'gift', 'sparkles', 'camera', 'music', 'utensils', 'flower-2', 'shirt', 'gem', 'cake'];

function BrowserMock({ ar }) {
  const [cards, setCards] = useStateShow(BROWSER_MOCK_FALLBACK);

  useEffectShow(() => {
    const db = window.SarayaDB;
    if (!db) return;
    db.from('vendor_profiles')
      .select('trade_name, trade_name_ar, business_category')
      .eq('status', 'approved')
      .limit(3)
      .then(({ data }) => {
        if (!data || data.length === 0) return;
        setCards(data.map((v, i) => ({
          name:    v.trade_name    || 'Vendor',
          name_ar: v.trade_name_ar || v.trade_name || 'مورد',
          sub:     v.business_category || 'Verified vendor',
          sub_ar:  v.business_category || 'مورد معتمد',
          icon:    MOCK_ICONS[i % MOCK_ICONS.length],
        })));
      });
  }, []);

  return (
    <div style={{ background: 'var(--white)', borderRadius: 16, boxShadow: 'var(--shadow-deep)', border: '1px solid var(--line)', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 14px', background: 'var(--bg-muted)', borderBottom: '1px solid var(--line)' }}>
        <span style={{ display: 'flex', gap: 6 }}>{['#E5A8A0', '#E8C97D', '#A9C6A0'].map((c) => <span key={c} style={{ width: 11, height: 11, borderRadius: 999, background: c }} />)}</span>
        <span style={{ marginInlineStart: 8, flex: 1, background: 'var(--white)', borderRadius: 7, padding: '5px 12px', fontSize: 11.5, color: 'var(--fg-muted)', textAlign: 'center', border: '1px solid var(--line)' }}>saraya.events/showroom</span>
      </div>
      <div style={{ padding: 16, display: 'grid', gap: 12 }}>
        {cards.map((c, i) => {
          const waHref = showroomWa(`Hello Saraya Events, I am interested in ${ar ? c.name_ar : c.name}. Please assist me.`);
          return (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '12px 14px', background: 'var(--bg-canvas)', borderRadius: 12, border: '1px solid var(--line)' }}>
              <span style={{ flexShrink: 0, display: 'inline-flex', width: 46, height: 46, borderRadius: 11, alignItems: 'center', justifyContent: 'center', background: 'var(--cream)', color: 'var(--gold-deep)' }}><Icon name={c.icon} size={22} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontWeight: 500 }}>{ar ? c.name_ar : c.name}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{ar ? c.sub_ar : c.sub}</div>
              </div>
              <a href={waHref} target="_blank" rel="noopener noreferrer" title="Ask Saraya Events" style={{ flexShrink: 0, display: 'inline-flex', width: 32, height: 32, borderRadius: 8, alignItems: 'center', justifyContent: 'center', background: '#25D366', color: '#fff', textDecoration: 'none' }}><Icon name="message-circle" size={16} /></a>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------------- Pricing card (12 perks) ---------------- */
function PricingCard({ ar, onSubscribe }) {
  const perks = [
    ['Online business showroom page', 'صفحة معرض إلكتروني'],
    ['Up to 25 products or services', 'حتى ٢٥ منتجًا أو خدمة'],
    ['WhatsApp order button', 'زر طلب عبر واتساب'],
    ['Contact button', 'زر تواصل'],
    ['Search / category listing', 'إدراج في البحث والفئات'],
    ['Arabic & English support', 'دعم عربي وإنجليزي'],
    ['Monthly performance analytics', 'تحليلات أداء شهرية'],
    ['Map / location pin', 'موقع على الخريطة'],
    ['Customer reviews', 'تقييمات العملاء'],
    ['Offer / event banners', 'لافتات العروض والفعاليات'],
    ['Mobile-friendly page', 'صفحة متوافقة مع الجوال'],
    ['Easy product updates', 'تحديث سهل للمنتجات'],
  ];
  return (
    <div style={{ background: 'var(--white)', borderRadius: 20, border: '1px solid var(--line)', boxShadow: 'var(--shadow-lift)', overflow: 'hidden' }}>
      <div style={{ background: 'var(--espresso)', color: 'var(--ivory)', padding: '26px 28px' }}>
        <Badge tone="gold">{ar ? 'المعرض الرقمي' : 'Virtual Showroom'}</Badge>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 14 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 52, fontWeight: 600, lineHeight: 1 }}>AED 99</span>
          <span style={{ fontSize: 16, color: 'rgba(250,246,240,0.7)' }}>/ {ar ? 'شهريًا' : 'month'}</span>
        </div>
        <p style={{ fontSize: 13.5, color: 'rgba(250,246,240,0.72)', marginTop: 8 }}>{ar ? 'ألغِ في أي وقت. بدون رسوم تأسيس. تُطبَّق العمولة فقط حسب باقتك على المعاملات المؤكدة.' : 'Cancel anytime. No setup fees. Commission applies only per your package tier on confirmed transactions.'}</p>
      </div>
      <div style={{ padding: '24px 28px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 16px' }}>
          {perks.map((p, i) => (
            <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', fontSize: 13.5, color: 'var(--fg-primary)' }}>
              <Icon name="check" size={15} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />{ar ? p[1] : p[0]}
            </div>
          ))}
        </div>
        <Button variant="primary" size="lg" full icon="arrow-down" style={{ marginTop: 22 }} onClick={onSubscribe}>{ar ? 'اشترك بـ ٩٩ درهم شهريًا' : 'Subscribe for AED 99/Month'}</Button>
        <p style={{ fontSize: 11.5, color: 'var(--fg-muted)', textAlign: 'center', marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}><Icon name="repeat" size={12} />{ar ? 'خصم تلقائي شهريًا ما لم يتم الإلغاء.' : 'Auto-deduction monthly unless cancelled.'}</p>
      </div>
    </div>
  );
}


/* ---------------- Admin: Manage Subscriptions panel ---------------- */
function AdminSubsPanel({ onClose }) {
  const [subs, setSubs] = useStateShow(() => window.SubsAPI.list());
  const refresh = () => setSubs(window.SubsAPI.list());
  const active = subs.filter((s) => s.status === 'active').length;
  const cancelled = subs.filter((s) => s.status === 'cancelled').length;
  const mrr = active * SHOWROOM_PRICE;
  const setStatus = (id, st) => { window.SubsAPI.setStatus(id, st); refresh(); };
  const setPay = (id, p) => { window.SubsAPI.setPayment(id, p); refresh(); };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 290, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'var(--scrim)' }} />
      <div style={{ position: 'relative', width: 'min(940px,100%)', height: 'min(88vh,800px)', display: 'flex', flexDirection: 'column', background: 'var(--bg-canvas)', borderRadius: 18, boxShadow: 'var(--shadow-deep)', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 22px', borderBottom: '1px solid var(--line)', background: 'var(--white)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Icon name="store" size={20} style={{ color: 'var(--gold-deep)' }} /><h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500 }}>Showroom Subscriptions</h3></div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', display: 'flex', padding: 4 }}><Icon name="x" size={22} /></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(150px,1fr))', gap: 12, padding: '16px 22px', background: 'var(--bg-muted)' }}>
          <Stat label="Active" value={active} icon="check-circle" />
          <Stat label="Cancelled" value={cancelled} icon="x-circle" />
          <Stat label="Monthly revenue" value={'AED ' + mrr} icon="trending-up" />
          <Stat label="Total" value={subs.length} icon="users" />
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 22px 22px' }}>
          {subs.length === 0 ? (
            <div style={{ textAlign: 'center', color: 'var(--fg-muted)', marginTop: 48 }}><Icon name="inbox" size={40} stroke={1} /><p style={{ marginTop: 12, fontSize: 14 }}>No subscriptions yet. Sign-ups from the Virtual Showroom page appear here.</p></div>
          ) : (
            <div style={{ display: 'grid', gap: 12 }}>
              {subs.map((s) => (
                <div key={s.id} style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 12, padding: '14px 16px' }}>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 500 }}>{s.business}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>{s.owner} · {s.category}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', marginTop: 4 }}>{s.phone} · {s.email}</div>
                      {s.desc && <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', marginTop: 4, maxWidth: 460 }}>{s.desc}</div>}
                    </div>
                    <div style={{ display: 'grid', gap: 8, minWidth: 170 }}>
                      <label style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Status
                        <Select value={s.status} onChange={(e) => setStatus(s.id, e.target.value)} style={{ marginTop: 3 }}>
                          <option value="active">Active</option><option value="paused">Paused</option><option value="cancelled">Cancelled</option>
                        </Select>
                      </label>
                      <label style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Payment
                        <Select value={s.payment} onChange={(e) => setPay(s.id, e.target.value)} style={{ marginTop: 3 }}>
                          <option value="pending">Pending</option><option value="paid">Paid</option><option value="overdue">Overdue</option>
                        </Select>
                      </label>
                    </div>
                  </div>
                  <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--fg-muted)' }}>Joined {new Date(s.createdAt).toLocaleDateString()}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ShowroomPage, AdminSubsPanel, SubsAPI });
