// demo-modal.jsx — "the 90-second tour": a guided, auto-advancing walkthrough
// of the real Werkd app screens, opened from the hero's "See 90s demo" button.
// Reuses the actual phone-screen components (no fake UI).
// Listens for window CustomEvent('werkd:open-demo'). Loads after phone-mock.jsx,
// shared-bits.jsx, direction-a.jsx, direction-a-extras2.jsx.

const DEMO_STEPS = [
  { key: 'today',  label: 'Today',       title: 'Your whole day, one line.',
    body: 'Next job, route, what you’ve earned, what needs attention — the moment you open the app.',
    render: () => <TodayScreen theme="light" state="default"/> },
  { key: 'composer', label: '⊕ Capture', title: 'Say it. Werkd builds it.',
    body: 'Tap ⊕ and talk — “replaced the water heater at Patel’s, $1,240.” Werkd builds the job, quote, or expense; you approve.',
    render: () => <ComposerScreen theme="light"/> },
  { key: 'field',  label: 'Field Mode',  title: 'On the job, hands-free.',
    body: 'The timer runs while you work. Tap the mic and tell werkd what you used or found — it logs the materials and writes the invoice while your hands stay on the job.',
    render: () => <FMInProgress/> },
  { key: 'job',    label: 'Job record',  title: 'One job, one screen.',
    body: 'Schedule, customer, scope, materials, photos — and one button for the job’s next step.',
    render: () => <JobRecordScreen theme="light"/> },
  { key: 'desk',   label: 'Desk',        title: 'Decisions, not paperwork.',
    body: 'Werkd drafts the invoice, the quote follow-up — you approve. Payment reminders run on their own schedule. The day’s admin, cleared in taps.',
    render: () => <DeskScreen theme="light"/> },
  { key: 'ledger', label: 'Ledger',      title: 'Look it up, then leave.',
    body: 'Money pulse up top. One search across customers, invoices, quotes, and jobs — price book and reports live here too.',
    render: () => <LedgerScreen theme="light"/> },
  { key: 'sched',  label: 'Scheduling',  title: 'Customers book when it suits you.',
    body: 'Werkd offers only the slots that fit your route and your day — not raw calendar gaps.',
    render: () => <SmartSlotsScreen theme="light"/> },
  { key: 'crm',    label: 'Customers',   title: 'Every customer, remembered.',
    body: 'Jobs, quotes, payments, photos — threaded per customer. Werkd nudges the follow-ups you’d forget.',
    render: () => <CustomersScreen theme="light"/> },
];

const STEP_MS = 6000;

