// Terminal (TUI) view
(function() {
  const { useState, useEffect, useRef } = React;

  const SESSION = [
    { type: 'prompt', user: 'adrien@bankx', path: '~', cmd: 'bx status' },
    { type: 'out', text: [
      '  bankx.dev CLI  2.1.0',
      '  session: sess_9f3a · workspace: darkmatter-labs',
      '',
      '  ●  connected  · 11 sources    ·  last sync 2s',
      '  ●  cash       · $284,013.42   ·  +2.1% 30d',
      '  ●  runway     · 18.4 months   ·  @ $94k burn',
      '  ⚠  uncat.     · 7 transactions      (run `bx tag --auto`)',
    ]},
    { type: 'prompt', user: 'adrien@bankx', path: '~', cmd: 'bx txn ls --since 24h --cat uncategorized' },
    { type: 'out', text: [
      'ID      TIME        MERCHANT                AMOUNT      ACCOUNT      CONF',
      '──────  ──────────  ──────────────────────  ──────────  ───────────  ────',
      't011    04/19 12:58 OUTBOUND WIRE 18392     −$4,200.00  ••0142        62%',
      't017    04/18 17:00 IRS USATAXPYMT         −$18,400.00  ••0923       100%',
      't029    04/16 20:00 SHINSEI SF                −$62.10  ••1007        88%',
      '',
      '3 of 7 shown · --all to view · --explain <id> for reasoning',
    ]},
    { type: 'prompt', user: 'adrien@bankx', path: '~', cmd: 'bx tag t011 --explain' },
    { type: 'out', text: [
      '▸ Analyzing transaction t011',
      '  merchant     OUTBOUND WIRE 18392',
      '  amount       −$4,200.00',
      '  memo         "AO · April retainer"',
      '',
      '  similar txns found in ledger:',
      '    2026-03-19  OUTBOUND WIRE 17201  −$4,200.00  → contract  (A. Obinna)',
      '    2026-02-19  OUTBOUND WIRE 16104  −$4,200.00  → contract  (A. Obinna)',
      '',
      '  suggestion:  category = contract · counterparty = A. Obinna',
      '  confidence:  96%',
      '  rule draft:  `memo ~= /AO/ && amount == -4200 → contract + AO`',
      '',
      '  apply? [y/N/edit]  › y',
      '  ✓ tagged  · rule r8 created  · 3 historical txns backfilled',
    ]},
    { type: 'prompt', user: 'adrien@bankx', path: '~', cmd: 'bx transfer --from ops --to tax --amount 30%.revenue.april' },
    { type: 'out', text: [
      '◇ dry-run',
      '  source       acc_main (Operating · ••0142)',
      '  destination  acc_tax  (Tax Reserve · ••0923)',
      '  amount       $72,564.00  (30% of $241,880 Apr revenue)',
      '  rails        bankx treasury · internal · free · instant',
      '',
      '  after:  ops  $211,449.42   tax  $137,384.00',
      '',
      '  confirm? [y/N]  › y',
      '  ✓ transfer pi_3NxK...9d  · settled · 127ms',
    ]},
    { type: 'prompt', user: 'adrien@bankx', path: '~', cmd: '' },
  ];

  function Terminal() {
    const [lines, setLines] = useState([]);
    const [cursorOn, setCursorOn] = useState(true);
    const scrollRef = useRef();

    useEffect(() => {
      let i = 0, t;
      function step() {
        if (i < SESSION.length) {
          // Capture by value — functional updaters run at render time, by which
          // point i has been incremented below, so reading SESSION[i] inside the
          // updater would push the wrong entry (and undefined on the final step).
          const entry = SESSION[i];
          setLines(s => [...s, entry]);
          i++;
          t = setTimeout(step, entry.type === 'prompt' ? 800 : 1400);
        }
      }
      t = setTimeout(step, 300);
      return () => clearTimeout(t);
    }, []);

    useEffect(() => {
      const id = setInterval(() => setCursorOn(c => !c), 600);
      return () => clearInterval(id);
    }, []);

    useEffect(() => {
      if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }, [lines]);

    return (
      <div className="page" style={{ padding: 20 }}>
        <div className="page-head">
          <div>
            <div className="crumb">developer<span className="sep">›</span>terminal<span className="sep">›</span>live session</div>
            <h1 className="display">Terminal <span style={{ color: 'var(--fg-3)', fontStyle: 'italic', fontSize: 22 }}>· bx 2.1.0</span></h1>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 6, letterSpacing: '0.1em' }}>
              $ curl bankx.dev/install.sh | sh   ·   mcp server at bx://mcp/stdio   ·   tui via `bx ui`
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn">Download binary</button>
            <button className="btn">Docs</button>
            <button className="btn primary">Mint API key</button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 'var(--gap)' }}>
          <div style={{
            background: '#050507', border: '1px solid var(--line-2)',
            height: 540, display: 'flex', flexDirection: 'column',
            fontFamily: 'var(--font-mono)', fontSize: 12.5,
          }}>
            <div style={{ padding: '6px 12px', borderBottom: '1px solid var(--line-2)', display: 'flex', alignItems: 'center', gap: 8, background: 'var(--bg-1)' }}>
              <span style={{ width: 10, height: 10, background: 'var(--neg)', display: 'inline-block' }} />
              <span style={{ width: 10, height: 10, background: 'var(--cat-amber)', display: 'inline-block' }} />
              <span style={{ width: 10, height: 10, background: 'var(--pos)', display: 'inline-block' }} />
              <span style={{ marginLeft: 12, color: 'var(--fg-2)', fontSize: 11 }}>bx — adrien@bankx — 124×38</span>
              <span style={{ marginLeft: 'auto', color: 'var(--fg-3)', fontSize: 10 }}>zsh · tmux(0:bx)</span>
            </div>
            <div ref={scrollRef} style={{ padding: '10px 14px', color: '#d8d3c4', flex: 1, overflowY: 'auto', lineHeight: 1.55 }}>
              {lines.map((l, i) => l.type === 'prompt' ? (
                <div key={i} style={{ marginTop: i ? 8 : 0 }}>
                  <span style={{ color: 'var(--cat-lime)' }}>{l.user}</span>
                  <span style={{ color: 'var(--fg-3)' }}>:</span>
                  <span style={{ color: 'var(--cat-cyan)' }}>{l.path}</span>
                  <span style={{ color: 'var(--fg-3)' }}> $ </span>
                  <span style={{ color: 'var(--accent)' }}>{l.cmd}</span>
                  {i === lines.length - 1 && <span style={{ color: 'var(--accent)', opacity: cursorOn ? 1 : 0 }}>█</span>}
                </div>
              ) : (
                <pre key={i} style={{ margin: 0, fontFamily: 'inherit', color: '#c3bdab', whiteSpace: 'pre-wrap' }}>
                  {l.text.join('\n')}
                </pre>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
            <div className="panel">
              <div className="panel-head"><span className="panel-title">MCP · Model Context Protocol</span><span className="chip live"><span className="dot pulse"/>online</span></div>
              <div style={{ padding: 'var(--pad-x)', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-1)', lineHeight: 1.85 }}>
                <div style={{ color: 'var(--fg-3)' }}>// claude, cursor, cody, etc.</div>
                <div><span style={{ color: 'var(--cat-violet)' }}>tools</span> exposed · 14</div>
                <div style={{ color: 'var(--fg-2)', paddingLeft: 8 }}>bx.txn.query · bx.txn.tag</div>
                <div style={{ color: 'var(--fg-2)', paddingLeft: 8 }}>bx.budget.diff · bx.rule.apply</div>
                <div style={{ color: 'var(--fg-2)', paddingLeft: 8 }}>bx.transfer · bx.reconcile · …</div>
                <div style={{ marginTop: 10 }}><span style={{ color: 'var(--cat-violet)' }}>resources</span> · 6 · ledger, journals, receipts</div>
                <div style={{ marginTop: 10 }}><span style={{ color: 'var(--cat-violet)' }}>prompts</span> · 4 · close-books, tax-prep…</div>
                <div style={{ marginTop: 12, padding: 8, background: 'var(--bx-0, var(--bg-0))', border: '1px solid var(--line)', color: 'var(--fg-1)' }}>
                  <div style={{ color: 'var(--fg-3)' }}>~/.cursor/mcp.json</div>
                  <div>{'{"bankx":'} {'{'}</div>
                  <div style={{ paddingLeft: 12 }}>"cmd": "bx mcp",</div>
                  <div style={{ paddingLeft: 12 }}>"env": {'{'}"BX_TOKEN":"$BX"{'}'}</div>
                  <div>{'}}'}</div>
                </div>
              </div>
            </div>
            <div className="panel">
              <div className="panel-head"><span className="panel-title">TUI · preview</span></div>
              <pre style={{ margin: 0, padding: 'var(--pad-x)', fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-1)', lineHeight: 1.45, whiteSpace: 'pre' }}>
{`┌─ bankx ───── help ? ─ quit q ─┐
│ [a] accounts    [r] rules      │
│ [t] txns        [x] tax        │
│ [b] budget      [/] search     │
├────────────────────────────────┤
│ OPS    $284,013.42  ▲ +$12,840 │
│ TAX     $64,820.00  ▲  +$2,140 │
│ PAY     $52,100.00  ▼ −$18,200 │
│                                │
│ ▣ 7 need review                │
│ ▣ 1 rule waiting confirm       │
└────────────────────────────────┘`}
              </pre>
            </div>
          </div>
        </div>
      </div>
    );
  }
  window.TerminalView = Terminal;
})();
