/* ============================================================
   ZERO — Agent Builder. window.Screens.Agentbuilder
   ============================================================ */
(function () {
  const { useState, useMemo } = React;
  const I = window.Icon;
  const { Card, SectionHead, Toggle, Badge } = window.UI;
  const { Slider, Radar, AgentAvatar } = window.BUILD;
  const D = window.DATA;

  function Field({ label, value, onChange, placeholder, textarea, hint }) {
    return (
      <div>
        <div className="row between" style={{ marginBottom: 6 }}>
          <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--tx-1)' }}>{label}</label>
          {hint && <span style={{ fontSize: 10.5, color: 'var(--tx-3)' }}>{hint}</span>}
        </div>
        {textarea
          ? <textarea className="zin" rows={textarea} value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} style={{ resize: 'vertical', lineHeight: 1.55 }} />
          : <input type="text" className="zin" value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} />}
      </div>
    );
  }

  function Agentbuilder() {
    const [cfg, setCfg] = useState({
      name: 'Growth Alpha', role: 'Agente CMO',
      desc: 'Especialista em aquisição e retenção, opera todo o funil de marketing.',
      mission: 'Crescer a receita através de automação de marketing.',
      personality: { ...D.personalityPresets[7].v },
      preset: 'Estratégico',
      prompt: '',
      tools: new Set(D.builderTools.filter(t => t.connected).map(t => t.name)),
      perms: Object.fromEntries(D.builderPermissions.map(p => [p.id, p.def])),
      model: 'Claude',
      memory: Object.fromEntries(D.memoryConfig.map(m => [m.id, m.def])),
      kpis: ['Aumentar a receita', 'Reduzir churn'],
      color: 'var(--violet)', icon: 'spark',
    });
    const set = (k, v) => setCfg(c => ({ ...c, [k]: v }));
    const [newKpi, setNewKpi] = useState('');

    function applyPreset(p) {
      setCfg(c => ({ ...c, personality: { ...p.v }, preset: p.name }));
    }
    function toggleTool(name) {
      setCfg(c => { const s = new Set(c.tools); s.has(name) ? s.delete(name) : s.add(name); return { ...c, tools: s }; });
    }
    function addKpi() {
      const v = newKpi.trim(); if (!v) return;
      setCfg(c => ({ ...c, kpis: [...c.kpis, v] })); setNewKpi('');
    }

    const promptTokens = Math.round(cfg.prompt.length / 4);
    const model = D.aiModels.find(m => m.name === cfg.model);

    return (
      <div style={{ height: '100%', display: 'grid', gridTemplateColumns: '1fr 348px' }}>
        {/* FORM */}
        <div style={{ overflowY: 'auto', minWidth: 0 }}>
          {/* header */}
          <div className="row between" style={{ padding: '16px 26px', borderBottom: '1px solid var(--line)', position: 'sticky', top: 0, zIndex: 10,
            background: 'oklch(0.16 0.013 265 /.7)', backdropFilter: 'blur(14px)' }}>
            <div className="row gap12">
              <AgentAvatar icon={cfg.icon} color={cfg.color} size={38} />
              <div><div style={{ fontWeight: 700, fontSize: 15 }}>Criar Agente IA</div>
                <div style={{ fontSize: 11.5, color: 'var(--tx-2)' }}>Configure um novo membro da sua equipe</div></div>
            </div>
            <div className="row gap8">
              <button className="btn btn-ghost btn-sm">Cancelar</button>
              <button className="btn btn-sm">Salvar rascunho</button>
              <button className="btn btn-primary btn-sm"><I.check w={14} /> Criar agente</button>
            </div>
          </div>

          <div style={{ padding: '22px 26px 80px', maxWidth: 760, display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* Identity */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="user" title="Identidade" sub="Quem é esse agente" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <Field label="Nome do agente" value={cfg.name} onChange={v => set('name', v)} placeholder="Ex.: Growth Alpha" />
                <Field label="Cargo / Função" value={cfg.role} onChange={v => set('role', v)} placeholder="Ex.: Agente CMO" />
              </div>
              <div style={{ marginTop: 14 }}><Field label="Descrição" value={cfg.desc} onChange={v => set('desc', v)} textarea={2} placeholder="O que esse agente faz…" /></div>
              <div style={{ marginTop: 14 }}><Field label="Declaração de missão" value={cfg.mission} onChange={v => set('mission', v)} placeholder="Ex.: Crescer a receita…" /></div>
            </Card>

            {/* Personality */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="sliders" title="Construtor de Personalidade" sub="Ajuste o comportamento do agente" />
              <div className="row gap8 wrap" style={{ marginBottom: 18 }}>
                {D.personalityPresets.map(p => (
                  <button key={p.name} onClick={() => applyPreset(p)} className="badge" style={{ cursor: 'pointer', padding: '5px 11px',
                    color: cfg.preset === p.name ? 'white' : 'var(--tx-1)',
                    background: cfg.preset === p.name ? cfg.color : 'var(--bg-1)',
                    borderColor: cfg.preset === p.name ? 'transparent' : 'var(--line)' }}>{p.name}</button>
                ))}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 18 }}>
                {D.personalityDims.map(d => (
                  <Slider key={d.id} label={d.label} value={cfg.personality[d.id]} color={cfg.color}
                    onChange={v => setCfg(c => ({ ...c, personality: { ...c.personality, [d.id]: v }, preset: 'Custom' }))} />
                ))}
              </div>
            </Card>

            {/* Core Prompt */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="code" title="Prompt Central" sub="Como o agente deve pensar e operar"
                action={<span className="mono" style={{ fontSize: 11, color: 'var(--tx-3)' }}>~{promptTokens} tokens</span>} />
              <textarea className="zin" rows={5} value={cfg.prompt} onChange={e => set('prompt', e.target.value)}
                placeholder="Defina como esse agente deve pensar e operar…" style={{ resize: 'vertical', lineHeight: 1.55 }} />
              <div className="track" style={{ marginTop: 10 }}><i style={{ width: Math.min(promptTokens / 20, 100) + '%', background: cfg.color }} /></div>
              <div style={{ fontSize: 10.5, color: 'var(--tx-3)', marginTop: 6 }}>Uso do contexto · {Math.min(Math.round(promptTokens / 20), 100)}% de 4.000 tokens</div>
            </Card>

            {/* Tools */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="plug" title="Acesso a Ferramentas" sub={`${cfg.tools.size} de ${D.builderTools.length} habilitadas`} />
              <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(140px,1fr))', gap: 10 }}>
                {D.builderTools.map(t => {
                  const on = cfg.tools.has(t.name);
                  return (
                    <button key={t.name} onClick={() => toggleTool(t.name)} className="row gap10 lift"
                      style={{ padding: '11px 12px', borderRadius: 11, cursor: 'pointer', textAlign: 'left', color: 'var(--tx-0)',
                        border: '1px solid ' + (on ? 'color-mix(in oklab,' + cfg.color + ', transparent 50%)' : 'var(--line)'),
                        background: on ? 'color-mix(in oklab,' + cfg.color + ', transparent 90%)' : 'var(--bg-1)' }}>
                      <span className="avatar" style={{ width: 30, height: 30, borderRadius: 8, fontSize: 11, background: 'var(--bg-3)', color: t.hue, border: '1px solid var(--line)' }}>{t.glyph}</span>
                      <div className="grow" style={{ minWidth: 0 }}>
                        <div className="ellipsis" style={{ fontSize: 12.5, fontWeight: 600 }}>{t.name}</div>
                        <div style={{ fontSize: 9.5, color: t.connected ? 'var(--green)' : 'var(--tx-3)' }}>{t.connected ? 'Conectado' : 'Desconectado'}</div>
                      </div>
                      <span style={{ color: on ? cfg.color : 'var(--tx-3)' }}>{on ? <I.checkCircle w={16} /> : <I.plus w={15} />}</span>
                    </button>
                  );
                })}
              </div>
            </Card>

            {/* Permissions */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="shield" title="Permissões" sub="O que o agente pode fazer sem pedir" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 24px' }}>
                {D.builderPermissions.map(p => (
                  <div key={p.id} className="row between" style={{ padding: '11px 0', borderBottom: '1px solid var(--line)' }}>
                    <span style={{ fontSize: 12.5, color: 'var(--tx-1)' }}>{p.label}</span>
                    <Toggle on={cfg.perms[p.id]} onChange={v => setCfg(c => ({ ...c, perms: { ...c.perms, [p.id]: v } }))} />
                  </div>
                ))}
              </div>
            </Card>

            {/* AI Model */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="cpu" title="Modelo de IA" sub="O motor de raciocínio do agente" />
              <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(130px,1fr))', gap: 10 }}>
                {D.aiModels.map(m => {
                  const on = cfg.model === m.name;
                  return (
                    <button key={m.name} onClick={() => set('model', m.name)} className="lift" style={{ padding: 13, borderRadius: 11, cursor: 'pointer', textAlign: 'left', color: 'var(--tx-0)',
                      border: '1px solid ' + (on ? 'color-mix(in oklab,' + cfg.color + ', transparent 45%)' : 'var(--line)'),
                      background: on ? 'color-mix(in oklab,' + cfg.color + ', transparent 90%)' : 'var(--bg-1)' }}>
                      <div className="row between" style={{ marginBottom: 8 }}>
                        <span style={{ fontWeight: 700, fontSize: 13 }}>{m.name}</span>
                        {on && <span style={{ color: cfg.color }}><I.check w={15} /></span>}
                      </div>
                      <div style={{ fontSize: 10.5, color: 'var(--tx-2)', display: 'flex', flexDirection: 'column', gap: 3 }}>
                        <span className="row between"><span>Latência</span><span style={{ color: 'var(--tx-1)' }}>{m.latency}</span></span>
                        <span className="row between"><span>Raciocínio</span><span style={{ color: 'var(--tx-1)' }}>{m.reasoning}</span></span>
                        <span className="row between"><span>Custo</span><span style={{ color: 'var(--tx-1)' }}>{'$'.repeat(m.cost)}<span style={{ color: 'var(--tx-3)' }}>{'$'.repeat(3 - m.cost)}</span></span></span>
                      </div>
                    </button>
                  );
                })}
              </div>
            </Card>

            {/* Memory */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="layers" title="Configuração de Memória" />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                {D.memoryConfig.map(m => (
                  <div key={m.id}>
                    <Slider label={m.label} value={cfg.memory[m.id]} color={cfg.color}
                      onChange={v => setCfg(c => ({ ...c, memory: { ...c.memory, [m.id]: v } }))} />
                    <div style={{ fontSize: 10.5, color: 'var(--tx-3)', marginTop: 4 }}>{m.desc}</div>
                  </div>
                ))}
              </div>
            </Card>

            {/* Knowledge base */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="upload" title="Base de Conhecimento" sub="Alimente o agente com seus documentos" />
              <div className="placeholder-img" style={{ height: 96, flexDirection: 'column', gap: 6, borderRadius: 12, cursor: 'pointer', marginBottom: 14 }}>
                <I.upload w={22} />
                <span style={{ fontSize: 11.5 }}>Arraste arquivos ou clique para enviar</span>
                <span style={{ fontSize: 10 }}>{D.knowledgeTypes.join(' · ')}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {D.knowledgeFiles.map((f, i) => (
                  <div key={i} className="row gap10" style={{ padding: '9px 12px', borderRadius: 9, background: 'var(--bg-1)', border: '1px solid var(--line)' }}>
                    <span className="avatar" style={{ width: 28, height: 28, borderRadius: 7, fontSize: 8.5, background: 'var(--bg-3)', color: 'var(--tx-1)', border: '1px solid var(--line)' }}>{f.type}</span>
                    <div className="grow" style={{ minWidth: 0 }}>
                      <div className="ellipsis" style={{ fontSize: 12.5, fontWeight: 600 }}>{f.name}</div>
                      {f.prog < 100
                        ? <div className="track" style={{ marginTop: 5 }}><i style={{ width: f.prog + '%', background: cfg.color }} /></div>
                        : <div style={{ fontSize: 10, color: 'var(--tx-3)' }}>{f.size} · indexado</div>}
                    </div>
                    <span style={{ color: f.prog < 100 ? 'var(--amber)' : 'var(--green)' }}>{f.prog < 100 ? <span className="mono" style={{ fontSize: 10 }}>{f.prog}%</span> : <I.checkCircle w={15} />}</span>
                  </div>
                ))}
              </div>
            </Card>

            {/* Objectives & KPIs */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="target" title="Objetivos & KPIs" sub="O que o sucesso significa" />
              <div className="row gap8 wrap" style={{ marginBottom: 12 }}>
                {cfg.kpis.map((k, i) => (
                  <span key={i} className="badge" style={{ padding: '5px 6px 5px 11px', color: 'var(--tx-1)', background: 'var(--bg-1)', borderColor: 'var(--line)' }}>
                    <span style={{ color: cfg.color }}><I.target w={12} /></span>{k}
                    <button onClick={() => setCfg(c => ({ ...c, kpis: c.kpis.filter((_, j) => j !== i) }))} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--tx-3)', padding: 2, display: 'grid' }}><I.x w={12} /></button>
                  </span>
                ))}
              </div>
              <div className="row gap8">
                <input type="text" className="zin" value={newKpi} placeholder="Adicionar um objetivo…" onChange={e => setNewKpi(e.target.value)} onKeyDown={e => e.key === 'Enter' && addKpi()} />
                <button onClick={addKpi} className="btn btn-sm"><I.plus w={14} /> Adicionar</button>
              </div>
              <div className="row gap6 wrap" style={{ marginTop: 12 }}>
                {D.kpiSuggestions.filter(s => !cfg.kpis.includes(s)).map(s => (
                  <button key={s} onClick={() => setCfg(c => ({ ...c, kpis: [...c.kpis, s] }))} className="badge" style={{ cursor: 'pointer', color: 'var(--tx-3)', background: 'transparent', borderColor: 'var(--line)' }}>+ {s}</button>
                ))}
              </div>
            </Card>

            {/* Appearance */}
            <Card style={{ padding: 20 }}>
              <SectionHead icon="palette" title="Aparência do Agente" />
              <div style={{ fontSize: 11.5, color: 'var(--tx-2)', marginBottom: 8 }}>Ícone</div>
              <div className="row gap8 wrap" style={{ marginBottom: 18 }}>
                {D.agentIcons.map(ic => (
                  <button key={ic} onClick={() => set('icon', ic)} style={{ padding: 0, border: '2px solid ' + (cfg.icon === ic ? cfg.color : 'transparent'), borderRadius: 12, cursor: 'pointer', background: 'transparent' }}>
                    <AgentAvatar icon={ic} color={cfg.color} size={40} />
                  </button>
                ))}
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--tx-2)', marginBottom: 8 }}>Cor de destaque</div>
              <div className="row gap8">
                {D.agentColors.map(c => (
                  <button key={c} onClick={() => set('color', c)} style={{ width: 30, height: 30, borderRadius: 9, background: c, cursor: 'pointer',
                    border: '2px solid ' + (cfg.color === c ? 'white' : 'transparent'), boxShadow: cfg.color === c ? '0 0 0 1px var(--bg-0)' : 'none' }} />
                ))}
              </div>
            </Card>
          </div>
        </div>

        {/* LIVE PREVIEW */}
        <div style={{ borderLeft: '1px solid var(--line)', background: 'oklch(0.16 0.013 265 /.4)', overflowY: 'auto' }}>
          <div style={{ padding: 20 }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Preview ao vivo</div>
            <Preview cfg={cfg} model={model} />
          </div>
        </div>
      </div>
    );
  }

  function Preview({ cfg, model }) {
    const tools = D.builderTools.filter(t => cfg.tools.has(t.name));
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* card */}
        <div className="panel" style={{ padding: 18, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: -30, right: -30, width: 120, height: 120, borderRadius: '50%',
            background: `radial-gradient(circle, color-mix(in oklab, ${cfg.color}, transparent 70%), transparent 70%)` }} />
          <div className="row gap12" style={{ position: 'relative' }}>
            <AgentAvatar icon={cfg.icon} color={cfg.color} size={52} />
            <div className="grow" style={{ minWidth: 0 }}>
              <div className="ellipsis" style={{ fontWeight: 800, fontSize: 17, letterSpacing: '-0.02em' }}>{cfg.name || 'Sem nome'}</div>
              <div className="ellipsis" style={{ fontSize: 12, color: 'var(--tx-2)' }}>{cfg.role || 'Sem função'}</div>
              <span className="badge" style={{ marginTop: 6, color: 'var(--green)', background: 'var(--green-soft)', borderColor: 'transparent' }}>
                <span className="dot dot-pulse" style={{ background: 'var(--green)', color: 'var(--green)' }} />Pronto</span>
            </div>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--tx-2)', lineHeight: 1.5, marginTop: 14, position: 'relative' }}>{cfg.mission}</div>
        </div>

        {/* personality graph */}
        <div className="panel-flat" style={{ padding: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Personalidade · {cfg.preset}</div>
          <Radar values={cfg.personality} dims={D.personalityDims} color={cfg.color} size={196} />
        </div>

        {/* capabilities */}
        <div className="panel-flat" style={{ padding: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Capacidades</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12 }}>
            <Stat icon="cpu" label="Modelo" value={cfg.model} />
            <Stat icon="bolt" label="Raciocínio" value={model ? model.reasoning + '/100' : '—'} />
            <Stat icon="plug" label="Ferramentas" value={cfg.tools.size + ' conectadas'} />
            <Stat icon="shield" label="Permissões" value={Object.values(cfg.perms).filter(Boolean).length + ' ativas'} />
            <Stat icon="target" label="KPIs" value={cfg.kpis.length + ' metas'} />
          </div>
        </div>

        {/* tools enabled */}
        <div className="panel-flat" style={{ padding: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Ferramentas habilitadas</div>
          <div className="row gap6 wrap">
            {tools.length ? tools.map(t => (
              <span key={t.name} className="badge" style={{ color: 'var(--tx-1)', background: 'var(--bg-1)', borderColor: 'var(--line)', fontSize: 10.5 }}>
                <span style={{ color: t.hue, fontWeight: 700, fontSize: 9 }}>{t.glyph}</span>{t.name}</span>
            )) : <span style={{ fontSize: 11.5, color: 'var(--tx-3)' }}>Nenhuma ferramenta selecionada</span>}
          </div>
        </div>
      </div>
    );
  }

  function Stat({ icon, label, value }) {
    const Ic = I[icon];
    return (
      <div className="row between">
        <span className="row gap8" style={{ color: 'var(--tx-2)' }}><Ic w={14} />{label}</span>
        <span style={{ fontWeight: 600, color: 'var(--tx-0)' }}>{value}</span>
      </div>
    );
  }

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