/* ============================================================
   ZERO — AI Command Center. window.Screens.Command
   ============================================================ */
(function () {
  const { useState, useEffect, useRef } = React;
  const I = window.Icon;
  const { StatusBadge, Badge, Typing } = window.UI;
  const D = window.DATA;

  function AgentCard({ a, selected, onClick }) {
    return (
      <button onClick={onClick} className="row gap10" style={{ width: '100%', textAlign: 'left', padding: '11px 12px', borderRadius: 12, cursor: 'pointer',
        border: '1px solid ' + (selected ? 'var(--line-strong)' : 'var(--line)'),
        background: selected ? 'linear-gradient(100deg, color-mix(in oklab,'+a.hue+', transparent 88%), transparent)' : 'var(--bg-1)',
        transition: 'all .15s ease', position: 'relative' }}>
        {selected && <span style={{ position: 'absolute', left: 0, top: 12, bottom: 12, width: 3, borderRadius: 4, background: a.hue }} />}
        <div style={{ position: 'relative', flex: 'none' }}>
          <span className="avatar" style={{ width: 34, height: 34, background: a.hue }}>{a.name[0]}</span>
          <span className="dot" style={{ position: 'absolute', bottom: -1, right: -1, width: 10, height: 10, border: '2px solid var(--bg-0)',
            background: window.UI.statusColor(a.status) }} />
        </div>
        <div className="grow" style={{ minWidth: 0 }}>
          <div className="row between"><span style={{ fontWeight: 700, fontSize: 13 }}>{a.name}</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--tx-3)' }}>{a.runs.toLocaleString('pt-BR')} exec.</span></div>
          <div style={{ fontSize: 11, color: 'var(--tx-2)' }}>{a.role}</div>
        </div>
      </button>
    );
  }

  function ChatMsg({ m, show }) {
    if (m.from === 'founder') {
      return (
        <div className="fadein" style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 18 }}>
          <div style={{ maxWidth: '76%' }}>
            <div className="row gap6" style={{ justifyContent: 'flex-end', marginBottom: 5 }}>
              <span className="mono" style={{ fontSize: 10.5, color: 'var(--tx-3)' }}>{m.time}</span>
              <span style={{ fontSize: 12, fontWeight: 700 }}>{m.name}</span>
            </div>
            <div style={{ padding: '11px 15px', borderRadius: '14px 14px 4px 14px', fontSize: 13.5, lineHeight: 1.55,
              background: 'linear-gradient(180deg, var(--violet-2), var(--violet))', color: 'white', boxShadow: '0 6px 20px oklch(0.64 0.17 288 /.3)' }}>
              {m.text}
            </div>
          </div>
        </div>
      );
    }
    return (
      <div className="fadein row gap10" style={{ marginBottom: 18, alignItems: 'flex-start' }}>
        <span className="avatar" style={{ width: 32, height: 32, background: m.hue, flex: 'none' }}>{m.name[0]}</span>
        <div style={{ maxWidth: '80%' }}>
          <div className="row gap8" style={{ marginBottom: 5 }}>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: m.hue }}>{m.name}</span>
            <span style={{ fontSize: 10.5, color: 'var(--tx-3)' }}>{m.role}</span>
            <span className="mono" style={{ fontSize: 10.5, color: 'var(--tx-3)' }}>{m.time}</span>
          </div>
          <div style={{ padding: '11px 15px', borderRadius: '4px 14px 14px 14px', fontSize: 13.5, lineHeight: 1.55,
            background: 'var(--bg-2)', border: '1px solid var(--line)', color: 'var(--tx-0)' }}>
            {m.text}
            {m.thinking && <div className="row gap8" style={{ marginTop: 8, color: 'var(--tx-3)', fontSize: 11.5 }}><Typing color={m.hue} /> monitorando a conversão em tempo real…</div>}
          </div>
        </div>
      </div>
    );
  }

  function Command() {
    const [selected, setSelected] = useState('atlas');
    const [count, setCount] = useState(0);          // how many messages revealed
    const [typing, setTyping] = useState(false);
    const [draft, setDraft] = useState('');
    const scrollRef = useRef(null);
    const msgs = D.chat;

    // progressive reveal
    useEffect(() => {
      if (count >= msgs.length) return;
      setTyping(count > 0);
      const t = setTimeout(() => { setTyping(false); setCount(c => c + 1); }, count === 0 ? 400 : 1300);
      return () => clearTimeout(t);
    }, [count]);

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

    const visible = msgs.slice(0, count);
    const selAgent = D.agents.find(a => a.id === selected) || D.agents[0];

    function send() {
      if (!draft.trim()) return;
      setDraft('');
      // re-run the cinematic sequence as if a new directive was issued
      setCount(0);
    }

    return (
      <div style={{ height: '100%', display: 'grid', gridTemplateColumns: '264px 1fr 296px', gap: 0 }}>
        {/* LEFT — agents */}
        <div style={{ borderRight: '1px solid var(--line)', padding: 16, overflowY: 'auto', background: 'oklch(0.16 0.013 265 /.4)' }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Equipe · 6 agentes</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {D.agents.map(a => <AgentCard key={a.id} a={a} selected={selected === a.id} onClick={() => setSelected(a.id)} />)}
          </div>
          <div className="hr" style={{ margin: '16px 0' }} />
          <div className="panel-flat" style={{ padding: 14 }}>
            <div className="row gap8" style={{ marginBottom: 10 }}>
              <span className="avatar" style={{ width: 28, height: 28, background: selAgent.hue }}>{selAgent.name[0]}</span>
              <div><div style={{ fontWeight: 700, fontSize: 13 }}>{selAgent.name}</div><div style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>{selAgent.role}</div></div>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--tx-2)', lineHeight: 1.5, marginBottom: 10 }}>{selAgent.task}</div>
            <StatusBadge status={selAgent.status} />
            <div className="row gap8" style={{ marginTop: 12 }}>
              <button className="btn btn-sm" style={{ flex: 1, justifyContent: 'center' }}><I.pause w={13} /> Pausar</button>
              <button className="btn btn-sm" style={{ flex: 1, justifyContent: 'center' }}><I.eye w={13} /> Inspecionar</button>
            </div>
          </div>
        </div>

        {/* CENTER — chat */}
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, height: '100%' }}>
          <div className="row between" style={{ padding: '14px 22px', borderBottom: '1px solid var(--line)', flex: 'none' }}>
            <div className="row gap10">
              <span style={{ display: 'grid', placeItems: 'center', width: 34, height: 34, borderRadius: 9, background: 'var(--violet-soft)', color: 'var(--violet-2)' }}><I.cpu w={18} /></span>
              <div><div style={{ fontWeight: 700, fontSize: 14 }}>Canal Operacional</div>
                <div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>Todos os agentes · modo autônomo</div></div>
            </div>
            <div className="row gap8">
              <Badge soft="var(--green-soft)" color="var(--green)" dot>Ao vivo</Badge>
              <button className="btn btn-icon btn-sm"><I.dots w={16} /></button>
            </div>
          </div>

          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '22px 26px' }}>
            <div className="row center" style={{ marginBottom: 20 }}>
              <span className="badge mono" style={{ color: 'var(--tx-3)', background: 'var(--bg-1)' }}>Hoje · 14:01</span>
            </div>
            {visible.map((m, i) => <ChatMsg key={i} m={m} />)}
            {typing && count < msgs.length && (
              <div className="row gap10" style={{ marginBottom: 18 }}>
                <span className="avatar" style={{ width: 32, height: 32, background: msgs[count].hue || 'var(--violet)' }}>{(msgs[count].name||'A')[0]}</span>
                <div style={{ padding: '13px 16px', borderRadius: 14, background: 'var(--bg-2)', border: '1px solid var(--line)' }}><Typing color={msgs[count].hue} /></div>
              </div>
            )}
          </div>

          {/* composer */}
          <div style={{ padding: '14px 22px 18px', borderTop: '1px solid var(--line)', flex: 'none' }}>
            <div className="row gap10" style={{ padding: '8px 8px 8px 16px', borderRadius: 14, border: '1px solid var(--line-strong)', background: 'var(--bg-1)' }}>
              <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
                placeholder="Dê uma diretriz à sua equipe…"
                style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: 'var(--tx-0)', fontSize: 13.5 }} />
              <button className="btn btn-sm" style={{ padding: '7px 10px' }}><I.sparkle w={14} /></button>
              <button onClick={send} className="btn btn-primary" style={{ padding: '8px 12px' }}><I.send w={15} /></button>
            </div>
            <div className="row gap8 wrap" style={{ marginTop: 10 }}>
              {['Analisar a semana', 'Lançar uma campanha', 'Corrigir o bug principal', 'Rascunhar update p/ investidores'].map(s => (
                <button key={s} onClick={() => { setDraft(s); }} className="badge" style={{ cursor: 'pointer', color: 'var(--tx-1)', background: 'var(--bg-1)', borderColor: 'var(--line)' }}>
                  <I.sparkle w={11} /> {s}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* RIGHT — context */}
        <div style={{ borderLeft: '1px solid var(--line)', padding: 18, overflowY: 'auto', background: 'oklch(0.16 0.013 265 /.4)' }}>
          <ContextPanel />
        </div>
      </div>
    );
  }

  function ContextPanel() {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Tarefas Atuais</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {D.ctxTasks.map((t, i) => (
              <div key={i}>
                <div className="row gap8" style={{ marginBottom: 6 }}>
                  <span style={{ color: t.done ? 'var(--green)' : t.hue, flex: 'none' }}>{t.done ? <I.checkCircle w={15} /> : <I.bolt w={14} />}</span>
                  <span className="grow" style={{ fontSize: 12.5, fontWeight: 600, textDecoration: t.done ? 'line-through' : 'none', color: t.done ? 'var(--tx-3)' : 'var(--tx-0)' }}>{t.text}</span>
                </div>
                {!t.done && <div className="row gap8" style={{ paddingLeft: 23 }}>
                  <div className="track grow"><i style={{ width: t.prog + '%', background: t.hue }} /></div>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--tx-3)' }}>{t.prog}%</span>
                </div>}
              </div>
            ))}
          </div>
        </div>

        <div className="hr" />

        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Prioridades</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {D.priorities.map((p, i) => (
              <div key={i} className="row gap10" style={{ padding: '10px 12px', borderRadius: 10, background: 'var(--bg-1)', border: '1px solid var(--line)' }}>
                <span style={{ width: 8, height: 8, borderRadius: 3, background: p.color, flex: 'none' }} />
                <span className="grow" style={{ fontSize: 12.5, fontWeight: 600 }}>{p.text}</span>
                <span className="badge" style={{ fontSize: 10, color: p.color, borderColor: 'transparent', background: `color-mix(in oklab, ${p.color}, transparent 86%)` }}>{p.level}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="hr" />

        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Próximos Passos</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {['Confirmar rollout do checkout-v2 para 100%', 'Aprovar orçamento de R$ 2,4 mil em retargeting', 'Revisar relatório semanal do board às 18h'].map((s, i) => (
              <div key={i} className="row gap8" style={{ fontSize: 12.5, color: 'var(--tx-1)' }}>
                <span style={{ color: 'var(--violet-2)', flex: 'none' }}><I.arrowRight w={14} /></span>{s}
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: 14, borderRadius: 12, background: 'var(--amber-soft)', border: '1px solid color-mix(in oklab, var(--amber), transparent 70%)' }}>
          <div className="row gap8" style={{ marginBottom: 6 }}>
            <span style={{ color: 'var(--amber)' }}><I.shield w={15} /></span>
            <span style={{ fontWeight: 700, fontSize: 12.5, color: 'var(--amber)' }}>Risco Operacional · Baixo</span>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--tx-1)', lineHeight: 1.5 }}>1 deploy em andamento. Conversão em 91% da linha de base e se recuperando. Nenhuma ação necessária.</div>
        </div>
      </div>
    );
  }

  window.Screens = window.Screens || {};
  window.Screens.Command = Command;
})();
