// Artboard 2: Agent Live Monitor — grid of agent cards + live terminal on right.

const { AGENTS: AA2, MINISTRIES: MM2 } = window.DHAM;

function AgentCard({ agent, selected, onClick }) {
  const m = MM2[agent.ministry];
  const pct = agent.status === 'working' ? Math.round(25 + (agent.tokens / 10000) % 70) : agent.status === 'online' ? 100 : 0;
  return (
    <div onClick={onClick} style={{
      background: selected ? 'var(--surface-hi)' : 'var(--surface)',
      border: `1px solid ${selected ? 'var(--gold)' : 'var(--line)'}`,
      borderRadius: 3, padding: 12, cursor: 'pointer',
      transition: 'all .15s', position: 'relative', overflow: 'hidden',
    }}>
      {/* ministry color accent */}
      <div style={{ position: 'absolute', top: 0, left: 0, width: 3, height: '100%', background: m.color }} />
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 10 }}>
        <Avatar agent={agent} size={32} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.1 }}>{agent.pali}</div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--thai)', marginTop: 2 }}>{agent.thai}</div>
        </div>
        <StatusPill status={agent.status} />
      </div>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--mono)', marginBottom: 4, letterSpacing: 0.5 }}>TASK</div>
      <div style={{ fontSize: 11, color: 'var(--text)', minHeight: 28, lineHeight: 1.3, marginBottom: 10 }}>{agent.task}</div>
      {/* progress */}
      <div style={{ height: 2, background: 'var(--surface-lo)', borderRadius: 1, overflow: 'hidden', marginBottom: 8 }}>
        <div style={{ height: '100%', width: `${pct}%`, background: agent.status === 'working' ? 'var(--working)' : 'var(--online)', transition: 'width .3s' }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--text-dim)' }}>
        <span>{agent.model}</span>
        <span>${agent.cost.toFixed(2)}</span>
        <span>{(agent.tokens / 1000).toFixed(1)}k tok</span>
      </div>
    </div>
  );
}

function LiveTerminal({ agent }) {
  const [lines, setLines] = React.useState([]);
  React.useEffect(() => {
    setLines([]);
    const samples = [
      `[info]  initializing context for ${agent.pali}`,
      `[task]  ${agent.task}`,
      `[tool]  read_file('src/queue.ts')`,
      `[tool]  -> 412 lines`,
      `[tool]  grep('TaskRunner', 'src/')`,
      `[tool]  -> 8 matches in 3 files`,
      `[llm]   planning response · ${agent.model}`,
      `[llm]   tokens in=1840 out=620`,
      `[tool]  write_file('src/queue.ts')`,
      `[ok]    written 430 lines · +18 -0`,
      `[test]  running unit tests...`,
      `[test]  ✓ 14 passed  ✗ 0 failed  ~ 1 skipped`,
      `[git]   commit 'refactor: cleaner TaskRunner'`,
      `[cost]  $0.03 this step · $${agent.cost.toFixed(2)} total`,
    ];
    let i = 0;
    const iv = setInterval(() => {
      if (i >= samples.length) { clearInterval(iv); return; }
      setLines((ls) => [...ls, { t: samples[i], ts: new Date(Date.now() - (samples.length - i) * 800) }]);
      i++;
    }, 380);
    return () => clearInterval(iv);
  }, [agent.id]);

  const color = (line) => {
    const l = typeof line === 'string' ? line : line.t;
    if (l.startsWith('[ok]'))   return 'var(--online)';
    if (l.startsWith('[info]')) return 'var(--info)';
    if (l.startsWith('[task]')) return 'var(--gold)';
    if (l.startsWith('[tool]')) return 'var(--text-dim)';
    if (l.startsWith('[llm]'))  return '#A78BFA';
    if (l.startsWith('[test]')) return 'var(--amber)';
    if (l.startsWith('[git]'))  return '#34D399';
    if (l.startsWith('[cost]')) return 'var(--gold-soft)';
    return 'var(--text)';
  };
  return (
    <div style={{ background: 'var(--surface-lo)', border: '1px solid var(--line)', borderRadius: 3, display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <Avatar agent={agent} size={28} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, fontWeight: 600 }}>{agent.pali}</div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>live output · tail -f</div>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--danger)' }} />
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--working)' }} />
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--online)' }} />
        </div>
      </div>
      <div style={{ flex: 1, padding: 12, fontFamily: 'var(--mono)', fontSize: 10.5, lineHeight: 1.65, overflow: 'auto' }}>
        {lines.map((l, i) => (
          <div key={i} style={{ color: color(l.t), opacity: 0, animation: 'dham-fade 0.3s forwards' }}>
            <span style={{ color: 'var(--text-faint)' }}>{l.ts.toTimeString().slice(0, 8)} </span>
            {l.t}
          </div>
        ))}
        <div style={{ width: 8, height: 12, background: 'var(--gold)', display: 'inline-block', animation: 'dham-blink 1s step-end infinite' }} />
      </div>
    </div>
  );
}

function Artboard_Monitor() {
  const [selected, setSelected] = React.useState('vijjadhara');
  const [filter, setFilter] = React.useState('all');
  const sel = AA2.find((a) => a.id === selected);
  const filtered = AA2.filter((a) => filter === 'all' || a.status === filter);

  return (
    <AppChrome activePage="monitor" title="Live Monitor" subtitle="REAL-TIME · 35 BHIKKHUS">
      <div style={{ display: 'flex', gap: 16, flex: 1, overflow: 'hidden' }}>
        {/* left: filters + grid */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 12, fontSize: 11, fontFamily: 'var(--mono)' }}>
            {[
              ['all', `All (${AA2.length})`],
              ['working', `Working (${AA2.filter((a) => a.status === 'working').length})`],
              ['online', `Online (${AA2.filter((a) => a.status === 'online').length})`],
              ['offline', `Offline (${AA2.filter((a) => a.status === 'offline').length})`],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setFilter(k)} style={{
                padding: '5px 10px', borderRadius: 3, cursor: 'pointer',
                background: filter === k ? 'var(--gold)' : 'transparent',
                color: filter === k ? 'var(--base)' : 'var(--text-dim)',
                border: `1px solid ${filter === k ? 'var(--gold)' : 'var(--line)'}`,
                fontFamily: 'inherit', fontSize: 10, letterSpacing: 0.5, textTransform: 'uppercase', fontWeight: 600,
              }}>{l}</button>
            ))}
            <div style={{ flex: 1 }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--text-dim)', fontSize: 10 }}>
              <span>MODEL:</span>
              <span style={{ color: 'var(--text)' }}>ALL</span>
              <span>·</span>
              <span>MINISTRY:</span>
              <span style={{ color: 'var(--text)' }}>ALL</span>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, overflow: 'auto', paddingRight: 4, alignContent: 'start' }}>
            {filtered.map((a) => (
              <AgentCard key={a.id} agent={a} selected={selected === a.id} onClick={() => setSelected(a.id)} />
            ))}
          </div>
        </div>
        {/* right: terminal */}
        <div style={{ width: 380, flexShrink: 0 }}>
          <LiveTerminal agent={sel} />
        </div>
      </div>
    </AppChrome>
  );
}

window.Artboard_Monitor = Artboard_Monitor;
