// Artboard 6: Chat — sidebar of agents + chat window.

const { AGENTS: AA6, MINISTRIES: MM6 } = window.DHAM;

const INIT_MSGS = [
  { from: 'vijjadhara', text: 'Good evening, Brahma. I have reviewed the mesh v2 spec and flagged three concerns.', ts: '23:02' },
  { from: 'me',         text: 'Go ahead.', ts: '23:03' },
  { from: 'vijjadhara', text: 'First: node-discovery currently relies on mDNS — will not survive the VPN bridge to nakhara-ready. Second: we have no explicit quorum rule for writes during a partition. Third: the 5-minute heartbeat is too coarse for our failure-detector target of <30s.', ts: '23:03' },
  { from: 'me',         text: 'Draft a proposal to address #1 and #3. Loop Arakkhaka in on #2.', ts: '23:05' },
  { from: 'vijjadhara', text: 'Acknowledged. Draft will be in your inbox by 23:30.', ts: '23:05' },
  { from: 'vijjadhara', text: 'One more thing — Angkura is ready to land the kanban drag-drop work once you approve PR #88.', ts: '23:06' },
];

function Artboard_Chat() {
  const [sel, setSel] = React.useState('vijjadhara');
  const [msgs, setMsgs] = React.useState(INIT_MSGS);
  const [typing, setTyping] = React.useState(false);
  const [input, setInput] = React.useState('');
  const endRef = React.useRef(null);

  const agent = AA6.find((a) => a.id === sel);
  const m = MM6[agent.ministry];

  React.useEffect(() => {
    endRef.current?.scrollTo?.(0, endRef.current.scrollHeight);
  }, [msgs, typing]);

  const send = () => {
    if (!input.trim()) return;
    const text = input;
    setMsgs((ms) => [...ms, { from: 'me', text, ts: new Date().toTimeString().slice(0, 5) }]);
    setInput('');
    setTyping(true);
    const replies = [
      'Understood. Proceeding.',
      'I will consult Citta and report back within the hour.',
      'Acknowledged, Brahma. This aligns with the Q2 priorities.',
      'One moment — I will coordinate with the relevant ministry.',
    ];
    setTimeout(() => {
      setTyping(false);
      setMsgs((ms) => [...ms, { from: agent.id, text: replies[Math.floor(Math.random() * replies.length)], ts: new Date().toTimeString().slice(0, 5) }]);
    }, 1400);
  };

  const sidebarAgents = AA6.filter((a) => a.status !== 'offline').slice(0, 12);

  return (
    <AppChrome activePage="chat" padded={false}>
      <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
        {/* Sidebar */}
        <div style={{ width: 260, borderRight: '1px solid var(--line)', background: 'var(--surface-lo)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Conversations</div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--mono)', letterSpacing: 1, marginTop: 2 }}>12 ACTIVE · 3 UNREAD</div>
          </div>
          <div style={{ flex: 1, overflow: 'auto' }}>
            {sidebarAgents.map((a, i) => (
              <div key={a.id} onClick={() => setSel(a.id)} style={{
                padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
                background: a.id === sel ? 'var(--surface)' : 'transparent',
                borderLeft: a.id === sel ? `2px solid var(--gold)` : '2px solid transparent',
                borderBottom: '1px solid var(--line)',
              }}>
                <Avatar agent={a} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div style={{ fontSize: 12, fontWeight: 600 }}>{a.pali}</div>
                    <div style={{ fontSize: 9, color: 'var(--text-faint)', fontFamily: 'var(--mono)' }}>{20 + i}:0{i % 10}</div>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {i === 0 ? 'One more thing — Angkura is ready...' : i === 2 ? 'Building invoices now · 42/80' : 'Standing by for instructions.'}
                  </div>
                </div>
                {i === 1 && <div style={{ width: 16, height: 16, borderRadius: 8, background: 'var(--gold)', color: 'var(--base)', fontSize: 9, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>2</div>}
              </div>
            ))}
          </div>
        </div>

        {/* Main chat */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: 'var(--base)' }}>
          {/* Header */}
          <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-lo)' }}>
            <Avatar agent={agent} size={40} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 15, fontWeight: 600 }}>{agent.pali}</span>
                <span style={{ fontSize: 13, color: 'var(--gold)', fontFamily: 'var(--thai)' }}>{agent.thai}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--text-dim)' }}>
                <MinistryTag id={agent.ministry} />
                <span>{agent.role}</span>
                <span>·</span>
                <DharmaStars level={agent.trust} size={7} />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, fontSize: 10, fontFamily: 'var(--mono)' }}>
              <button style={{ padding: '5px 10px', background: 'transparent', border: '1px solid var(--line)', color: 'var(--text-dim)', borderRadius: 2, cursor: 'pointer', fontFamily: 'inherit' }}>PROFILE</button>
              <button style={{ padding: '5px 10px', background: 'transparent', border: '1px solid var(--line)', color: 'var(--text-dim)', borderRadius: 2, cursor: 'pointer', fontFamily: 'inherit' }}>TASKS</button>
            </div>
          </div>

          {/* Messages */}
          <div ref={endRef} style={{ flex: 1, overflow: 'auto', padding: '20px 32px' }}>
            <div style={{ textAlign: 'center', fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--text-faint)', letterSpacing: 2, marginBottom: 16 }}>
              ─── TODAY · WED 21 APR ───
            </div>
            {msgs.map((msg, i) => {
              const mine = msg.from === 'me';
              const fromAgent = AA6.find((a) => a.id === msg.from);
              return (
                <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 12, justifyContent: mine ? 'flex-end' : 'flex-start' }}>
                  {!mine && fromAgent && <Avatar agent={fromAgent} size={28} showStatus={false} />}
                  <div style={{ maxWidth: '70%' }}>
                    <div style={{
                      padding: '8px 12px', borderRadius: 3,
                      background: mine ? m.color : 'var(--surface)',
                      color: mine ? '#111' : 'var(--text)',
                      border: mine ? 'none' : '1px solid var(--line)',
                      fontSize: 13, lineHeight: 1.45,
                    }}>{msg.text}</div>
                    <div style={{ fontSize: 9, color: 'var(--text-faint)', fontFamily: 'var(--mono)', marginTop: 3, textAlign: mine ? 'right' : 'left' }}>{msg.ts}</div>
                  </div>
                </div>
              );
            })}
            {typing && (
              <div style={{ display: 'flex', gap: 10, marginBottom: 12, alignItems: 'center' }}>
                <Avatar agent={agent} size={28} showStatus={false} />
                <div style={{ padding: '10px 14px', borderRadius: 3, background: 'var(--surface)', border: '1px solid var(--line)', display: 'flex', gap: 4 }}>
                  {[0, 1, 2].map((i) => (
                    <div key={i} style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--text-dim)', animation: `dham-bounce 1.4s infinite ${i * 0.2}s` }} />
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Composer */}
          <div style={{ padding: 16, borderTop: '1px solid var(--line)', background: 'var(--surface-lo)', display: 'flex', gap: 8, alignItems: 'flex-end' }}>
            <div style={{ display: 'flex', gap: 4, paddingBottom: 8 }}>
              {['/task', '/deploy', '/ask'].map((c) => (
                <button key={c} style={{ padding: '4px 8px', fontSize: 10, fontFamily: 'var(--mono)', background: 'transparent', border: '1px solid var(--line)', color: 'var(--text-dim)', borderRadius: 2, cursor: 'pointer' }}>{c}</button>
              ))}
            </div>
            <textarea value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder={`Message ${agent.pali}... (⌘+↵ to send)`}
              style={{ flex: 1, minHeight: 38, maxHeight: 100, background: 'var(--base)', border: '1px solid var(--line)', padding: '10px 12px', color: 'var(--text)', fontSize: 12, borderRadius: 2, fontFamily: 'inherit', resize: 'none' }} />
            <button onClick={send} style={{ padding: '10px 16px', background: 'var(--gold)', color: 'var(--base)', border: 'none', borderRadius: 2, fontWeight: 600, fontSize: 11, letterSpacing: 0.5, cursor: 'pointer', fontFamily: 'inherit' }}>SEND</button>
          </div>
        </div>
      </div>
    </AppChrome>
  );
}

window.Artboard_Chat = Artboard_Chat;
