// V8 — Terminal
// tmux-style dense dashboard for power users. Split panes, blinking cursor,
// live log tail, vim status bar, animated sparklines. Pure dark, monospace.

const v8 = {
  bg: '#07090e',
  panel: '#0b0e15',
  panel2: '#111622',
  line: '#1a2030',
  line2: '#232a3e',
  ink: '#d4dcea',
  ink2: '#8391ad',
  ink3: '#5b6782',
  green: '#7cdc8f',
  cyan: '#6ee7f0',
  yellow: '#f4d160',
  orange: '#f99157',
  red: '#f87171',
  magenta: '#e08cd0',
  blue: '#7aa7ff',
  mono: '"JetBrains Mono", ui-monospace, monospace',
};

function V8Terminal() {
  return (
    <div style={{
      width: '100%', height: '100%', background: v8.bg, color: v8.ink,
      fontFamily: v8.mono, fontSize: 12, overflow: 'hidden',
      display: 'grid', gridTemplateRows: '24px 1fr 22px',
      letterSpacing: '0.01em',
    }}>
      <V8TmuxBar />
      <V8Grid />
      <V8ViBar />
      <style>{`
        @keyframes v8Blink { 50% { opacity: 0 } }
        @keyframes v8Tail { 0% { opacity: 0; transform: translateX(-4px) } 100% { opacity: 1; transform: translateX(0) } }
        @keyframes v8Scan { 0% { transform: translateY(-100%) } 100% { transform: translateY(400%) } }
        @keyframes v8BarShift { 0% { transform: translateX(0) } 100% { transform: translateX(-6px) } }
        @keyframes v8Dash { to { stroke-dashoffset: -80 } }
        @keyframes v8Pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.45 } }
        @keyframes v8Tick { 0% { transform: scaleX(0); transform-origin: left } 100% { transform: scaleX(1); transform-origin: left } }
      `}</style>
    </div>
  );
}

function V8TmuxBar() {
  const windows = [
    ['0', 'dashboard', true],
    ['1', 'money',     false],
    ['2', 'schedule',  false],
    ['3', 'logs:tail', false],
    ['4', 'ai',        false],
  ];
  return (
    <div style={{ display: 'flex', alignItems: 'center', background: '#030508', borderBottom: `1px solid ${v8.line}`, fontSize: 11, color: v8.ink3 }}>
      <div style={{ padding: '0 10px', background: v8.green, color: '#030508', fontWeight: 700, letterSpacing: '0.1em', display: 'grid', placeItems: 'center', height: '100%' }}>CONTRO</div>
      {windows.map(([i, n, on]) => (
        <div key={i} style={{
          padding: '0 10px', height: '100%', display: 'grid', placeItems: 'center',
          background: on ? v8.panel : 'transparent',
          color: on ? v8.green : v8.ink3,
          borderRight: `1px solid ${v8.line}`,
        }}>
          <span style={{ opacity: 0.6, marginRight: 6 }}>{i}:</span>{n}{on && <span style={{ color: v8.yellow, marginLeft: 4 }}>*</span>}
        </div>
      ))}
      <div style={{ flex: 1 }} />
      <div style={{ padding: '0 10px' }}>marcus@ridgeline-dev</div>
      <div style={{ padding: '0 10px', color: v8.green }}>● 41/44</div>
      <div style={{ padding: '0 10px', background: v8.line2 }}>tue 21 apr · 09:14</div>
    </div>
  );
}

function V8Grid() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1.3fr 1fr', gridTemplateRows: '1fr 1fr', gap: 1, background: v8.line }}>
      <V8Pane title="portfolio.sh" meta="live" span={{ row: 1 }}><V8Portfolio /></V8Pane>
      <V8Pane title="ops.log — tail -f" meta="streaming" span={{ row: 1 }}><V8LogTail /></V8Pane>
      <V8Pane title="kpi --watch" meta="1s">
        <V8KPI />
      </V8Pane>

      <V8Pane title="cashflow.py" meta="q2" span={{ row: 1 }}><V8Cashflow /></V8Pane>
      <V8Pane title="agents --status" meta="4 running" span={{ row: 1 }}><V8Agents /></V8Pane>
      <V8Pane title="contro > _" meta="repl">
        <V8Repl />
      </V8Pane>
    </div>
  );
}

