// Saraya Events — Virtual Showroom: animated demo player + backend/system flow.
// • ShowroomDemoModal — a self-playing "video" walkthrough (6 scenes, controls).
// • BackendFlowSection — a system diagram + a LIVE, testable backend simulator
//   that runs the real subscription pipeline and records a test subscription.

const { useState: useStateDemo, useEffect: useEffectDemo, useRef: useRefDemo } = React;

/* ============================ DEMO PLAYER ============================ */
const DEMO_SCENES = [
  { icon: 'user-plus',     en: 'Register your business', ar: 'سجّل عملك', cap_en: 'A business fills the quick signup form — owner, business name, category.', cap_ar: 'يملأ صاحب العمل نموذج التسجيل السريع.' },
  { icon: 'credit-card',   en: 'Pay AED 99 securely', ar: 'ادفع ٩٩ درهمًا بأمان', cap_en: 'Checkout collects the AED 99/month fee through a secure payment gateway.', cap_ar: 'يتم تحصيل رسوم الاشتراك عبر بوابة دفع آمنة.' },
  { icon: 'key-round',     en: 'Instant access granted', ar: 'تفعيل فوري للوصول', cap_en: 'A login is generated automatically and emailed to the business.', cap_ar: 'يُنشأ تسجيل دخول تلقائيًا ويُرسل بالبريد.' },
  { icon: 'upload-cloud',  en: 'Build your showroom', ar: 'جهّز معرضك', cap_en: 'They upload up to 25 products or services with photos and prices.', cap_ar: 'يرفعون حتى ٢٥ منتجًا أو خدمة بالصور والأسعار.' },
  { icon: 'message-circle',en: 'Customers find & order', ar: 'العملاء يطلبون', cap_en: 'Shoppers browse the showroom and order via WhatsApp or online checkout.', cap_ar: 'يتصفح العملاء ويطلبون عبر واتساب أو أونلاين.' },
  { icon: 'wallet',        en: 'You get paid', ar: 'تستلم أرباحك', cap_en: 'Saraya charges no separate service fee — commission applies only based on your vendor package (Starter 2%, Growth 1%, Premium 0.5%) on confirmed transactions.', cap_ar: 'تُحتسب العمولة على المعاملات المؤكدة فقط حسب باقتك: الأساسية 2%، النمو 1%، المميزة 0.5%. لا توجد رسوم خدمة منفصلة.' },
];

