// DemoPlayer — a "video" of Pulse running the floor, drawn in the sketch
// wireframe style. Scripted ~32s timeline: tasks progress, one blocks,
// you answer by voice, it resolves. Play/pause + scrubber + persistence.
// Exports: DemoPlayer

const DEMO_DUR = 32;

// ---- scripted task states as a function of time ----
function demoTasks(t) {
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  const api = (() => {
    if (t < 9)  return { status: 'running', pct: clamp(70 + t * 1.1, 0, 80), log: 'finishing token refresh…' };
    if (t < 20) return { status: 'needs',   pct: 80, log: 'awaiting approval: run db migration?' };
    if (t < 24) return { status: 'running', pct: clamp(80 + (t - 20) * 5, 80, 99), log: 'running migration…' };
    return { status: 'done', pct: 100, log: 'migration clean · auth merged ✓' };
  })();
  return [
    { id: 'd1', repo: 'pulse-api', title: 'Fix auth token refresh', runtime: '12:40', diff: '+124 −30', ...api },
    { id: 'd2', repo: 'search', title: 'Index rebuild script', runtime: '31:48', diff: '+154 −61',
      status: t < 5 ? 'running' : 'done', pct: clamp(60 + t * 8, 60, 100),
      log: t < 5 ? 'reindexing 1.2M docs…' : 'rebuilt 1.2M docs · all green' },
    { id: 'd3', repo: 'webapp', title: 'Dark mode pass', runtime: '04:12', diff: '+48 −9',
      status: 'running', pct: clamp(35 + t * 1.3, 35, 78), log: 'editing theme.css…' },
    { id: 'd4', repo: 'infra', title: 'Split terraform modules', runtime: '08:51', diff: '+88 −140',
      status: 'running', pct: clamp(50 + t * 0.8, 50, 72), log: 'refactoring vpc module…' },
  ];
}

const DEMO_CAPTIONS = [
  { at: 0,    who: 'pulse', text: 'Four tasks on the floor. webapp is halfway through the dark-mode pass.' },
  { at: 5,    who: 'pulse', text: 'search just finished — 1.2M docs reindexed, all green.' },
  { at: 9,    who: 'pulse', text: 'pulse-api needs a call: okay to run the db migration?' },
  { at: 15,   who: 'you',   text: '“ship it.”' },
  { at: 18,   who: 'pulse', text: 'Running it now — I\u2019ll keep you posted.' },
  { at: 24,   who: 'pulse', text: 'Done. Migration ran clean, auth is merged.' },
];

function demoCaption(t) {
  let cur = DEMO_CAPTIONS[0];
  for (const c of DEMO_CAPTIONS) { if (t >= c.at) cur = c; }
  return cur;
}

function fmtTime(t) {
  const s = Math.floor(t);
  return `0:${String(s).padStart(2, '0')}`;
}

// ---- one task row inside the demo (compact) ----
function DemoRow({ s, accent }) {
  const needs = s.status === 'needs';
  return (
    <div className="wf-box r3" style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '10px 16px', background: '#fff',
      borderColor: needs ? accent : '#2b2a28', borderWidth: needs ? 3 : 2,
      transition: 'border-color .3s',
    }}>
      <StatusDot status={s.status} accent={accent} size={14} />
      <div style={{ width: 190, flex: 'none' }}>
        <div style={{ fontWeight: 700, fontSize: 17, lineHeight: 1.1 }}>{s.repo}</div>
        <div style={{ fontSize: 14, color: '#55504a', lineHeight: 1.1 }}>{s.title}</div>
      </div>
      <div style={{ width: 140, flex: 'none' }}>
        <ProgressBar pct={s.pct} accent={accent} status={s.status} />
      </div>
      <div className="wf-mono" style={{ flex: 1, minWidth: 0, fontSize: 12.5, color: '#55504a', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
        » {s.log}
      </div>
      <span style={{ flex: 'none', fontSize: 13, width: 78, textAlign: 'right' }}>
        <StatusWord status={s.status} accent={accent} />
      </span>
    </div>
  );
}