function V8Pane({ title, meta, children, span }) {
  return (
    <div style={{
      background: v8.panel, display: 'flex', flexDirection: 'column',
      minHeight: 0, overflow: 'hidden', position: 'relative',
      gridRow: span?.row ? `span ${span.row}` : undefined,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 10px', background: '#05070b', borderBottom: `1px solid ${v8.line}`, fontSize: 10 }}>
        <span style={{ color: v8.green }}>▸</span>
        <span style={{ color: v8.ink }}>{title}</span>
        <span style={{ flex: 1 }} />
        <span style={{ color: v8.ink3 }}>[{meta}]</span>
      </div>
      <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>{children}</div>
    </div>
  );
}

// ─ Portfolio table with animated sparklines ──────────────
function V8Portfolio() {
  const rows = [
    ['HBV-02', 'Harborview Blk B',  0.62, '$1.24M', 'on',   v8.green],
    ['PRG-03', 'Pine Ridge L3',     0.48, '$884k',  'on',   v8.green],
    ['EBL-01', 'East Bay Lofts',    0.33, '$612k',  'over', v8.orange],
    ['MER-04', 'Meridian Tower',    0.81, '$2.1M',  'on',   v8.green],
    ['FOS-02', 'Foster & 9th',      0.14, '$188k',  'hold', v8.yellow],
    ['WHF-01', 'Warehouse Fit-out', 0.56, '$342k',  'on',   v8.green],
  ];
  return (
    <div style={{ padding: '8px 10px', fontSize: 11, height: '100%', overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '70px 1fr 80px 80px 50px', gap: 8, color: v8.ink3, borderBottom: `1px dashed ${v8.line2}`, paddingBottom: 4, marginBottom: 4 }}>
        <span>CODE</span><span>PROJECT</span><span>PROGRESS</span><span>BILLED</span><span>STATUS</span>
      </div>
      {rows.map((r, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 80px 80px 50px', gap: 8, padding: '5px 0', alignItems: 'center', borderBottom: `1px solid ${v8.line}` }}>
          <span style={{ color: v8.cyan }}>{r[0]}</span>
          <span>{r[1]}</span>
          <div style={{ position: 'relative', height: 8, background: v8.line2, borderRadius: 1 }}>
            <div style={{ position: 'absolute', inset: '0 auto 0 0', width: `${r[2] * 100}%`, background: r[5], animation: `v8Tick 900ms ${i * 80}ms cubic-bezier(.2,.8,.2,1) both` }} />
            <span style={{ position: 'absolute', right: 3, top: -1, fontSize: 9, color: v8.ink3 }}>{Math.round(r[2]*100)}</span>
          </div>
          <span style={{ color: v8.ink }}>{r[3]}</span>
          <span style={{ color: r[5] }}>[{r[4]}]</span>
        </div>
      ))}
      <div style={{ marginTop: 10, fontSize: 10, color: v8.ink3, display: 'flex', gap: 18 }}>
        <span>Σ billed  <span style={{ color: v8.ink }}>$5.37M</span></span>
        <span>avg %  <span style={{ color: v8.ink }}>49</span></span>
        <span>over  <span style={{ color: v8.orange }}>1</span></span>
      </div>
      {/* scan line */}
      <div style={{ position: 'absolute', left: 10, right: 10, height: 18, background: 'linear-gradient(180deg, transparent, rgba(124,220,143,0.08), transparent)', animation: 'v8Scan 6s linear infinite', pointerEvents: 'none' }} />
    </div>
  );
}

// ─ Log tail, lines appearing top-to-bottom ───────────────
function V8LogTail() {
  const [k, setK] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setK(v => (v + 1) % 40), 550); return () => clearInterval(t); }, []);
  const all = [
    ['09:14:02', 'INFO', v8.green,   'invoice.parse  ok  inv-1142.pdf  → PO-0338  $184,220'],
    ['09:13:58', 'WARN', v8.yellow,  'schedule.drift  HBV-02 · framing +1.2d'],
    ['09:13:51', 'INFO', v8.cyan,    'draw.signed     Calloway Co  #7  $842,000'],
    ['09:13:44', 'INFO', v8.green,   'rfi.close       RFI-041  (resolved by rev-C)'],
    ['09:13:32', 'ERR ', v8.red,     'safety.ppe      cam-3  no_vest  block-A  09:12:41'],
    ['09:13:18', 'INFO', v8.green,   'material.recv   rebar#4  ×24  WHF-01'],
    ['09:13:04', 'INFO', v8.magenta, 'agent.done      lien-waiver-bot  4/4 collected'],
    ['09:12:52', 'INFO', v8.cyan,    'ts.submit       mondragon-framing  14 crew'],
    ['09:12:38', 'WARN', v8.yellow,  'po.variance     PO-0338  +8.2%  rebar_price'],
    ['09:12:14', 'INFO', v8.green,   'weather.pull    6 sites  ·  2 rain alerts'],
    ['09:11:58', 'INFO', v8.green,   'sync.quickbooks  12 bills  2 invoices  ok'],
    ['09:11:42', 'INFO', v8.cyan,    'doc.revise       sheet A-102  rev-D  uploaded'],
  ];
  const visible = Math.min(all.length, Math.floor(k / 2) + 5);
  return (
    <div style={{ padding: '8px 10px', fontSize: 10.5, lineHeight: 1.7, height: '100%', overflow: 'hidden' }}>
      {all.slice(0, visible).map((l, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '72px 40px 1fr', gap: 6, animation: i === visible - 1 ? 'v8Tail 400ms ease-out both' : 'none' }}>
          <span style={{ color: v8.ink3 }}>{l[0]}</span>
          <span style={{ color: l[2] }}>{l[1]}</span>
          <span style={{ color: v8.ink }}>{l[3]}</span>
        </div>
      ))}
      <div style={{ marginTop: 6, color: v8.green }}>
        <span style={{ opacity: 0.6 }}>tail -f ops.log</span>
        <span style={{ display: 'inline-block', width: 7, height: 11, background: v8.green, marginLeft: 4, verticalAlign: 'middle', animation: 'v8Blink 1s steps(2) infinite' }} />
      </div>
    </div>
  );
}

