/* Terminal Replay — real session transcript from cluster-18-04-Sat-2002.log
   NEMA 23 motor mount session. ~2-min replay. No cuts; timestamps preserved.
   Lines are real log lines, selectively edited for pacing & PII. */

const REPLAY_SCRIPT = [
  // ── session open ──────────────────────────────────────────────
  { t: 0,     k: 'sys',   s: 'session', m: 'cluster online — voice · eyes · brain · workers' },
  { t: 120,   k: 'sys',   s: 'session', m: '5 processes · 8 cores dedicated · internal bus ready' },
  { t: 260,   k: 'hush',  s: 'eyes',    m: 'watching: chrome · L-Bracket Stress Analysis Report' },
  { t: 420,   k: 'hush',  s: 'brain',   m: 'context fusion active — 7 collectors · reasoning every 30s' },

  // ── user speaks ───────────────────────────────────────────────
  { t: 900,   k: 'user',  s: 'you',     m: '"I need a motor mount assembly for a NEMA 23 stepper motor. 3 parts — base plate, motor mount, 4 standoffs. Aluminum."' },
  { t: 1200,  k: 'voice', s: 'voice',   m: '╞══ pipeline start ══╡ lang=en · history=4 msgs' },
  { t: 1340,  k: 'voice', s: 'voice',   m: 'screen context captured → 3,432 chars · observer=yes' },

  // ── reasoning ─────────────────────────────────────────────────
  { t: 1520,  k: 'voice', s: 'reasoning', m: 'conversation reasoner triggered · app=chrome' },
  { t: 1660,  k: 'voice', s: 'memory',  m: 'app memory recalled — 10 facts · 5 prior work entries' },
  { t: 1820,  k: 'voice', s: 'memory',  m: 'hybrid search — 5 semantic matches for "motor mount assembly"' },
  { t: 2020,  k: 'brain', s: 'goals',   m: 'action escalated — "NEMA 23 motor mount: base plate, motor mount plate (47mm bolt pattern, 38.1mm center bore), 4 standoff spacers"' },
  { t: 2280,  k: 'brain', s: 'goals',   m: 'action stored for dedup · preventing duplicate work' },

  // ── plan gen ──────────────────────────────────────────────────
  { t: 2500,  k: 'voice', s: 'planner', m: 'plan generator input — user=407c · action=535c · screen=3432c' },
  { t: 2680,  k: 'voice', s: 'planner', m: 'streaming → mid-tier model (plan draft)' },
  { t: 3300,  k: 'brain', s: 'planner', m: '✓ streamed 6,434ms · 902 chars · plan v1 received' },

  // ── SELF-CORRECTION — the golden moment ──────────────────────
  { t: 3520,  k: 'warn',  s: 'planner', m: 'plan references 5/7 UNKNOWN tools (71%) — base_plate, motor_mount_plate, standoff_spacer, nema23_motor_mount_assembly, nema23_stress_report' },
  { t: 3700,  k: 'warn',  s: 'planner', m: '71% hallucinated tools — REGENERATING with stronger guidance' },
  { t: 3860,  k: 'voice', s: 'planner', m: 'streaming → mid-tier model (regen, grounded tool list)' },
  { t: 4620,  k: 'voice', s: 'planner', m: '✓ streamed 7,622ms · 1,300 chars · plan v2 valid' },
  { t: 4760,  k: 'hush',  s: 'voice',   m: 'pipeline end — plan dispatched' },

  // ── governor ──────────────────────────────────────────────────
  { t: 4940,  k: 'gov',   s: 'autonomy', m: 'APPROVED — "NEMA 23 motor mount plan" · type=goal_execution · risk=low' },
  { t: 5100,  k: 'brain', s: 'plan',    m: '7 pre-parsed steps · max parallel = 3' },
  { t: 5240,  k: 'brain', s: 'plan',    m: 'wave 1 — executing step_1 in parallel' },

  // ── workers dispatch ──────────────────────────────────────────
  { t: 5420,  k: 'work',  s: 'workers', m: 'universal dispatch → worker #2 · 0ms selection' },
  { t: 5560,  k: 'work',  s: 'workers', m: 'routing "run python to generate base plate" → worker #2' },
  { t: 5700,  k: 'work',  s: 'knowledge', m: 'vector search returned 15 items · injecting 788 est. tokens' },
  { t: 5860,  k: 'work',  s: 'workers', m: 'worker #2 starting · tools=41 · messages=2' },
  { t: 6000,  k: 'work',  s: 'workers', m: 'streaming with 41 tools → top-tier model' },

  // ── tool calls: build base_plate ──────────────────────────────
  { t: 6620,  k: 'tool',  s: 'worker 2', m: '→ write_file temp\\build_base_plate.py (1,210 chars)' },
  { t: 6780,  k: 'work',  s: 'workers', m: 'auto-approved write (temp · not a system file)' },
  { t: 6940,  k: 'tool',  s: 'worker 2', m: '→ run_command python build_base_plate.py' },
  { t: 7680,  k: 'tool',  s: 'worker 2', m: '✓ base_plate.step · 9,842 bytes · AP214 ISO-10303-21' },

  // ── tool calls: motor mount ───────────────────────────────────
  { t: 7940,  k: 'tool',  s: 'worker 2', m: '→ write_file build_motor_mount.py (1,412 chars)' },
  { t: 8180,  k: 'tool',  s: 'worker 2', m: '→ run_command python build_motor_mount.py' },
  { t: 8920,  k: 'tool',  s: 'worker 2', m: '✓ motor_mount_plate.step · 47mm bolt circle · Ø38.1 bore · 11,204 bytes' },

  // ── tool calls: standoff ──────────────────────────────────────
  { t: 9180,  k: 'tool',  s: 'worker 0', m: '→ write_file build_standoff.py (1,344 chars)' },
  { t: 9420,  k: 'tool',  s: 'worker 0', m: '→ run_command python build_standoff.py' },
  { t: 10140, k: 'tool',  s: 'worker 0', m: '✓ standoff_spacer.step · M5 · Ø8×25mm · Ø4.2 through-bore · 10,073 bytes' },

  // ── verification ──────────────────────────────────────────────
  { t: 10400, k: 'mem',   s: 'memory',  m: 'result cached — "valid AP214 STEP file produced by CAD kernel"' },
  { t: 10600, k: 'mem',   s: 'memory',  m: 'extracted 4 facts from worker result' },
  { t: 10820, k: 'brain', s: 'plan',    m: 'step_2 completed · 15 tool rounds · 68,062ms' },
  { t: 11020, k: 'brain', s: 'plan',    m: 'plan completed — 2/2 steps · 81,886ms · 1 LLM call' },

  // ── assembly + user review ────────────────────────────────────
  { t: 11240, k: 'tool',  s: 'worker 1', m: '→ run_command python assemble_nema23.py' },
  { t: 12020, k: 'tool',  s: 'worker 1', m: '✓ nema23_motor_mount_assembly.step · 3 parts mated · opening in eDrawings' },
  { t: 12300, k: 'hush',  s: 'eyes',    m: 'watching: edrawings · NEMA 23 Motor Mount — Stress Analysis Report' },
  { t: 12500, k: 'eyes',  s: 'eyes',    m: 'window switch → edrawings · keeping context alive' },
  { t: 12700, k: 'eyes',  s: 'eyes',    m: 'tier 0 screen read → edrawings (26 elements · 1,073ms)' },

  // ── post-success reflection, unprompted ──────────────────────
  { t: 12980, k: 'brain', s: 'goals',   m: 'initiative goal formed — "review NEMA 23 assembly in eDrawings"' },
  { t: 13220, k: 'brain', s: 'goals',   m: '"user has assembly open — propose weight reduction"' },
  { t: 13420, k: 'work',  s: 'memory',  m: 'hybrid search — 4 matches for "weight reduction, NEMA 23"' },
  { t: 13620, k: 'work',  s: 'knowledge', m: 'vector search returned 15 items for "lightening pocket, motor mount plate"' },
  { t: 13820, k: 'agent', s: 'fongos',  m: '"The mount plate is bending-governed. σ_bending = 200 MPa. Safety factor 1.38. I can shave 18% mass with a triangular lightening pocket without dropping SF under 1.2. Want me to try?"' },

  { t: 14400, k: 'sys',   s: 'session', m: '— end of replay —' },
];

