// CliInstallReplay — animated terminal showing a realistic `npx sekura init`
// session. Lives on the /cicd/ page above the static workflow YAML so users
// see what the install actually feels like before reading the config.
//
// No external deps. The animation is a single setState loop driven by
// requestAnimationFrame-ish setTimeouts. Pauses/restarts via the inline
// control row. Reduced motion: jumps to the final frame and stays there.

function CliInstallReplay() {
  const { React } = window;
  const { useState, useEffect, useRef } = React;

  // Each entry is one terminal "event". `type` controls how it renders.
  //   'prompt' — the user's typed command (preceded by $)
  //   'log'    — a plain output line
  //   'ok'     — ✓ green output line
  //   'arrow'  — → cyan/coral output line (action in progress)
  //   'group'  — indented sub-line under a prior log
  //   'wait'   — typed nothing, just adds a pause
  //   'link'   — output line that contains a URL
  // `wait` is the ms before this line appears (after the previous one finishes).
  const SCRIPT = [
    { type: 'prompt', text: 'npx sekura@latest init', wait: 400 },
    { type: 'log',    text: '↳ fetching @sekura/cli@latest from registry.npmjs.org', wait: 700 },
    { type: 'log',    text: '↳ verified signature · running...', wait: 900 },
    { type: 'arrow',  text: 'detecting development environments…', wait: 700 },
    { type: 'ok',     text: 'Claude Code', indent: true, wait: 250 },
    { type: 'ok',     text: 'Cursor',      indent: true, wait: 220 },
    { type: 'ok',     text: 'VS Code',     indent: true, wait: 220 },
    { type: 'ok',     text: 'Windsurf',    indent: true, wait: 220 },
    { type: 'ok',     text: 'registered Sekura MCP server in 4 IDEs', wait: 600 },
    { type: 'arrow',  text: 'opening browser for GitHub OAuth…', wait: 1000 },
    { type: 'ok',     text: 'signed in as @yourhandle', wait: 700 },
    { type: 'ok',     text: 'token stored in OS keychain (keytar)', wait: 600 },
    { type: 'log',    text: '? select a repo to scan:', wait: 700 },
    { type: 'group',  text: '▸ acme/payments-service', wait: 220 },
    { type: 'group',  text: '  acme/auth-api', wait: 200 },
    { type: 'group',  text: '  acme/web-platform', wait: 600 },
    { type: 'ok',     text: 'committed .github/workflows/sekura.yml', wait: 900 },
    { type: 'ok',     text: 'set SEKURA_TOKEN as repo secret', wait: 700 },
    { type: 'arrow',  text: 'dispatching first scan on your runner…', wait: 900 },
    { type: 'link',   text: 'scan running → github.com/acme/payments-service/actions/runs/8194730', wait: 1100 },
    { type: 'ok',     text: 'done in 27s', wait: 700 },
    { type: 'log',    text: '', wait: 400 },
    { type: 'log',    text: 'next: open a PR — Sekura will review it inline.', wait: 600 },
  ];

  const TOTAL_MS = SCRIPT.reduce((a, s) => a + s.wait, 0);
  const RESTART_PAUSE = 4000;

  const [revealed, setRevealed] = useState(0);
  const [paused, setPaused] = useState(false);
  const reduceMotion = useRef(false);

  useEffect(() => {
    reduceMotion.current =
      window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduceMotion.current) setRevealed(SCRIPT.length);
  }, []);

  useEffect(() => {
    if (paused || reduceMotion.current) return;
    if (revealed >= SCRIPT.length) {
      const id = setTimeout(() => setRevealed(0), RESTART_PAUSE);
      return () => clearTimeout(id);
    }
    const step = SCRIPT[revealed];
    const id = setTimeout(() => setRevealed(revealed + 1), step.wait);
    return () => clearTimeout(id);
  }, [revealed, paused]);

  const progress = Math.min(
    100,
    Math.round(
      (SCRIPT.slice(0, revealed).reduce((a, s) => a + s.wait, 0) / TOTAL_MS) * 100,
    ),
  );

  const renderLine = (entry, i) => {
    const typing = i === revealed - 1;
    if (entry.type === 'prompt') {
      return (
        <div key={i} className="cli-line cli-line--prompt">
          <span className="cli-prompt-marker">$</span>
          <span className="cli-text">{entry.text}</span>
          {typing && <span className="cli-cursor" />}
        </div>
      );
    }
    if (entry.type === 'ok') {
      return (
        <div key={i} className={`cli-line cli-line--ok ${entry.indent ? 'is-indent' : ''}`}>
          <span className="cli-glyph cli-glyph--ok">✓</span>
          <span className="cli-text">{entry.text}</span>
        </div>
      );
    }
    if (entry.type === 'arrow') {
      return (
        <div key={i} className="cli-line cli-line--arrow">
          <span className="cli-glyph cli-glyph--arrow">→</span>
          <span className="cli-text">{entry.text}</span>
          {typing && <span className="cli-cursor" />}
        </div>
      );
    }
    if (entry.type === 'group') {
      return (
        <div key={i} className="cli-line cli-line--group">
          <span className="cli-text">{entry.text}</span>
        </div>
      );
    }
    if (entry.type === 'link') {
      return (
        <div key={i} className="cli-line cli-line--link">
          <span className="cli-text">{entry.text}</span>
        </div>
      );
    }
    // 'log' or default
    return (
      <div key={i} className="cli-line cli-line--log">
        <span className="cli-text">{entry.text}</span>
      </div>
    );
  };

  return (
    <section className="cli-replay-section" aria-label="Animated CLI install replay">
      <div className="cli-replay-frame">
        <div className="cli-replay-chrome">
          <div className="cli-replay-dots" aria-hidden="true">
            <span className="cli-dot cli-dot--r" />
            <span className="cli-dot cli-dot--y" />
            <span className="cli-dot cli-dot--g" />
          </div>
          <div className="cli-replay-title">~/your-repo · zsh · npx sekura</div>
          <div className="cli-replay-ctrls">
            <button
              type="button"
              onClick={() => setPaused(p => !p)}
              aria-label={paused ? 'play' : 'pause'}
              className="cli-replay-ctrl"
            >
              {paused ? '▶' : '❚❚'}
            </button>
            <button
              type="button"
              onClick={() => { setRevealed(0); setPaused(false); }}
              aria-label="restart"
              className="cli-replay-ctrl"
            >
              ↻
            </button>
          </div>
        </div>
        <div className="cli-replay-body">
          {SCRIPT.slice(0, revealed).map((entry, i) => renderLine(entry, i))}
        </div>
        <div className="cli-replay-progress" aria-hidden="true">
          <div className="cli-replay-progress-bar" style={{ width: `${progress}%` }} />
        </div>
      </div>
      <p className="cli-replay-caption">
        ~30 seconds end-to-end. Loops automatically.
      </p>
    </section>
  );
}

window.CliInstallReplay = CliInstallReplay;