// ─ KPI watch — tiny number rows with sparklines ──────────
function V8KPI() {
  const rows = [
    ['rev.ytd',   '5.27M',  '+8.1',  v8.green, [3,4,3,5,6,5,7,8]],
    ['margin',    '18.4%',  '+0.4',  v8.green, [3,4,4,5,5,6,6,7]],
    ['ar.open',   '1.84M',  '−2',    v8.yellow,[5,5,4,5,4,3,4,3]],
    ['ap.due7',   '312k',   '+41',   v8.orange,[2,3,4,5,6,7,8,9]],
    ['crew.on',   '41/44',  '-3',    v8.cyan,  [4,5,5,5,4,5,5,4]],
    ['safety.d',  '14d',    'ok',    v8.green, [1,1,1,1,2,2,3,4]],
    ['rfis.open', '7',      '2odue', v8.red,   [3,4,4,5,6,7,6,7]],
  ];
  return (
    <div style={{ padding: '8px 10px', fontSize: 10.5, lineHeight: 1.85 }}>
      {rows.map((r, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '72px 64px 40px 1fr', gap: 6, alignItems: 'center' }}>
          <span style={{ color: v8.cyan }}>{r[0]}</span>
          <span style={{ color: v8.ink }}>{r[1]}</span>
          <span style={{ color: r[3] }}>{r[2]}</span>
          <svg width="70" height="14" viewBox="0 0 70 14">
            <polyline fill="none" stroke={r[3]} strokeWidth="1"
              points={r[4].map((v,j) => `${j*10},${14 - v}`).join(' ')} />
          </svg>
        </div>
      ))}
    </div>
  );
}

// ─ Cashflow candle chart ─────────────────────────────────
function V8Cashflow() {
  const bars = [
    [2,5],[3,6],[1,4],[2,7],[4,9],[3,6],[5,10],[4,8],[6,11],[5,9],[7,12],[6,10],[8,13],[7,11],
  ];
  return (
    <div style={{ padding: '8px 10px', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', fontSize: 10, color: v8.ink3, gap: 14 }}>
        <span>cash.balance  <span style={{ color: v8.green }}>$2.14M</span></span>
        <span>14d min  <span style={{ color: v8.ink }}>$1.72M</span></span>
        <span>14d max  <span style={{ color: v8.ink }}>$2.31M</span></span>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', gap: 4, marginTop: 8, position: 'relative' }}>
        {bars.map((b, i) => {
          const max = 14; const low = b[0], high = b[1];
          const bottom = (low / max) * 100;
          const h = ((high - low) / max) * 100;
          return (
            <div key={i} style={{ flex: 1, position: 'relative', height: '100%' }}>
              <div style={{ position: 'absolute', bottom: `${bottom}%`, height: `${h}%`, left: '30%', right: '30%',
                background: i === bars.length - 1 ? v8.cyan : v8.green,
                animation: `v8Tick 800ms ${i * 50}ms cubic-bezier(.2,.8,.2,1) both`, transformOrigin: 'bottom' }} />
              <div style={{ position: 'absolute', bottom: `${bottom + h}%`, left: 0, right: 0, height: 1, background: i === bars.length - 1 ? v8.cyan : v8.green, opacity: 0.4 }} />
            </div>
          );
        })}
        {/* trendline */}
        <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }} viewBox="0 0 280 100" preserveAspectRatio="none">
          <path d="M 10 65 C 60 62, 100 50, 140 45 S 230 22, 270 18"
            fill="none" stroke={v8.yellow} strokeWidth="1" strokeDasharray="3 3"
            style={{ animation: 'v8Dash 4s linear infinite' }} />
        </svg>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: v8.ink3, marginTop: 4 }}>
        <span>apr 08</span><span>apr 14</span><span>today</span>
      </div>
    </div>
  );
}