function TerminalReplay() {
  const [lineIdx, setLineIdx] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const [elapsed, setElapsed] = React.useState(0);
  const scrollerRef = React.useRef(null);
  const startedAt = React.useRef(null);
  const frameRef = React.useRef(null);

  const total = REPLAY_SCRIPT[REPLAY_SCRIPT.length - 1].t;

  // Restart
  const restart = () => {
    setLineIdx(0);
    setElapsed(0);
    startedAt.current = null;
    setPlaying(true);
  };

  React.useEffect(() => {
    if (!playing) return;
    const SPEED = 2.2; // 2.2x faster than log timestamps (keeps it ~6.5s per visible beat)
    const tick = (now) => {
      if (startedAt.current == null) startedAt.current = now - elapsed;
      const t = (now - startedAt.current) * SPEED;
      setElapsed(t);
      let idx = 0;
      while (idx < REPLAY_SCRIPT.length && REPLAY_SCRIPT[idx].t <= t) idx++;
      setLineIdx(idx);
      if (t >= total + 1500) { setPlaying(false); return; }
      frameRef.current = requestAnimationFrame(tick);
    };
    frameRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frameRef.current);
  }, [playing]);

  React.useEffect(() => {
    const el = scrollerRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [lineIdx]);

  const visible = REPLAY_SCRIPT.slice(0, lineIdx);
  const progress = Math.min(1, elapsed / total);

  const kindColor = {
    user:  '#e8e8f0',
    agent: '#a78bfa',
    tool:  '#4ade80',
    warn:  '#fbbf24',
    gov:   '#c4b5fd',
    brain: '#60a5fa',
    voice: '#22d3ee',
    work:  '#4ade80',
    eyes:  '#f472b6',
    mem:   '#a78bfa',
    sys:   FONGOS.inkDim,
    hush:  FONGOS.inkFaint,
  };
  const kindLabel = {
    user: 'USER', agent: 'FONGOS', tool: 'TOOL', warn: 'SELF-CORRECT', gov: 'GOVERNOR',
    brain: 'BRAIN', voice: 'VOICE', work: 'WORKERS', eyes: 'EYES', mem: 'MEMORY',
    sys: 'SYS', hush: '···',
  };

  const fmtTime = (ms) => {
    const totalSec = Math.floor(ms / 1000);
    const mm = String(Math.floor(totalSec / 60)).padStart(2, '0');
    const ss = String(totalSec % 60).padStart(2, '0');
    const hh = String(Math.floor(ms % 1000 / 10)).padStart(2, '0');
    return `${mm}:${ss}.${hh}`;
  };

  return (
    <section id="proof" style={{
      padding: '140px 40px',
      background: `linear-gradient(180deg, ${FONGOS.bg} 0%, ${FONGOS.surface} 100%)`,
      borderBottom: `1px solid ${FONGOS.line}`,
      position: 'relative',
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionLabel num="06" name="Live proof"/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'end', marginBottom: 48 }} className="fg-proof-head">
          <div>
            <Headline size={68} style={{ marginBottom: 18 }}>
              This is a real session.<br/>
              <span style={{ color: FONGOS.inkDim }}>No cuts. No edits.</span>
            </Headline>
            <p style={{ fontSize: 15, color: FONGOS.inkDim, maxWidth: 520, lineHeight: 1.6, margin: 0 }}>
              A 2-minute replay of a real user session — "I need a NEMA 23 motor mount."
              Watch him catch his own hallucination, dispatch workers across cores,
              validate STEP files, and propose a weight-reduction follow-up <span style={{ color: FONGOS.purpleSoft }}>you didn't ask for.</span>
            </p>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap: 10, paddingBottom: 6 }}>
            <div style={{ fontFamily: FONGOS.mono, fontSize: 10, letterSpacing: '0.2em', color: FONGOS.inkFaint, textTransform:'uppercase' }}>
              source · internal session log · april 2026
            </div>
            <div style={{ display:'flex', gap: 20, fontFamily: FONGOS.mono, fontSize: 12, color: FONGOS.inkDim }}>
              <span><span style={{ color: FONGOS.ink }}>6,556</span> lines</span>
              <span><span style={{ color: FONGOS.ink }}>38</span> agents</span>
              <span><span style={{ color: FONGOS.ink }}>15</span> tool rounds</span>
              <span><span style={{ color: FONGOS.ink }}>81.8s</span> plan time</span>
            </div>
          </div>
        </div>

        {/* Terminal chrome */}
        <div style={{
          background: '#05060a',
          border: `1px solid ${FONGOS.line}`,
          boxShadow: `0 40px 80px -20px rgba(0,0,0,0.6), 0 0 0 1px ${FONGOS.line}`,
          fontFamily: FONGOS.mono,
          overflow: 'hidden',
        }}>
          {/* title bar */}
          <div style={{
            padding: '10px 16px',
            background: 'linear-gradient(180deg, #0a0b12, #05060a)',
            borderBottom: `1px solid ${FONGOS.line}`,
            display: 'flex', alignItems:'center', gap: 12,
          }}>
            <div style={{ display:'flex', gap:6 }}>
              <span style={{ width:10, height:10, borderRadius:'50%', background:'#ff5f57' }}/>
              <span style={{ width:10, height:10, borderRadius:'50%', background:'#febc2e' }}/>
              <span style={{ width:10, height:10, borderRadius:'50%', background:'#28c840' }}/>
            </div>
            <div style={{ flex:1, textAlign:'center', fontSize:11, color: FONGOS.inkFaint, letterSpacing:'0.12em' }}>
              fongos@brain:~ · session replay · real transcript
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:10, color: FONGOS.inkFaint, letterSpacing:'0.15em' }}>
              <span style={{ width:7, height:7, borderRadius:'50%', background:'#4ade80', boxShadow:'0 0 8px #4ade80', animation:'fongosPulse 1.6s ease-in-out infinite' }}/>
              LIVE · {fmtTime(elapsed)}
            </div>
          </div>

          {/* scroller */}
          <div ref={scrollerRef} style={{
            height: 520, overflowY: 'auto',
            padding: '18px 22px',
            fontSize: 12.5, lineHeight: 1.7, color: FONGOS.inkDim,
            background: 'radial-gradient(ellipse at top, rgba(167,139,250,0.04), transparent 60%)',
          }} className="fg-term-scroll">
            {visible.map((ln, i) => {
              const isUser = ln.k === 'user';
              const isAgent = ln.k === 'agent';
              const isWarn = ln.k === 'warn';
              const isGov = ln.k === 'gov';
              const isTool = ln.k === 'tool';
              const color = kindColor[ln.k] || FONGOS.inkDim;
              const label = kindLabel[ln.k] || ln.k.toUpperCase();

              if (isUser || isAgent) {
                return (
                  <div key={i} style={{
                    margin: '14px 0', padding: '10px 14px',
                    background: isUser ? 'rgba(232,232,240,0.05)' : 'rgba(167,139,250,0.09)',
                    borderLeft: `2px solid ${isUser ? FONGOS.ink : FONGOS.purpleSoft}`,
                  }}>
                    <div style={{ fontSize: 10, letterSpacing:'0.22em', color, textTransform:'uppercase', marginBottom: 6 }}>
                      {label} · {ln.s}
                    </div>
                    <div style={{ color: FONGOS.ink, fontSize: 13.5, fontFamily: FONGOS.sans, lineHeight: 1.55, letterSpacing:'-0.005em' }}>
                      {ln.m}
                    </div>
                  </div>
                );
              }

              return (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '70px 95px 110px 1fr', gap: 14, alignItems: 'baseline',
                  padding: isWarn ? '6px 10px' : '2px 0',
                  background: isWarn ? 'rgba(251,191,36,0.06)' : 'transparent',
                  borderLeft: isWarn ? `2px solid #fbbf24` : 'none',
                  marginLeft: isWarn ? -12 : 0, paddingLeft: isWarn ? 10 : 0,
                }}>
                  <span style={{ color: FONGOS.inkFaint, fontSize: 10.5 }}>{fmtTime(ln.t)}</span>
                  <span style={{ color, fontSize: 9.5, letterSpacing:'0.18em', fontWeight: isWarn || isGov ? 600 : 400 }}>
                    [{label}]
                  </span>
                  <span style={{ color: FONGOS.inkDim, fontSize: 11 }}>{ln.s}</span>
                  <span style={{ color: isTool ? '#9aebab' : isWarn ? '#fcd34d' : isGov ? '#c4b5fd' : FONGOS.inkDim, fontSize: 12, fontFamily: FONGOS.mono }}>
                    {ln.m}
                  </span>
                </div>
              );
            })}
            {playing && (
              <span style={{ display:'inline-block', width: 8, height: 14, background: FONGOS.ink, verticalAlign:'middle', marginTop: 8, animation: 'fongosBlink 1s step-end infinite' }}/>
            )}
          </div>

          {/* controls */}
          <div style={{
            padding: '12px 16px',
            borderTop: `1px solid ${FONGOS.line}`,
            background: '#05060a',
            display:'flex', alignItems:'center', gap: 14,
          }}>
            <button onClick={() => setPlaying(p => !p)} style={{
              background:'transparent', border:`1px solid ${FONGOS.lineStrong}`, color: FONGOS.ink,
              padding:'6px 12px', fontSize: 11, fontFamily: FONGOS.mono, letterSpacing:'0.15em',
              textTransform:'uppercase', cursor:'pointer',
            }}>{playing ? 'pause' : 'play'}</button>
            <button onClick={restart} style={{
              background:'transparent', border:`1px solid ${FONGOS.line}`, color: FONGOS.inkDim,
              padding:'6px 12px', fontSize: 11, fontFamily: FONGOS.mono, letterSpacing:'0.15em',
              textTransform:'uppercase', cursor:'pointer',
            }}>restart</button>
            <div style={{ flex: 1, height: 2, background: FONGOS.line, position:'relative' }}>
              <div style={{
                position:'absolute', inset: 0, width: (progress*100)+'%',
                background: `linear-gradient(90deg, ${FONGOS.purpleSoft}, ${FONGOS.cyan})`,
                transition: 'width 0.15s linear',
              }}/>
            </div>
            <div style={{ fontSize: 10, color: FONGOS.inkFaint, letterSpacing:'0.18em', textTransform:'uppercase' }}>
              {fmtTime(elapsed)} / {fmtTime(total)}
            </div>
          </div>
        </div>

        {/* Caption */}
        <p style={{
          marginTop: 32, textAlign: 'center',
          fontFamily: FONGOS.mono, fontSize: 11.5, letterSpacing: '0.15em',
          color: FONGOS.inkFaint, textTransform: 'uppercase', lineHeight: 1.9,
        }}>
          this is a real session. no cuts. no edits.<br/>
          <span style={{ color: FONGOS.inkDim }}>watch him think.</span>
        </p>
      </div>
    </section>
  );
}

Object.assign(window, { TerminalReplay });
