/* ============================================================
   ZERO — Team Builder. window.Screens.Teambuilder
   ============================================================ */
(function () {
  const { useState, useEffect, useRef } = React;
  const I = window.Icon;
  const { Card, SectionHead, Toggle, Badge, Typing } = window.UI;
  const { AgentAvatar } = window.BUILD;
  const D = window.DATA;

  let uid = 0;
  const inst = (a) => ({ ...a, iid: 'i' + (++uid) });

  const TABS = [
    ['assemble', 'Montar', 'users'],
    ['org', 'Organograma', 'network'],
    ['workflow', 'Workflow', 'activity'],
    ['comms', 'Comunicação', 'cpu'],
  ];

  function Teambuilder() {
    const [team, setTeam] = useState({ name: 'Meu Time de IA', desc: 'A equipe que toca a empresa no autopilot.', mission: 'Crescer com eficiência, 24/7.' });
    const [roster, setRoster] = useState(() => ['lib-ceo', 'lib-mkt', 'lib-sales', 'lib-sup'].map(id => inst(D.agentLibrary.find(a => a.id === id))));
    const [tab, setTab] = useState('assemble');
    const [drag, setDrag] = useState(null);
    const [over, setOver] = useState(false);

    function addAgent(a) { setRoster(r => [...r, inst(a)]); }
    function removeAgent(iid) { setRoster(r => r.filter(x => x.iid !== iid)); }
    function dupAgent(iid) { setRoster(r => { const a = r.find(x => x.iid === iid); const i = r.indexOf(a); const c = [...r]; c.splice(i + 1, 0, inst(a)); return c; }); }

    function applyTemplate(t) {
      const map = { CEO: 'lib-ceo', Dev: 'lib-dev', Marketing: 'lib-mkt', Growth: 'lib-mkt', Vendas: 'lib-sales', Suporte: 'lib-sup', Ops: 'lib-ops', Finance: 'lib-fin', Produto: 'lib-ana', Conteúdo: 'lib-mkt', Analytics: 'lib-ana' };
      setRoster(t.roles.map(r => inst(D.agentLibrary.find(a => a.id === (map[r] || 'lib-ceo')))));
    }

    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        {/* header */}
        <div style={{ padding: '14px 26px', borderBottom: '1px solid var(--line)' }}>
          <div className="row between wrap gap16">
            <div className="row gap12" style={{ flex: 1, minWidth: 260 }}>
              <span style={{ display: 'grid', placeItems: 'center', width: 40, height: 40, borderRadius: 11, background: 'var(--violet-soft)', color: 'var(--violet-2)', flex: 'none' }}><I.network w={20} /></span>
              <div className="grow" style={{ minWidth: 0 }}>
                <input value={team.name} onChange={e => setTeam(t => ({ ...t, name: e.target.value }))}
                  style={{ background: 'transparent', border: 'none', outline: 'none', color: 'var(--tx-0)', fontSize: 17, fontWeight: 800, letterSpacing: '-0.02em', width: '100%' }} />
                <input value={team.desc} onChange={e => setTeam(t => ({ ...t, desc: e.target.value }))}
                  style={{ background: 'transparent', border: 'none', outline: 'none', color: 'var(--tx-2)', fontSize: 12, width: '100%' }} />
              </div>
            </div>
            <div className="row gap8">
              <Badge soft="var(--violet-soft)" color="var(--violet-2)">{roster.length} agentes</Badge>
              <button className="btn btn-primary btn-sm"><I.check w={14} /> Salvar equipe</button>
            </div>
          </div>
          {/* tabs */}
          <div className="row gap4" style={{ marginTop: 14, background: 'var(--bg-1)', padding: 3, borderRadius: 10, border: '1px solid var(--line)', width: 'fit-content' }}>
            {TABS.map(([id, label, icon]) => {
              const Ic = I[icon];
              return (
                <button key={id} onClick={() => setTab(id)} className="row gap6" style={{ padding: '7px 14px', borderRadius: 7, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', border: 'none',
                  background: tab === id ? 'var(--bg-3)' : 'transparent', color: tab === id ? 'var(--tx-0)' : 'var(--tx-2)' }}>
                  <Ic w={14} />{label}
                </button>
              );
            })}
          </div>
        </div>

        <div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
          {tab === 'assemble' && <Assemble {...{ roster, setRoster, drag, setDrag, over, setOver, addAgent, removeAgent, dupAgent, applyTemplate }} />}
          {tab === 'org' && <OrgChart roster={roster} />}
          {tab === 'workflow' && <Workflow />}
          {tab === 'comms' && <Comms />}
        </div>
      </div>
    );
  }

  /* -------- Assemble (drag & drop) -------- */
  function Assemble({ roster, setRoster, drag, setDrag, over, setOver, addAgent, removeAgent, dupAgent, applyTemplate }) {
    function onDropRoster() { if (drag && drag.from === 'lib') addAgent(drag.a); setDrag(null); setOver(false); }
    return (
      <div style={{ height: '100%', display: 'grid', gridTemplateColumns: '270px 1fr' }}>
        {/* library */}
        <div style={{ borderRight: '1px solid var(--line)', overflowY: 'auto', padding: 16, background: 'oklch(0.16 0.013 265 /.4)' }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Biblioteca de agentes</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {D.agentLibrary.map(a => (
              <div key={a.id} draggable onDragStart={() => setDrag({ from: 'lib', a })} onDragEnd={() => setDrag(null)}
                className="row gap10 lift" style={{ padding: 10, borderRadius: 11, background: 'var(--bg-1)', border: '1px solid var(--line)', cursor: 'grab' }}>
                <AgentAvatar icon={a.icon} color={a.hue} size={32} />
                <div className="grow" style={{ minWidth: 0 }}>
                  <div className="ellipsis" style={{ fontSize: 12.5, fontWeight: 700 }}>{a.name}</div>
                  <div className="ellipsis" style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>{a.role}</div>
                </div>
                <button onClick={() => addAgent(a)} className="btn btn-icon btn-sm" style={{ padding: 4, border: 'none', background: 'transparent', color: 'var(--tx-3)' }}><I.plus w={15} /></button>
              </div>
            ))}
          </div>
          <div className="hr" style={{ margin: '16px 0' }} />
          <div className="eyebrow" style={{ marginBottom: 10 }}>Começar de um template</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
            {D.teamTemplates.slice(0, 4).map(t => (
              <button key={t.name} onClick={() => applyTemplate(t)} className="row gap8" style={{ padding: '8px 10px', borderRadius: 9, cursor: 'pointer', textAlign: 'left',
                background: 'transparent', border: '1px solid var(--line)', color: 'var(--tx-1)' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <span style={{ width: 8, height: 8, borderRadius: 3, background: t.hue, flex: 'none' }} />
                <span className="grow ellipsis" style={{ fontSize: 12 }}>{t.name}</span>
                <I.arrowRight w={13} />
              </button>
            ))}
          </div>
        </div>

        {/* roster drop zone */}
        <div onDragOver={e => { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)} onDrop={onDropRoster}
          style={{ overflowY: 'auto', padding: 22, background: over ? 'var(--violet-soft)' : 'transparent', transition: 'background .15s ease' }}>
          <div className="row between" style={{ marginBottom: 16 }}>
            <div><div className="h3">Sua equipe</div><div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>Arraste agentes da biblioteca para montar</div></div>
            <Badge soft="oklch(1 0 0 /.05)" color="var(--tx-2)">{roster.length} membros</Badge>
          </div>
          {roster.length === 0 && (
            <div className="placeholder-img" style={{ height: 160, flexDirection: 'column', gap: 8 }}>
              <I.users w={26} /><span>Arraste agentes para cá</span>
            </div>
          )}
          <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(220px,1fr))', gap: 14 }}>
            {roster.map((a, i) => (
              <div key={a.iid} className="panel lift" style={{ padding: 16 }}>
                <div className="row between" style={{ marginBottom: 12 }}>
                  <AgentAvatar icon={a.icon} color={a.hue} size={42} />
                  <div className="row gap4">
                    <button onClick={() => dupAgent(a.iid)} className="btn btn-icon btn-sm" style={{ padding: 5, border: 'none', background: 'transparent', color: 'var(--tx-3)' }}><I.copy w={14} /></button>
                    <button onClick={() => removeAgent(a.iid)} className="btn btn-icon btn-sm" style={{ padding: 5, border: 'none', background: 'transparent', color: 'var(--tx-3)' }}><I.trash w={14} /></button>
                  </div>
                </div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{a.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>{a.role}</div>
                <div className="row gap8" style={{ marginTop: 12 }}>
                  <span className="badge" style={{ fontSize: 10, color: i === 0 ? 'var(--violet-2)' : 'var(--tx-2)', background: i === 0 ? 'var(--violet-soft)' : 'oklch(1 0 0 /.05)', borderColor: 'transparent' }}>
                    {i === 0 ? 'Supervisor' : 'Worker'}</span>
                  <span className="badge" style={{ fontSize: 10, color: 'var(--green)', background: 'var(--green-soft)', borderColor: 'transparent' }}><span className="dot" style={{ background: 'var(--green)' }} />Pronto</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  /* -------- Org chart + hierarchy -------- */
  function OrgChart({ roster }) {
    const [rules, setRules] = useState({ reporting: true, approvals: true, delegation: false });
    if (roster.length === 0) return <Empty msg="Adicione agentes na aba Montar para ver o organograma." />;
    const sup = roster[0];
    const children = roster.slice(1);
    const line = 'var(--line-strong)';
    return (
      <div style={{ height: '100%', overflowY: 'auto', padding: '34px 26px', display: 'grid', gridTemplateColumns: '1fr 280px', gap: 24, alignItems: 'start' }}>
        <div>
          {/* supervisor */}
          <div className="col center">
            <OrgCard a={sup} role="Supervisor" highlight />
            {children.length > 0 && <div style={{ width: 2, height: 26, background: line }} />}
            {children.length > 0 && (
              <div style={{ position: 'relative', display: 'flex', gap: 18, justifyContent: 'center', flexWrap: 'wrap' }}>
                <div style={{ position: 'absolute', top: 0, left: 90, right: 90, height: 2, background: line }} />
                {children.map(c => (
                  <div key={c.iid} className="col center">
                    <div style={{ width: 2, height: 20, background: line }} />
                    <OrgCard a={c} role="Worker" />
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* hierarchy settings */}
        <Card style={{ padding: 18 }}>
          <SectionHead icon="sliders" title="Hierarquia" sub="Regras de operação" />
          <div className="eyebrow" style={{ margin: '4px 0 10px' }}>Papéis</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
            <RoleRow label="Agente Supervisor" who={sup ? sup.name : '—'} color="var(--violet-2)" />
            <RoleRow label="Agente Gestor" who={children[0] ? children[0].name : '—'} color="var(--teal)" />
            <RoleRow label="Agentes Workers" who={children.length + ' agentes'} color="var(--green)" />
          </div>
          <div className="hr" style={{ marginBottom: 12 }} />
          {[['reporting', 'Cadeia de reporte', 'Workers reportam ao supervisor'],
            ['approvals', 'Aprovações', 'Ações de alto impacto exigem o supervisor'],
            ['delegation', 'Delegação automática', 'O supervisor distribui tarefas sozinho']].map(([k, t, d]) => (
            <div key={k} className="row between" style={{ padding: '11px 0', borderBottom: '1px solid var(--line)' }}>
              <div style={{ paddingRight: 10 }}><div style={{ fontSize: 12.5, fontWeight: 600 }}>{t}</div><div style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>{d}</div></div>
              <Toggle on={rules[k]} onChange={v => setRules(r => ({ ...r, [k]: v }))} />
            </div>
          ))}
        </Card>
      </div>
    );
  }

  function OrgCard({ a, role, highlight }) {
    return (
      <div className="panel lift" style={{ padding: 14, width: 168, textAlign: 'center', borderColor: highlight ? 'color-mix(in oklab,' + a.hue + ', transparent 50%)' : 'var(--line)',
        background: highlight ? 'color-mix(in oklab,' + a.hue + ', transparent 90%)' : undefined }}>
        <div style={{ display: 'grid', placeItems: 'center', marginBottom: 8 }}><AgentAvatar icon={a.icon} color={a.hue} size={40} /></div>
        <div style={{ fontSize: 13, fontWeight: 700 }}>{a.name}</div>
        <div style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>{a.role}</div>
        <span className="badge" style={{ marginTop: 8, fontSize: 9.5, color: a.hue, background: 'color-mix(in oklab,' + a.hue + ', transparent 86%)', borderColor: 'transparent' }}>{role}</span>
      </div>
    );
  }

  function RoleRow({ label, who, color }) {
    return (
      <div className="row gap10" style={{ padding: '9px 11px', borderRadius: 9, background: 'var(--bg-1)', border: '1px solid var(--line)' }}>
        <span style={{ width: 8, height: 8, borderRadius: 3, background: color, flex: 'none' }} />
        <span className="grow" style={{ fontSize: 12, color: 'var(--tx-1)' }}>{label}</span>
        <span style={{ fontSize: 11.5, fontWeight: 600 }}>{who}</span>
      </div>
    );
  }

  /* -------- Workflow designer -------- */
  function Workflow() {
    const [nodes, setNodes] = useState(D.workflowNodes);
    return (
      <div style={{ height: '100%', overflowY: 'auto', padding: '30px 26px' }}>
        <div className="row between" style={{ maxWidth: 520, margin: '0 auto 8px' }}>
          <div><div className="h3">Designer de Workflow</div><div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>Como o trabalho flui entre os agentes</div></div>
          <button className="btn btn-sm"><I.wand w={14} /> Auto-gerar</button>
        </div>
        <div style={{ maxWidth: 520, margin: '0 auto', display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 16 }}>
          {nodes.map((n, i) => {
            const Ic = I[n.icon];
            return (
              <React.Fragment key={n.id}>
                <div className="panel lift" style={{ padding: '13px 16px', width: '100%', display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ display: 'grid', placeItems: 'center', width: 38, height: 38, borderRadius: 10, flex: 'none',
                    background: 'color-mix(in oklab,' + n.hue + ', transparent 85%)', color: n.hue }}><Ic w={18} /></span>
                  <div className="grow" style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{n.title}</div>
                    <div style={{ fontSize: 11, color: 'var(--tx-2)' }}>{n.agent}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--tx-3)' }}>passo {i + 1}</span>
                  <button onClick={() => setNodes(ns => ns.filter(x => x.id !== n.id))} className="btn btn-icon btn-sm" style={{ padding: 5, border: 'none', background: 'transparent', color: 'var(--tx-3)' }}><I.x w={14} /></button>
                </div>
                <div className="col center" style={{ height: 30 }}>
                  <div style={{ width: 2, flex: 1, background: 'var(--line-strong)' }} />
                  <span style={{ color: 'var(--tx-3)', marginTop: -4 }}><I.chevDown w={16} /></span>
                </div>
              </React.Fragment>
            );
          })}
          <button className="row center gap8" style={{ width: '100%', padding: 14, borderRadius: 12, border: '1.5px dashed var(--line-strong)', background: 'transparent', color: 'var(--tx-2)', cursor: 'pointer', fontSize: 12.5, fontWeight: 600 }}>
            <I.plus w={15} /> Adicionar passo
          </button>
        </div>
      </div>
    );
  }

  /* -------- Inter-agent comms -------- */
  function Comms() {
    const msgs = D.teamChatter;
    const [count, setCount] = useState(0);
    const [typing, setTyping] = useState(false);
    const ref = useRef(null);
    useEffect(() => {
      if (count >= msgs.length) return;
      setTyping(count > 0);
      const t = setTimeout(() => { setTyping(false); setCount(c => c + 1); }, count === 0 ? 350 : 1200);
      return () => clearTimeout(t);
    }, [count]);
    useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [count, typing]);
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div className="row gap10" style={{ padding: '14px 26px', borderBottom: '1px solid var(--line)' }}>
          <span className="badge" style={{ color: 'var(--green)', background: 'var(--green-soft)', borderColor: 'transparent' }}><span className="dot dot-pulse" style={{ background: 'var(--green)', color: 'var(--green)' }} />Sistema vivo</span>
          <span style={{ fontSize: 12.5, color: 'var(--tx-2)' }}>Os agentes coordenam entre si em tempo real</span>
        </div>
        <div ref={ref} style={{ flex: 1, overflowY: 'auto', padding: '22px 26px', maxWidth: 720, width: '100%', margin: '0 auto' }}>
          {msgs.slice(0, count).map((m, i) => (
            <div key={i} className="fadein row gap10" style={{ marginBottom: 16, alignItems: 'flex-start' }}>
              <AgentAvatar icon="cpu" color={m.hue} size={32} round />
              <div style={{ maxWidth: '78%' }}>
                <div className="row gap8" style={{ marginBottom: 4 }}>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: m.hue }}>{m.name}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--tx-3)' }}>{m.time}</span>
                </div>
                <div style={{ padding: '10px 14px', borderRadius: '4px 14px 14px 14px', fontSize: 13.5, lineHeight: 1.5, background: 'var(--bg-2)', border: '1px solid var(--line)' }}>{m.text}</div>
              </div>
            </div>
          ))}
          {typing && count < msgs.length && (
            <div className="row gap10"><AgentAvatar icon="cpu" color={msgs[count].hue} size={32} round />
              <div style={{ padding: '13px 16px', borderRadius: 14, background: 'var(--bg-2)', border: '1px solid var(--line)' }}><Typing color={msgs[count].hue} /></div></div>
          )}
        </div>
      </div>
    );
  }

  function Empty({ msg }) {
    return <div style={{ height: '100%', display: 'grid', placeItems: 'center', color: 'var(--tx-3)', fontSize: 13, padding: 40, textAlign: 'center' }}>{msg}</div>;
  }

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