// ─ Agents table ──────────────────────────────────────────
function V8Agents() {
  const rows = [
    ['invoice.parse',   'pid 3401', 'running', v8.cyan,    '12s', 'inv-1143.pdf · fields 6/9'],
    ['schedule.watch',  'pid 3402', 'alert',   v8.yellow,  '4m',  'HBV-02 drift +1.2d'],
    ['draw.prep',       'pid 3403', 'done',    v8.green,   '—',   'G703 attached to draw-7'],
    ['lien.collect',    'pid 3404', 'running', v8.cyan,    '2m',  '4 subs · chasing'],
    ['sub.match',       'pid 3405', 'idle',    v8.ink3,    '—',   'no new POs'],
  ];
  return (
    <div style={{ padding: '8px 10px', fontSize: 10.5, lineHeight: 1.7 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '140px 70px 60px 40px 1fr', gap: 6, color: v8.ink3, borderBottom: `1px dashed ${v8.line2}`, paddingBottom: 2, marginBottom: 2 }}>
        <span>NAME</span><span>PID</span><span>STATE</span><span>AGE</span><span>DETAIL</span>
      </div>
      {rows.map((r, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '140px 70px 60px 40px 1fr', gap: 6, padding: '3px 0' }}>
          <span style={{ color: v8.magenta }}>{r[0]}</span>
          <span style={{ color: v8.ink3 }}>{r[1]}</span>
          <span style={{ color: r[3], display: 'flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: r[3], animation: r[2] === 'running' ? 'v8Pulse 1s infinite' : 'none' }} />
            {r[2]}
          </span>
          <span style={{ color: v8.ink3 }}>{r[4]}</span>
          <span style={{ color: v8.ink }}>{r[5]}</span>
        </div>
      ))}
      <div style={{ marginTop: 6, color: v8.ink3, fontSize: 10 }}>
        4 running · 1 alert · 1 idle · queue 0
      </div>
    </div>
  );
}

// ─ Repl ──────────────────────────────────────────────────
function V8Repl() {
  const lines = [
    { c: v8.green,  t: '$ contro query "overbudget POs this week"' },
    { c: v8.ink3,   t: 'matching 238 records...' },
    { c: v8.ink,    t: '┌─ PO-0338  Brannigan Concrete   +8.2%  $15.2k' },
    { c: v8.ink,    t: '├─ PO-0402  Castile MEP          +3.1%  $4.4k' },
    { c: v8.ink,    t: '└─ PO-0417  Lowe Glazing         +2.7%  $1.1k' },
    { c: v8.green,  t: '$ contro draft co --sub brannigan' },
    { c: v8.cyan,   t: '✓ CO-017 drafted · $42,180 · attached' },
  ];
  return (
    <div style={{ padding: '8px 10px', fontSize: 10.5, lineHeight: 1.7 }}>
      {lines.map((l, i) => (
        <div key={i} style={{ color: l.c, animation: `v8Tail 400ms ${i * 200}ms both` }}>{l.t}</div>
      ))}
      <div style={{ color: v8.green, marginTop: 4 }}>
        $ <span style={{ display: 'inline-block', width: 7, height: 11, background: v8.green, marginLeft: 2, verticalAlign: 'middle', animation: 'v8Blink 1s steps(2) infinite' }} />
      </div>
    </div>
  );
}

function V8ViBar() {
  return (
    <div style={{ background: '#030508', display: 'flex', alignItems: 'center', fontSize: 11, color: v8.ink3 }}>
      <div style={{ padding: '0 10px', background: v8.green, color: '#030508', fontWeight: 700, letterSpacing: '0.1em', height: '100%', display: 'grid', placeItems: 'center' }}>NORMAL</div>
      <div style={{ padding: '0 10px', background: v8.line2, height: '100%', display: 'grid', placeItems: 'center' }}>contro/portfolio</div>
      <div style={{ padding: '0 10px', color: v8.ink }}> main </div>
      <div style={{ padding: '0 10px', color: v8.yellow }}>● 2 alerts</div>
      <div style={{ flex: 1 }} />
      <div style={{ padding: '0 10px' }}>unicode</div>
      <div style={{ padding: '0 10px' }}>utf-8</div>
      <div style={{ padding: '0 10px' }}>42:128</div>
      <div style={{ padding: '0 10px', background: v8.green, color: '#030508', fontWeight: 700, height: '100%', display: 'grid', placeItems: 'center' }}>72%</div>
    </div>
  );
}

Object.assign(window, { V8Terminal });
