/* global React */
// Animated CLI demo — types a command, streams JSON output, then a signed receipt.

const { useEffect, useState, useRef } = React;

const SCRIPT = [
  { t: 'cmd', text: 'mece ask "top 10 agent evals with runnable code" --source digg:all --format json' },
  { t: 'wait', ms: 600 },
  { t: 'line', text: '↳ resolving niche...                ai-agents-daily', tone: 'dim' },
  { t: 'line', text: '↳ ledger.Reserve(haiku, max=512)    [OK] 8500 µcr', tone: 'ok' },
  { t: 'line', text: '↳ crawl shared source pool          zyte:cache hit', tone: 'dim' },
  { t: 'line', text: '↳ dedupe + summarize                23 items kept', tone: 'dim' },
  { t: 'line', text: '↳ rerank (haiku, 487 in / 96 out)   [OK]', tone: 'ok' },
  { t: 'wait', ms: 250 },
  { t: 'json' },
  { t: 'wait', ms: 350 },
  { t: 'line', text: '✓ receipt signed · ed25519:7f3a..91c2', tone: 'trust' },
  { t: 'line', text: '✓ refunded unused output tokens     +1850 µcr', tone: 'ok' },
  { t: 'line', text: '', tone: 'dim' },
  { t: 'cmd', text: '/btw less launch gossip, more eval methodology' },
  { t: 'wait', ms: 350 },
  { t: 'line', text: '↳ preference patch                  topic_weights[evals]+0.4', tone: 'dim' },
  { t: 'line', text: '↳ preference patch                  blocked_keywords[+]"gossip"', tone: 'dim' },
  { t: 'line', text: '✓ learned · applied to next refresh', tone: 'ok' },
];

const JSON_OUTPUT = [
  { key: '  "feed"', val: '"ai-agents-daily"' },
  { key: '  "items"', val: '[' },
  { key: '    {' },
  { key: '      "score"', val: '0.94,' },
  { key: '      "title"', val: '"Anthropic ships claude-haiku-4-5 with strict-tools",' },
  { key: '      "why"', val: '"runnable eval harness, concrete benchmarks"' },
  { key: '    },' },
  { key: '    {' },
  { key: '      "score"', val: '0.91,' },
  { key: '      "title"', val: '"Repligate publishes 12k-step agent trace",' },
  { key: '      "why"', val: '"reproducible, full tool log"' },
  { key: '    },' },
  { key: '  ],' },
  { key: '  "spent_micro_credits"', val: '6650,' },
  { key: '  "criteria_version"', val: '"sha:af3..91"' },
];

function CLIDemo() {
  const [step, setStep] = useState(0);
  const [typed, setTyped] = useState('');
  const [showJSON, setShowJSON] = useState(false);
  const [jsonLines, setJsonLines] = useState(0);
  const bodyRef = useRef(null);
  const [running, setRunning] = useState(true);

  useEffect(() => {
    if (!running) return;
    if (step >= SCRIPT.length) {
      // restart after pause
      const t = setTimeout(() => {
        setStep(0); setTyped(''); setShowJSON(false); setJsonLines(0);
      }, 4000);
      return () => clearTimeout(t);
    }
    const item = SCRIPT[step];
    if (item.t === 'cmd') {
      // type the command char-by-char
      let i = 0;
      const id = setInterval(() => {
        i++;
        setTyped(item.text.slice(0, i));
        if (i >= item.text.length) {
          clearInterval(id);
          setTimeout(() => setStep((s) => s + 1), 400);
        }
      }, 22);
      return () => clearInterval(id);
    } else if (item.t === 'wait') {
      const t = setTimeout(() => setStep((s) => s + 1), item.ms);
      return () => clearTimeout(t);
    } else if (item.t === 'json') {
      setShowJSON(true);
      // reveal json lines one by one
      let i = 0;
      const id = setInterval(() => {
        i++;
        setJsonLines(i);
        if (i >= JSON_OUTPUT.length) {
          clearInterval(id);
          setTimeout(() => setStep((s) => s + 1), 200);
        }
      }, 40);
      return () => clearInterval(id);
    } else {
      // line — just advance
      const t = setTimeout(() => setStep((s) => s + 1), 280);
      return () => clearTimeout(t);
    }
  }, [step, running]);

  // Build the running display
  const rendered = [];
  let typedHistory = []; // commands typed so far
  for (let i = 0; i < step; i++) {
    const item = SCRIPT[i];
    if (item.t === 'cmd') typedHistory.push(item.text);
    if (item.t === 'line') rendered.push(item);
    if (item.t === 'json' && showJSON) rendered.push({ t: 'json' });
  }

  // Render
  return (
    <div className="terminal" role="img" aria-label="MECE CLI demo">
      <div className="terminal-bar">
        <span className="terminal-dot r"></span>
        <span className="terminal-dot y"></span>
        <span className="terminal-dot g"></span>
        <span className="terminal-title">~/projects/feed — mece</span>
      </div>
      <div className="terminal-body" ref={bodyRef}>
        {/* prior commands & output */}
        {(() => {
          const blocks = [];
          let cmdIdx = 0;
          for (let i = 0; i < step; i++) {
            const item = SCRIPT[i];
            if (item.t === 'cmd') {
              blocks.push(
                <div key={`c${i}`} style={{ marginTop: i > 0 ? 14 : 0 }}>
                  <span className="t-prompt">❯</span> <span>{item.text}</span>
                </div>
              );
              cmdIdx++;
            } else if (item.t === 'line') {
              const cls = item.tone === 'ok' ? 't-ok'
                        : item.tone === 'warn' ? 't-warn'
                        : item.tone === 'trust' ? 't-trust'
                        : 't-dim';
              blocks.push(<div key={`l${i}`} className={cls}>{item.text || '\u00A0'}</div>);
            } else if (item.t === 'json') {
              blocks.push(
                <div key={`j${i}`} style={{ padding: '8px 0' }}>
                  <span className="t-dim">{'{'}</span>
                  {JSON_OUTPUT.slice(0, jsonLines).map((row, ri) => (
                    <div key={ri}>
                      <span className="t-key">{row.key}</span>
                      {row.val ? <span>: <span className={
                        row.val.startsWith('"') ? 't-str' : 't-num'
                      }>{row.val}</span></span> : null}
                    </div>
                  ))}
                  {jsonLines >= JSON_OUTPUT.length && <div><span className="t-dim">{'}'}</span></div>}
                </div>
              );
            }
          }
          return blocks;
        })()}

        {/* currently typing command */}
        {step < SCRIPT.length && SCRIPT[step].t === 'cmd' && (
          <div style={{ marginTop: 14 }}>
            <span className="t-prompt">❯</span> <span>{typed}</span>
            <span className="cursor"></span>
          </div>
        )}
        {/* idle cursor at end */}
        {step >= SCRIPT.length && (
          <div style={{ marginTop: 14 }}>
            <span className="t-prompt">❯</span> <span className="cursor"></span>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CLIDemo });