function DemoModal() {
  const DA = window.DA;
  const m = window.useIsMobile ? window.useIsMobile() : false;
  const [open, setOpen] = React.useState(false);
  const [i, setI] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [typed, setTyped] = React.useState('');
  const timerRef = React.useRef(null);

  // open via global event
  React.useEffect(() => {
    const onOpen = () => { setI(0); setOpen(true); setPaused(false); };
    window.addEventListener('werkd:open-demo', onOpen);
    return () => window.removeEventListener('werkd:open-demo', onOpen);
  }, []);

  // esc to close, lock body scroll while open
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setOpen(false);
      if (e.key === 'ArrowRight') { setI((p) => (p + 1) % DEMO_STEPS.length); setPaused(true); }
      if (e.key === 'ArrowLeft') { setI((p) => (p - 1 + DEMO_STEPS.length) % DEMO_STEPS.length); setPaused(true); }
    };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prevOverflow; };
  }, [open]);

  // Type the caption out like Werkd narrating each screen, then dwell ~5s and
  // advance — turns the slideshow into a guided, alive walkthrough.
  React.useEffect(() => {
    if (!open) return;
    const full = DEMO_STEPS[i].body;
    if (paused) { setTyped(full); return; }
    setTyped('');
    let idx = 0;
    const SPEED = 18;
    const typeId = setInterval(() => {
      idx += 1; setTyped(full.slice(0, idx));
      if (idx >= full.length) clearInterval(typeId);
    }, SPEED);
    timerRef.current = setTimeout(() => setI((p) => (p + 1) % DEMO_STEPS.length), full.length * SPEED + 5000);
    return () => { clearInterval(typeId); clearTimeout(timerRef.current); };
  }, [open, paused, i]);

  if (!open) return null;
  const step = DEMO_STEPS[i];
  const go = (n) => { setI((n + DEMO_STEPS.length) % DEMO_STEPS.length); setPaused(true); };

  const modal = (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(8,8,9,0.86)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
        display: 'flex', alignItems: m ? 'flex-start' : 'center', justifyContent: 'center',
        overflowY: m ? 'auto' : 'visible',
        fontFamily: DA.font, padding: m ? '60px 12px 28px' : 24,
      }}>
      {/* close */}
      <button onClick={() => setOpen(false)} aria-label="Close" style={{
        position: 'absolute', top: 22, right: 26,
        width: 44, height: 44, borderRadius: '50%',
        background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)',
        color: '#fff', fontSize: 22, cursor: 'pointer', lineHeight: 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>×</button>

      <div style={{
        width: 'min(960px, 100%)', maxHeight: m ? 'none' : '100%',
        display: 'grid', gridTemplateColumns: '380px 1fr', gap: 48, alignItems: m ? 'start' : 'center',
      }} className="demo-grid">
        {/* phone */}
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div key={'demoph-' + i} className="demo-phone-in">
            <PhoneFrame width={m ? 270 : 320} theme="light" glow>
              {step.render()}
            </PhoneFrame>
          </div>
        </div>

        {/* caption + controls */}
        <div className="demo-caption">
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 18,
            fontSize: 12, fontWeight: 700, letterSpacing: '0.16em', color: DA.brandLight,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: DA.brandLight }}/>
            THE 90-SECOND TOUR · {String(i + 1).padStart(2, '0')} / {String(DEMO_STEPS.length).padStart(2, '0')}
          </div>
          <div key={'democap-' + i} className="demo-fade">
            <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.14em', color: 'rgba(255,255,255,0.5)', marginBottom: 10, textTransform: 'uppercase' }}>
              {step.label}
            </div>
            <h3 style={{
              margin: '0 0 14px', fontSize: m ? 25 : 34, fontWeight: 800, letterSpacing: '-0.03em',
              color: '#fff', lineHeight: 1.08, textWrap: 'balance',
              minHeight: m ? 'auto' : '2.1em', display: 'flex', alignItems: 'flex-end',
            }}>{step.title}</h3>
            <div style={{ position: 'relative', maxWidth: 420, minHeight: m ? 56 : 100, marginBottom: m ? 20 : 28 }}>
              <p aria-hidden="true" style={{ margin: 0, fontSize: m ? 15 : 17, lineHeight: 1.5, visibility: 'hidden' }}>{step.body}</p>
              <p style={{
                position: 'absolute', inset: 0, margin: 0, fontSize: m ? 15 : 17, lineHeight: 1.5,
                color: 'rgba(255,255,255,0.65)', textWrap: 'pretty',
              }}>{typed}<span className="demo-caret" style={{
                display: 'inline-block', width: 2, height: '1.05em', background: DA.brandLight,
                marginLeft: 3, verticalAlign: '-0.18em', borderRadius: 1,
              }}/></p>
            </div>
          </div>

          {/* progress segments */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 24, maxWidth: 420 }}>
            {DEMO_STEPS.map((s, idx) => (
              <button key={s.key} onClick={() => go(idx)} aria-label={s.label} style={{
                flex: 1, height: 4, borderRadius: 2, border: 'none', padding: 0, cursor: 'pointer',
                background: idx === i ? DA.brand : idx < i ? 'rgba(249,115,22,0.4)' : 'rgba(255,255,255,0.15)',
                transition: 'background 0.3s',
              }}/>
            ))}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button onClick={() => go(i - 1)} style={demoNavBtn(DA)}>← Back</button>
            <button onClick={() => go(i + 1)} style={{ ...demoNavBtn(DA), background: DA.brandLight, borderColor: DA.brandLight, color: DA.ink }}>
              {i === DEMO_STEPS.length - 1 ? 'Restart' : 'Next →'}
            </button>
            <button onClick={() => setPaused((p) => !p)} style={{ ...demoNavBtn(DA), padding: '10px 14px' }} aria-label={paused ? 'Play' : 'Pause'}>
              {paused ? '▶' : 'II'}
            </button>
          </div>

          <button type="button" onClick={() => { setOpen(false); window.openEarlyAccess && window.openEarlyAccess(); }} style={{
            display: 'inline-block', marginTop: 24, fontSize: 14, fontWeight: 700,
            color: DA.brandLight, background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: DA.font,
          }}>Request early access →</button>
        </div>
      </div>

      <style>{`
        @keyframes demoFadeIn { from { opacity: 0; } to { opacity: 1; } }
        .demo-fade { animation: demoFadeIn 0.55s ease both; }
        @keyframes demoPhoneIn { from { opacity: 0; transform: scale(0.94) translateY(10px); } to { opacity: 1; transform: scale(1) translateY(0); } }
        .demo-phone-in { animation: demoPhoneIn 0.6s cubic-bezier(0.22, 1, 0.36, 1) both; }
        @keyframes demoCaretBlink { 0%, 100% { opacity: 1; } 50% { opacity: 0.12; } }
        .demo-caret { animation: demoCaretBlink 1.15s ease-in-out infinite; }
        @media (max-width: 760px) {
          .demo-grid { grid-template-columns: 1fr !important; gap: 24px !important; max-height: none !important; overflow: visible !important; }
          .demo-caption { text-align: center; }
          .demo-caption p, .demo-caption > div[style*="max-width"] { margin-left: auto; margin-right: auto; }
        }
      `}</style>
    </div>
  );

  return ReactDOM.createPortal(modal, document.body);
}

function demoNavBtn(DA) {
  return {
    padding: '10px 20px', borderRadius: 6, cursor: 'pointer',
    background: 'transparent', border: '1px solid rgba(255,255,255,0.22)',
    color: '#fff', fontSize: 14, fontWeight: 700, fontFamily: DA.font,
  };
}

window.DemoModal = DemoModal;