function ShowroomDemoModal({ onClose }) {
  const { lang } = useLang(); const ar = lang === 'ar';
  const [i, setI] = useStateDemo(0);
  const [playing, setPlaying] = useStateDemo(true);
  const [prog, setProg] = useStateDemo(0);
  const raf = useRefDemo(null); const start = useRefDemo(null);
  const DUR = 4000;

  useEffectDemo(() => {
    if (!playing) return;
    start.current = performance.now() - prog * DUR;
    const tick = (now) => {
      const p = Math.min(1, (now - start.current) / DUR);
      setProg(p);
      if (p >= 1) { setProg(0); setI((x) => (x + 1) % DEMO_SCENES.length); start.current = performance.now(); }
      raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, [playing, i]);

  const go = (n) => { setI((n + DEMO_SCENES.length) % DEMO_SCENES.length); setProg(0); start.current = performance.now(); };
  const sc = DEMO_SCENES[i];

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(42,31,26,0.72)', backdropFilter: 'blur(6px)' }} />
      <div style={{ position: 'relative', width: 'min(760px,100%)', background: 'var(--bg-canvas)', borderRadius: 20, boxShadow: 'var(--shadow-deep)', overflow: 'hidden' }}>
        {/* top bar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', background: 'var(--espresso)', color: 'var(--ivory)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontSize: 13.5, fontWeight: 600 }}><Icon name="play-circle" size={18} style={{ color: 'var(--gold-light)' }} />{ar ? 'كيف يعمل المعرض الرقمي' : 'How the Virtual Showroom works'}</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ivory)', display: 'flex', padding: 3 }}><Icon name="x" size={22} /></button>
        </div>

        {/* stage */}
        <div style={{ position: 'relative', height: 380, background: 'var(--cream)', overflow: 'hidden' }}>
          {DEMO_SCENES.map((s, n) => (
            <div key={n} style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 32px', opacity: n === i ? 1 : 0, transform: n === i ? 'translateY(0)' : 'translateY(14px)', transition: 'opacity 500ms var(--ease-out), transform 500ms var(--ease-out)', pointerEvents: n === i ? 'auto' : 'none' }}>
              <DemoScene scene={s} n={n} active={n === i} ar={ar} />
            </div>
          ))}
          <span style={{ position: 'absolute', top: 14, insetInlineStart: 18, fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--fg-muted)' }}>{String(i + 1).padStart(2, '0')} / {String(DEMO_SCENES.length).padStart(2, '0')}</span>
        </div>

        {/* caption */}
        <div style={{ padding: '20px 26px 8px', textAlign: 'center' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>{ar ? sc.ar : sc.en}</h3>
          <p style={{ fontSize: 14, color: 'var(--fg-secondary)', marginTop: 6, minHeight: 42, maxWidth: 520, marginInline: 'auto', lineHeight: 1.5 }}>{ar ? sc.cap_ar : sc.cap_en}</p>
        </div>

        {/* progress segments */}
        <div style={{ display: 'flex', gap: 6, padding: '0 26px' }}>
          {DEMO_SCENES.map((s, n) => (
            <button key={n} onClick={() => go(n)} style={{ flex: 1, height: 5, borderRadius: 999, border: 'none', cursor: 'pointer', background: 'var(--line-strong)', overflow: 'hidden', padding: 0 }}>
              <span style={{ display: 'block', height: '100%', width: n < i ? '100%' : n === i ? (prog * 100) + '%' : '0%', background: 'var(--gold-deep)', transition: n === i ? 'none' : 'width 200ms' }} />
            </button>
          ))}
        </div>

        {/* controls */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, padding: '16px 26px 22px' }}>
          <button onClick={() => go(i - 1)} style={demoCtrl}><Icon name="chevron-left" size={20} /></button>
          <button onClick={() => setPlaying((p) => !p)} style={{ ...demoCtrl, width: 50, height: 50, background: 'var(--espresso)', color: 'var(--ivory)', border: 'none' }}><Icon name={playing ? 'pause' : 'play'} size={22} /></button>
          <button onClick={() => go(i + 1)} style={demoCtrl}><Icon name="chevron-right" size={20} /></button>
        </div>
      </div>
    </div>
  );
}
const demoCtrl = { width: 42, height: 42, borderRadius: 999, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'var(--white)', border: '1px solid var(--line-strong)', cursor: 'pointer', color: 'var(--fg-primary)' };

/* one animated mock screen per scene */
function DemoScene({ scene, n, active, ar }) {
  if (n === 0) return <MockCard ar={ar}><div style={{ display: 'grid', gap: 9 }}>{[ar ? 'اسم العمل' : 'Business name', ar ? 'الفئة' : 'Category', ar ? 'البريد' : 'Email'].map((l, k) => <div key={k} style={{ display: 'grid', gap: 5 }}><span style={{ fontSize: 10.5, color: 'var(--fg-muted)' }}>{l}</span><div style={{ height: 30, borderRadius: 8, background: 'var(--bg-muted)', border: '1px solid var(--line)', position: 'relative', overflow: 'hidden' }}><span style={{ position: 'absolute', insetInlineStart: 10, top: 8, width: active ? (40 + k * 18) + '%' : 0, height: 13, borderRadius: 4, background: 'var(--gold-tint)', transition: 'width 700ms var(--ease-out) ' + (k * 180) + 'ms' }} /></div></div>)}</div></MockCard>;
  if (n === 1) return <MockCard ar={ar}><div style={{ background: 'var(--espresso)', color: 'var(--ivory)', borderRadius: 12, padding: '18px 20px' }}><div style={{ fontSize: 11.5, color: 'rgba(250,246,240,0.6)' }}>{ar ? 'الإجمالي' : 'Total due'}</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 600 }}>AED 99<span style={{ fontSize: 15, color: 'rgba(250,246,240,0.6)' }}> / {ar ? 'شهر' : 'mo'}</span></div><div style={{ marginTop: 12, height: 38, borderRadius: 8, background: 'rgba(250,246,240,0.12)', display: 'flex', alignItems: 'center', gap: 8, padding: '0 12px', fontSize: 12, letterSpacing: '0.18em' }}>•••• •••• •••• 4242</div><div style={{ marginTop: 10, height: 38, borderRadius: 8, background: active ? 'var(--gold)' : 'var(--gold-deep)', color: 'var(--espresso)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, fontWeight: 600, fontSize: 13, transition: 'background 300ms' }}><Icon name="lock" size={14} />{ar ? 'ادفع الآن' : 'Pay Now'}</div></div></MockCard>;
  if (n === 2) return <MockCard ar={ar}><div style={{ textAlign: 'center' }}><span style={{ display: 'inline-flex', width: 56, height: 56, borderRadius: 999, alignItems: 'center', justifyContent: 'center', background: 'var(--success-bg)', color: 'var(--success)', transform: active ? 'scale(1)' : 'scale(0.6)', transition: 'transform 500ms var(--ease-out)' }}><Icon name="check" size={30} /></span><div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 16 }}>{[[ar ? 'المستخدم' : 'Username', 'lina-fashion-7k'], [ar ? 'كلمة المرور' : 'Password', 'x9p2m4']].map((c, k) => <div key={k} style={{ background: 'var(--bg-tint)', borderRadius: 9, padding: '10px 12px', textAlign: 'start' }}><div style={{ fontSize: 9.5, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{c[0]}</div><div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{c[1]}</div></div>)}</div></div></MockCard>;
  if (n === 3) return <MockCard ar={ar} wide><div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 9 }}>{[0, 1, 2, 3, 4, 5].map((k) => <div key={k} style={{ aspectRatio: '1', borderRadius: 9, background: k % 2 ? 'var(--rose-tint)' : 'var(--champagne, var(--gold-tint))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold-deep)', opacity: active ? 1 : 0, transform: active ? 'scale(1)' : 'scale(0.8)', transition: 'all 420ms var(--ease-out) ' + (k * 90) + 'ms' }}><Icon name={['shirt', 'gem', 'gift', 'sparkles', 'crown', 'flower-2'][k]} size={22} /></div>)}</div></MockCard>;
  if (n === 4) return <MockCard ar={ar}><div style={{ display: 'grid', gap: 10 }}>{[['shirt', ar ? 'فستان حرير' : 'Silk dress', 'AED 420'], ['gem', ar ? 'إكسسوار' : 'Accessory', 'AED 120']].map((r, k) => <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 11, padding: '10px 12px' }}><span style={{ width: 40, height: 40, borderRadius: 9, background: 'var(--rose-tint)', color: 'var(--rose-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={r[0]} size={19} /></span><div style={{ flex: 1 }}><div style={{ fontFamily: 'var(--font-serif)', fontSize: 14.5, fontWeight: 500 }}>{r[1]}</div><div style={{ fontSize: 12, color: 'var(--gold-deep)', fontWeight: 600 }}>{r[2]}</div></div><span style={{ width: 30, height: 30, borderRadius: 7, background: '#25D366', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', transform: active ? 'scale(1)' : 'scale(0)', transition: 'transform 400ms var(--ease-out) ' + (k * 160 + 200) + 'ms' }}><Icon name="message-circle" size={15} /></span></div>)}</div></MockCard>;
  return <MockCard ar={ar}><div style={{ textAlign: 'center' }}><div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, fontSize: 13, color: 'var(--fg-secondary)' }}><span>{ar ? 'مبيعات' : 'Sales'}</span><Icon name="arrow-right" size={15} style={{ color: 'var(--gold-deep)' }} /><span>{ar ? 'سرايا' : 'Saraya'}</span><Icon name="arrow-right" size={15} style={{ color: 'var(--gold-deep)' }} /><span>{ar ? 'حسابك' : 'You'}</span></div><div style={{ fontFamily: 'var(--font-display)', fontSize: 38, fontWeight: 600, marginTop: 14, color: 'var(--gold-deep)', opacity: active ? 1 : 0, transform: active ? 'translateY(0)' : 'translateY(10px)', transition: 'all 500ms var(--ease-out)' }}>AED 538.71</div><div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 4 }}>{ar ? 'بعد خصم العمولة' : 'after package commission'}</div></div></MockCard>;
}
function MockCard({ children, wide }) {
  return <div style={{ width: wide ? 320 : 300, background: 'var(--bg-canvas)', border: '1px solid var(--line)', borderRadius: 14, boxShadow: 'var(--shadow-lift)', padding: 18 }}>{children}</div>;
}

Object.assign(window, { ShowroomDemoModal });