function DemoPlayer({ accent }) {
  const [t, setT] = React.useState(() => {
    const v = parseFloat(localStorage.getItem('pulse-landing-demo-t'));
    return Number.isFinite(v) ? Math.min(v, DEMO_DUR) : 0;
  });
  const [playing, setPlaying] = React.useState(false);
  const tRef = React.useRef(t);
  tRef.current = t;

  React.useEffect(() => {
    if (!playing) return;
    let last = performance.now();
    let raf;
    const tick = (now) => {
      const dt = (now - last) / 1000; last = now;
      let next = tRef.current + dt;
      if (next >= DEMO_DUR) { next = DEMO_DUR; setPlaying(false); }
      setT(next);
      localStorage.setItem('pulse-landing-demo-t', String(next));
      if (next < DEMO_DUR) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  const seek = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    const frac = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));
    const next = frac * DEMO_DUR;
    setT(next);
    localStorage.setItem('pulse-landing-demo-t', String(next));
  };

  const toggle = () => {
    if (!playing && t >= DEMO_DUR) { setT(0); localStorage.setItem('pulse-landing-demo-t', '0'); }
    setPlaying(!playing);
  };

  const tasks = demoTasks(t);
  const rank = { needs: 0, done: 1, running: 2 };
  const ordered = [...tasks].sort((a, b) => rank[a.status] - rank[b.status]);
  const cap = demoCaption(t);
  const ended = t >= DEMO_DUR;
  const poster = !playing && t === 0;
  const speaking = playing && cap.who === 'pulse';

  return (
    <div className="wf-box r1" style={{ overflow: 'hidden', background: '#fff', position: 'relative' }}>
      {/* "video" surface */}
      <div className="wf-stars" style={{ display: 'flex', minHeight: 380, position: 'relative' }}>
        {/* agent rail */}
        <div style={{ width: 230, flex: 'none', borderRight: '2px solid #2b2a28', background: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '30px 20px 22px', gap: 16 }}>
          <AgentAvatar variant="Bot face" size={96} accent={accent} talking={speaking} />
          <div className="wf-annot" style={{ fontSize: 20, color: cap.who === 'you' ? '#2b2a28' : accent, textAlign: 'center', lineHeight: 1.2, minHeight: 72 }}>
            {cap.who === 'you' ? <span><span className="wf-mono" style={{ fontSize: 12, color: '#98917f' }}>you · voice</span><br />{cap.text}</span> : cap.text}
          </div>
          <div className="wf-box r3" style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 9, padding: '7px 14px', background: '#fff', borderColor: cap.who === 'you' ? accent : '#2b2a28' }}>
            <span className={cap.who === 'you' ? 'wf-pulse' : ''} style={{ width: 10, height: 10, borderRadius: '50%', background: accent, display: 'block' }}></span>
            <span className="wf-annot" style={{ fontSize: 16, color: '#6f6a60' }}>hold to talk</span>
          </div>
        </div>
        {/* task stack */}
        <div style={{ flex: 1, minWidth: 0, padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
            <span style={{ fontSize: 19, fontWeight: 700 }}>The floor</span>
            <span className="wf-annot" style={{ fontSize: 17, color: '#98917f' }}>blocked first, then done, then running</span>
            <span className="wf-mono" style={{ marginLeft: 'auto', fontSize: 12, color: '#98917f' }}>
              {tasks.filter((s) => s.status === 'running').length} running · {tasks.filter((s) => s.status === 'needs').length} need you
            </span>
          </div>
          {ordered.map((s) => <DemoRow key={s.id} s={s} accent={accent} />)}
        </div>

        {/* poster overlay */}
        {poster && (
          <div onClick={toggle} style={{
            position: 'absolute', inset: 0, background: 'rgba(250,248,243,0.82)', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, zIndex: 3,
          }}>
            <div className="wf-pulse" style={{
              width: 92, height: 92, borderRadius: '50%', border: `3px solid ${accent}`, background: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '4px 4px 0 rgba(43,42,40,0.12)',
            }}>
              <span style={{
                width: 0, height: 0, marginLeft: 7,
                borderTop: '17px solid transparent', borderBottom: '17px solid transparent',
                borderLeft: `28px solid ${accent}`, display: 'block',
              }}></span>
            </div>
            <div className="wf-annot" style={{ fontSize: 24, color: '#2b2a28' }}>watch Pulse run the floor — 32 sec</div>
          </div>
        )}

        {/* end card */}
        {ended && !playing && (
          <div onClick={toggle} style={{
            position: 'absolute', inset: 0, background: 'rgba(250,248,243,0.9)', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, zIndex: 3,
          }}>
            <div style={{ fontSize: 40, fontWeight: 700, fontFamily: "'Patrick Hand', cursive", color: '#2b2a28' }}>
              That’s Pulse.
            </div>
            <div className="wf-annot" style={{ fontSize: 21, color: '#6f6a60' }}>one voice, four tasks, zero babysitting · click to replay ↻</div>
          </div>
        )}
      </div>

      {/* control bar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 16px', borderTop: '2px solid #2b2a28', background: '#f4f1ea' }}>
        <button onClick={toggle} className="wf-box r3" style={{
          width: 40, height: 34, flex: 'none', cursor: 'pointer', background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
        }} aria-label={playing ? 'Pause' : 'Play'}>
          {playing ? (
            <span style={{ display: 'flex', gap: 4 }}>
              <span style={{ width: 4, height: 14, background: '#2b2a28', display: 'block' }}></span>
              <span style={{ width: 4, height: 14, background: '#2b2a28', display: 'block' }}></span>
            </span>
          ) : (
            <span style={{
              width: 0, height: 0, marginLeft: 3,
              borderTop: '8px solid transparent', borderBottom: '8px solid transparent',
              borderLeft: `13px solid #2b2a28`, display: 'block',
            }}></span>
          )}
        </button>
        <div onClick={seek} style={{ flex: 1, padding: '6px 0', cursor: 'pointer' }}>
          <div className="wf-box r2" style={{ height: 14, padding: 2, background: '#fff' }}>
            <div style={{ width: `${(t / DEMO_DUR) * 100}%`, height: '100%', background: accent, borderRadius: 6, transition: playing ? 'none' : 'width .15s' }}></div>
          </div>
        </div>
        <span className="wf-mono" style={{ flex: 'none', fontSize: 13, color: '#6f6a60' }}>{fmtTime(t)} / {fmtTime(DEMO_DUR)}</span>
        <span className="wf-box r3 wf-mono" style={{ flex: 'none', fontSize: 11, color: '#6f6a60', padding: '2px 10px', background: '#fff' }}>demo</span>
      </div>
    </div>
  );
}

window.DemoPlayer = DemoPlayer;
