/* global React, Icon, Spark, API */

let QR_REFRESH_TIMER = null;

function clearQrRefreshTimer() {
  if (QR_REFRESH_TIMER) clearTimeout(QR_REFRESH_TIMER);
  QR_REFRESH_TIMER = null;
  window.QR_REFRESH_TIMER = null;
}

function scheduleQrRefresh(callback) {
  clearQrRefreshTimer();
  QR_REFRESH_TIMER = setTimeout(() => {
    if (typeof callback === 'function') callback();
  }, 35000);
  window.QR_REFRESH_TIMER = QR_REFRESH_TIMER;
}

function studioToast(message, type = '') {
  if (window.STUDIO?.toast) window.STUDIO.toast(message, type);
}

function studioConfirm(config) {
  return window.STUDIO?.confirm ? window.STUDIO.confirm(config) : Promise.resolve(false);
}

function parseKbSources(text) {
  return String(text || '').split(/\n+/).map(line => line.trim()).filter(Boolean).map(line => {
    if (/^https?:\/\//i.test(line)) return { source_type: 'url', uri: line };
    return { source_type: 'text', content: line };
  });
}

function readKbFiles(files) {
  const list = Array.from(files || []);
  return Promise.all(list.map(file => new Promise(resolve => {
    const reader = new FileReader();
    reader.onload = () => resolve({ source_type: 'file', uri: file.name, mime_type: file.type || 'application/octet-stream', content: reader.result });
    reader.onerror = () => resolve(null);
    reader.readAsDataURL(file);
  }))).then(items => items.filter(Boolean));
}

function parseMemoryVariables(text) {
  const raw = String(text || '').trim();
  if (!raw) return [];
  const normalized = raw.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
  const found = [];
  const add = (name, description) => {
    if (!found.some(item => item.name === name)) found.push({ name, type: 'text', description, persistent: true, save_to_table: true });
  };
  if (/@?nome|nome do usuário|nome do cliente|como se chama/.test(normalized)) add('nome', 'Nome ou forma de tratamento do cliente.');
  if (/@?numero|telefone|whatsapp|celular/.test(normalized)) add('numero', 'Telefone ou número de WhatsApp do cliente.');
  if (/@?email|e-mail|mail/.test(normalized)) add('email', 'Email do cliente para retorno.');
  if (/@?problema|dúvida|dificuldade|erro|motivo|precisa|necessidade/.test(normalized)) add('problema', 'Problema, dúvida ou necessidade principal do cliente.');
  if (/queria falar|quer falar|falar sobre|assunto|pauta|tema/.test(normalized)) add('assunto', 'Assunto que o cliente quer tratar.');
  if (/empresa|organi[sz]ação|instituicao|negócio/.test(normalized)) add('empresa', 'Empresa ou organização do cliente.');
  if (/cpf|cnpj|documento/.test(normalized)) add('documento', 'Documento informado pelo cliente quando necessário.');
  if (found.length) return found;
  return raw.split(/\n|,|;/).map(line => line.trim()).filter(Boolean).slice(0, 6).map(line => {
    const clean = line.replace(/^@+/, '').trim();
    const rawName = clean.split(/[:,-]/)[0].trim() || clean;
    const name = rawName.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/\b(do|da|de|o|a|os|as|ele|ela|cliente|usuário)\b/g, '').replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, '');
    return { name: name || 'info_cliente', type: 'text', description: `Informação do cliente: ${clean}`, persistent: true, save_to_table: true };
  });
}

function manualFormFromTemplate(templateId = 'default') {
  const template = window.WA.agentTemplateById(templateId);
  const preset = window.WA.modelPresetById(template.model_preset || window.WA.DEFAULT_MODEL_PRESET);
  return {
    template_id: template.id,
    name: template.name || '',
    instance_name: template.instance_name || '',
    description: template.description || '',
    ai_model: template.ai_model || preset.model || window.WA.DEFAULT_MODEL,
    model_preset: template.model_preset || preset.id,
    ai_api_key: '',
    temperature: template.temperature ?? preset.temperature ?? 0.7,
    system_prompt: template.system_prompt || window.WA.DEFAULT_PROMPT,
    kb_sources: template.kb_sources || '',
    client_info: template.client_info || '',
    negative_rules: template.negative_rules || [],
    conversation_goals: template.conversation_goals || [],
    final_goal: template.final_goal || '',
    handoff_config: template.handoff_config || { enabled: false, conditions: [], next_action: '' },
  };
}

window.AgentsPage = function AgentsPage({ onOpenAgent, onNewAgent }) {
  const [q, setQ] = React.useState('');
  const [view, setView] = React.useState('grid');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [modalMode, setModalMode] = React.useState(null);
  const [manualForm, setManualForm] = React.useState(() => manualFormFromTemplate());
  const [manualKbFiles, setManualKbFiles] = React.useState([]);
  const [detailIndex, setDetailIndex] = React.useState(0);
  const [detailAnswers, setDetailAnswers] = React.useState({});
  const [detailWorking, setDetailWorking] = React.useState(false);
  const [detailError, setDetailError] = React.useState('');
  const [detailCreated, setDetailCreated] = React.useState(null);
  const [createdGuide, setCreatedGuide] = React.useState(null);
  const [qrAgent, setQrAgent] = React.useState(null);
  const [qrData, setQrData] = React.useState(null);
  const [qrLoading, setQrLoading] = React.useState(false);
  const [qrCountdown, setQrCountdown] = React.useState(30);
  const data = window.MOCK || {};
  const agents = data.agents || [];
  const list = agents.filter(agent => {
    const text = `${agent.name} ${agent.role} ${agent.model} ${agent.channel}`.toLowerCase();
    const statusMatch =
      statusFilter === 'all' ||
      (statusFilter === 'online' && agent.status === 'online') ||
      (statusFilter === 'attention' && agent.status !== 'online') ||
      (statusFilter === 'disconnected' && ['offline', 'not_found', 'expired'].includes(agent.status));
    return statusMatch && text.includes(q.toLowerCase());
  });
  const counts = {
    online: agents.filter(a => a.status === 'online').length,
    attention: agents.filter(a => a.status !== 'online').length,
    disconnected: agents.filter(a => ['offline', 'not_found', 'expired'].includes(a.status)).length,
  };

  async function deleteAgent(agent) {
    if (!(await studioConfirm({ title: 'Excluir agente', message: `Excluir agente "${agent.name}"?`, confirmLabel: 'Excluir', danger: true }))) return;
    try {
      await API.deleteAgent(agent.id);
      await window.STUDIO.refresh();
      studioToast('Agente excluido.');
    } catch (err) {
      studioToast(err.message || String(err), 'bad');
    }
  }

  async function createManualAgent() {
    const name = manualForm.name.trim();
    if (!name) {
      studioToast('Informe o nome do agente.', 'bad');
      return;
    }
    try {
      const fileSources = await readKbFiles(manualKbFiles);
      const kbSources = [...parseKbSources(manualForm.kb_sources), ...fileSources];
      const memoryVariables = parseMemoryVariables(manualForm.client_info);
      const created = await API.createAgent({
        name,
        instance_name: manualForm.instance_name.trim() || name,
        description: manualForm.description.trim(),
        ai_model: manualForm.ai_model || window.WA.DEFAULT_MODEL,
        ai_api_key: String(manualForm.ai_api_key || '').trim(),
        temperature: Number(manualForm.temperature ?? 0.7),
        system_prompt: manualForm.system_prompt.trim() || window.WA.DEFAULT_PROMPT,
        negative_rules: manualForm.negative_rules || [],
        conversation_goals: (manualForm.conversation_goals || []).length ? manualForm.conversation_goals : memoryVariables.map(item => `Coletar ${item.name} quando fizer sentido.`),
        final_goal: manualForm.final_goal || '',
        handoff_config: manualForm.handoff_config || { enabled: false, conditions: [], next_action: '' },
        kb_sources: kbSources,
        tools: {
          contextual_memory: { enabled: true, variables: memoryVariables },
          knowledge_base: { enabled: kbSources.length > 0 },
          ticket_creation: { enabled: true },
        },
      });
      setManualForm(manualFormFromTemplate());
      setManualKbFiles([]);
      setModalMode(null);
      await window.STUDIO.refresh();
      setCreatedGuide({ id: created?.agent_id || created?.id, name, kbCount: kbSources.length, memoryCount: memoryVariables.length });
      studioToast(created?.post_create_error ? `Agente criado, mas fontes/ferramentas falharam: ${created.post_create_error}` : 'Agente criado.', created?.post_create_error ? 'bad' : '');
    } catch (err) {
      studioToast(err.message || String(err), 'bad');
    }
  }

  function applyManualTemplate(templateId) {
    setManualForm(manualFormFromTemplate(templateId));
    setManualKbFiles([]);
  }

  function applyModelPreset(presetId) {
    const preset = window.WA.modelPresetById(presetId);
    setManualForm(prev => ({ ...prev, model_preset: preset.id, ai_model: preset.model, temperature: preset.temperature }));
  }

  function startDetailedAgentBuilder() {
    setDetailIndex(0);
    setDetailAnswers({ kb_sources: '', kb_files: [] });
    setDetailError('');
    setDetailCreated(null);
    setDetailWorking(false);
    setModalMode('detail');
  }

  async function nextDetailedBuilder() {
    if (detailWorking || detailCreated) return;
    const questions = window.WA.DETAIL_BUILDER_QUESTIONS;
    if (detailIndex < questions.length - 1) {
      setDetailError('');
      setDetailIndex(detailIndex + 1);
      return;
    }
    setDetailWorking(true);
    setDetailError('');
    try {
      const builderQuestions = questions.filter(qn => qn.kind !== 'kb');
      const description = builderQuestions.map(qn => `${qn.label}\n${detailAnswers[qn.id] || ''}`).join('\n\n');
      const fileSources = await readKbFiles(detailAnswers.kb_files);
      const kbSources = [...parseKbSources(detailAnswers.kb_sources), ...fileSources];
      const memoryVariables = parseMemoryVariables(detailAnswers.client_info);
      const preview = await API.agentBuilderPreview({ description, temperature: 0.2, kb_sources: kbSources }).catch(() => ({ fallback: true, description }));
      const name = preview.name || titleFromDescription(description);
      const created = await API.createAgent({
        name,
        instance_name: `${name}-${Math.random().toString(36).slice(2, 7)}`,
        description: preview.description || description.slice(0, 240),
        ai_model: window.WA.DEFAULT_MODEL,
        temperature: Number(preview.temperature ?? 0.7),
        system_prompt: preview.system_prompt || window.WA.DEFAULT_PROMPT,
        negative_rules: normalizeBuilderList(preview.instructions?.dont || preview.constraints || preview.negative_rules),
        conversation_goals: normalizeBuilderList(preview.conversation_goals || preview.goals),
        final_goal: preview.final_goal || '',
        handoff_config: preview.handoff_config || { enabled: true, conditions: ['pedido de humano', 'baixa confiança'], next_action: 'criar ticket' },
        conditional_prompts: preview.conditional_prompts || [],
        kb_sources: kbSources,
        tools: toolsFromSuggested(preview.suggested_tools || [], memoryVariables, kbSources.length > 0),
        contextual_memory: { enabled: true },
      });
      const fresh = await window.STUDIO.refresh();
      const agentId = created?.agent_id || created?.id || (fresh?.agents || []).find(agent => agent.name === name)?.id;
      setDetailCreated({ id: agentId, name, kbCount: kbSources.length, memoryCount: memoryVariables.length });
      studioToast(created?.post_create_error ? `Agente criado, mas fontes/ferramentas falharam: ${created.post_create_error}` : 'Agente criado pelo builder.', created?.post_create_error ? 'bad' : '');
    } catch (err) {
      setDetailError(err.message || String(err));
      studioToast(err.message || String(err), 'bad');
    } finally {
      setDetailWorking(false);
    }
  }

  function closeDetailedBuilder() {
    setModalMode(null);
    setDetailCreated(null);
    setDetailError('');
  }

  function openCreatedAgent() {
    const id = detailCreated?.id;
    closeDetailedBuilder();
    if (id) onOpenAgent(id);
  }

  async function openQr(agent) {
    setQrAgent(agent);
    setQrData(null);
    await refreshQr(agent);
  }

  async function refreshQr(agent = qrAgent) {
    if (!agent) return;
    setQrLoading(true);
    try {
      const data = await API.getQr(agent.id);
      setQrData(data);
      setQrCountdown(30);
      scheduleQrRefresh(() => refreshQr(agent));
    } catch (err) {
      setQrData({ error: err.message || String(err) });
    } finally {
      setQrLoading(false);
    }
  }

  function closeQr() {
    clearQrRefreshTimer();
    setQrAgent(null);
    setQrData(null);
  }

  React.useEffect(() => {
    if (!qrAgent) return undefined;
    const timer = setInterval(() => setQrCountdown(value => Math.max(value - 1, 0)), 1000);
    return () => clearInterval(timer);
  }, [qrAgent?.id]);

  React.useEffect(() => {
    if (!qrAgent) return undefined;
    const timer = setInterval(() => window.STUDIO?.refresh?.().catch(() => {}), 5000);
    return () => clearInterval(timer);
  }, [qrAgent?.id]);

  return (
    <>
      <div className="page-head">
        <div>
          <div className="page-eyebrow">Inteligência - {agents.length} bots</div>
          <h1 className="page-title">Bots de IA</h1>
          <p className="page-sub">Assistentes que respondem no site e no WhatsApp. Novos bots ficam em rascunho até o setup terminar.</p>
        </div>
        <div className="page-meta">
          <button className="tb-btn" onClick={() => setModalMode('manual')}><Icon name="plus" size={12}/> Criar bot de IA</button>
          <button className="tb-btn primary" onClick={startDetailedAgentBuilder}>Criar agente detalhadamente</button>
        </div>
      </div>

      <div className="page">
        {!agents.length && (
          <div className="empty-cta">
            <strong>Comece criando o primeiro bot de IA.</strong>
            <div className="inline-help">Depois o setup guia WhatsApp, testes e publicação.</div>
            <button className="tb-btn primary" onClick={() => setModalMode('manual')}><Icon name="plus" size={12}/> Criar bot de IA</button>
          </div>
        )}

        <div className="panel">
          <div className="panel-head">
            <div className="toolbar-wrap">
              <div className="topbar-search local-search">
                <Icon name="search" size={13}/>
                <input value={q} onChange={event => setQ(event.target.value)} placeholder="Buscar agente, papel, modelo..."/>
              </div>
              <button className={`fp ${statusFilter === 'all' ? 'active' : ''}`} onClick={() => setStatusFilter('all')}>Todos <span className="count">{agents.length}</span></button>
              <button className={`fp ${statusFilter === 'online' ? 'active' : ''}`} onClick={() => setStatusFilter('online')}>Conectados <span className="count">{counts.online}</span></button>
              <button className={`fp ${statusFilter === 'attention' ? 'active' : ''}`} onClick={() => setStatusFilter('attention')}>Requer ação <span className="count">{counts.attention}</span></button>
              <button className={`fp ${statusFilter === 'disconnected' ? 'active' : ''}`} onClick={() => setStatusFilter('disconnected')}>Sem conexão <span className="count">{counts.disconnected}</span></button>
              <div className="view-toggle" style={{ marginLeft: 'auto', display: 'flex', gap: 2 }}>
                <button className={`tb-btn ghost icon-btn ${view === 'table' ? 'active' : ''}`} title="Tabela" onClick={() => setView('table')}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="4"/><rect x="3" y="11" width="18" height="4"/><rect x="3" y="19" width="18" height="2"/></svg>
                </button>
                <button className={`tb-btn ghost icon-btn ${view === 'grid' ? 'active' : ''}`} title="Cards" onClick={() => setView('grid')}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="8" height="8"/><rect x="13" y="3" width="8" height="8"/><rect x="3" y="13" width="8" height="8"/><rect x="13" y="13" width="8" height="8"/></svg>
                </button>
              </div>
            </div>
          </div>

          {view === 'grid' ? (
            <div className="agents-grid stagger-children">
              {list.map((agent) => {
                const status = agent.statusTag || (agent.status === 'online' ? 'ok' : ['connecting', 'not_found'].includes(agent.status) ? 'warn' : agent.status === 'offline' ? 'bad' : '');
                return (
                  <div key={agent.id} className="agent-card" onClick={() => onOpenAgent(agent.id)}>
                    <div className="agent-card-head">
                      <span className="av-mark lg">{agent.name[0]}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="agent-card-name">{agent.name}</div>
                        <div className="agent-card-sub">{agent.role}</div>
                      </div>
                      <span className={`badge ${status}`}><span className={`sw ${status}`}/></span>
                    </div>
                    <div className="agent-card-stats">
                      <div className="agent-stat"><span className="agent-stat-val">{agent.conversations}</span><span className="agent-stat-lbl">conversas</span></div>
                      <div className="agent-stat"><span className="agent-stat-val">{agent.tickets}</span><span className="agent-stat-lbl">tickets</span></div>
                      <div className="agent-stat"><span className="agent-stat-val">{agent.latency ? agent.latency + 'ms' : '--'}</span><span className="agent-stat-lbl">latência</span></div>
                    </div>
                    <div className="agent-card-foot">
                      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{agent.model}</span>
                      <span className={`pill ${agent.isPublished ? 'pill-ok' : 'pill-warn'}`}>{agent.isPublished ? 'Produção' : 'Rascunho'}</span>
                    </div>
                    <div className="agent-card-actions" onClick={e => e.stopPropagation()}>
                      <button className="tb-btn ghost" onClick={() => openQr(agent)}>QR</button>
                      <button className="tb-btn danger" onClick={() => deleteAgent(agent)}>Excluir</button>
                    </div>
                  </div>
                );
              })}
              {!list.length && <div className="empty" style={{ gridColumn: '1/-1', padding: '32px 0', textAlign: 'center' }}>Nenhum bot encontrado.</div>}
            </div>
          ) : (
          <table className="dt agents-table">
            <thead>
              <tr>
                <th>Bot de IA</th><th>Setup</th><th>Modelo</th><th>Canal</th>
                <th className="num">Conversas</th><th className="num">Tickets</th><th className="num">Latência</th>
                <th>Tendencia</th><th>Status</th><th></th>
              </tr>
            </thead>
            <tbody>
              {list.map((agent, i) => {
                const status = agent.statusTag || (agent.status === 'online' ? 'ok' : ['connecting', 'not_found'].includes(agent.status) ? 'warn' : agent.status === 'offline' ? 'bad' : '');
                const spark = Array.from({ length: 8 }, (_, k) => 20 + ((agent.runs + i + k * 7) % 70));
                return (
                  <tr key={agent.id}>
                    <td data-label="Bot de IA">
                      <button className="table-link agent-identity" onClick={() => onOpenAgent(agent.id)}>
                        <span className="av-mark">{agent.name[0]}</span>
                        <div className="identity-copy">
                          <div className="identity-title">{agent.name}</div>
                          <div className="identity-sub">{agent.role} - {agent.kbSources} fontes - {agent.tools} tools</div>
                        </div>
                      </button>
                    </td>
                    <td data-label="Setup"><span className={`pill ${agent.isPublished ? 'pill-ok' : 'pill-warn'}`}>{agent.setupLabel || (agent.isPublished ? 'Em produção' : 'Rascunho')}</span></td>
                    <td data-label="Modelo" className="mono">{agent.model}</td>
                    <td data-label="Canal">{agent.channel}</td>
                    <td className="num" data-label="Conversas">{agent.conversations.toLocaleString('pt-BR')}</td>
                    <td className="num" data-label="Tickets">{agent.tickets}</td>
                    <td className="num" data-label="Latência">{agent.latency ? agent.latency + ' ms' : '--'}</td>
                    <td data-label="Tendencia" style={{ width: 100 }}><Spark data={spark} color="var(--accent)"/></td>
                    <td data-label="Status"><span className={`badge ${status}`} title="Status da conexão WhatsApp"><span className={`sw ${status}`}/> {agent.statusLabel || agent.status}</span></td>
                    <td data-label="" className="actions-cell">
                      <div className="row-actions agent-actions">
                        <button className="tb-btn ghost" onClick={() => onOpenAgent(agent.id)}>Abrir</button>
                        <button className="tb-btn ghost" onClick={() => openQr(agent)}>QR</button>
                        <button className="tb-btn danger" onClick={() => deleteAgent(agent)}>Excluir</button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {!list.length && <tr><td colSpan="10" className="empty">Nenhum bot encontrado.</td></tr>}
            </tbody>
          </table>
          )}
        </div>

        <div className="module-grid-3">
          <InfoPanel title="Criar agente" rows={['Manual: nome, modelo e prompt.', 'Com IA: builder gera persona e regras.', 'Detalhado: fluxo guiado em etapas.']}/>
          <InfoPanel title="Memória contextual" rows={['@nome, @numero, @email, @problema, @necessidade.', 'Persistência por conversa e agente.', 'Nunca exibida ao usuário final.']}/>
          <InfoPanel title="Templates condicionais" rows={['Comercial, suporte, humano, dados.', 'Intent, regex, state_equals, always.', 'Editaveis no perfil do agente.']}/>
        </div>
      </div>

      {modalMode === 'manual' && (
        <div className="modal-backdrop open">
          <div className="create-modal">
            <div className="create-head">
              <div>
                <div className="create-title">Novo bot de IA</div>
                <div className="create-sub">Crie o rascunho. O setup guia conexão, teste e publicação.</div>
              </div>
              <button className="tb-btn ghost" onClick={() => setModalMode(null)}>Fechar</button>
            </div>
            <div className="create-body">
              <div className="create-grid">
                <label className="fg">
                  <span className="fl tooltip" data-tip="Manual usa um template simples. Detalhado faz perguntas e sugere configurações.">Tipo de criação</span>
                  <select className="input" value={manualForm.template_id} onChange={e => applyManualTemplate(e.target.value)}>
                    {window.WA.AGENT_TEMPLATES.map(template => <option key={template.id} value={template.id}>{template.label}</option>)}
                  </select>
                </label>
                <label className="fg">
                  <span className="fl fl-required tooltip" data-tip="Nome visivel do bot. Pode mudar depois.">Nome do bot</span>
                  <input className="input" value={manualForm.name} onChange={e => setManualForm(prev => ({ ...prev, name: e.target.value }))} placeholder="Ex: Mateus"/>
                </label>
                <label className="fg">
                  <span className="fl tooltip" data-tip="Apelido técnico usado internamente para a conta conectada. Se vazio, usa o nome do bot.">Nome interno</span>
                  <input className="input" value={manualForm.instance_name} onChange={e => setManualForm(prev => ({ ...prev, instance_name: e.target.value }))} placeholder="vazio usa o nome"/>
                </label>
                <label className="fg span-2">
                  <span className="fl">Descrição</span>
                  <textarea className="input prose-input" rows="3" value={manualForm.description} onChange={e => setManualForm(prev => ({ ...prev, description: e.target.value }))} placeholder="O que este agente faz?"/>
                </label>
                <label className="fg span-2">
                  <span className="fl tooltip" data-tip="Documentos, URLs ou textos que o bot pode consultar. Opcional.">Base de conhecimento</span>
                  <textarea className="input prose-input" rows="4" value={manualForm.kb_sources} onChange={e => setManualForm(prev => ({ ...prev, kb_sources: e.target.value }))} placeholder="Cole URLs, uma por linha, ou texto direto para indexar."/>
                </label>
                <label className="fg span-2">
                  <span className="fl">Anexos da base</span>
                  <input className="input file-input" type="file" multiple onChange={e => setManualKbFiles(Array.from(e.target.files || []))}/>
                  <span className="field-hint">{manualKbFiles.length ? `${manualKbFiles.length} arquivo(s) selecionado(s)` : 'PDF, DOCX ou arquivos de texto.'}</span>
                </label>
                <label className="fg span-2">
                  <span className="fl tooltip" data-tip="Dados que o bot deve lembrar na conversa, como nome, telefone e necessidade.">Informações do cliente a coletar</span>
                  <textarea className="input prose-input" rows="3" value={manualForm.client_info} onChange={e => setManualForm(prev => ({ ...prev, client_info: e.target.value }))} placeholder={"@nome\n@numero\n@email\n@problema\n@necessidade"}/>
                </label>
                <label className="fg">
                  <span className="fl tooltip" data-tip="Qual IA usar. GPT-4o mini é bom para português com custo baixo; modelos Groq são mais rápidos.">Qual IA usar?</span>
                  <select className="input" value={manualForm.model_preset} onChange={e => applyModelPreset(e.target.value)}>
                    {window.WA.MODEL_PRESETS.map(preset => <option key={preset.id} value={preset.id}>{preset.label} - temp {preset.temperature}</option>)}
                  </select>
                  <span className="field-hint">{manualForm.ai_model}</span>
                </label>
                <label className="fg">
                  <span className="fl tooltip" data-tip="Chave usada apenas por este agente. Se ficar vazio, o backend tenta a chave global do provedor no .env.">Chave de API do agente</span>
                  <input className="input mono" type="password" autoComplete="new-password" spellCheck="false" value={manualForm.ai_api_key} onChange={e => setManualForm(prev => ({ ...prev, ai_api_key: e.target.value }))} placeholder="sk-..., gsk_... ou chave NVIDIA"/>
                  <span className="field-hint">Opcional quando a chave global do provedor já está configurada.</span>
                </label>
                <label className="fg span-2">
                  <span className="fl fl-required tooltip" data-tip="Instrução principal: como o bot deve falar, limites e objetivo.">Prompt base</span>
                  <textarea className="input prose-input" rows="6" value={manualForm.system_prompt} onChange={e => setManualForm(prev => ({ ...prev, system_prompt: e.target.value }))}/>
                </label>
              </div>
            </div>
            <div className="create-actions">
              <button className="tb-btn" onClick={startDetailedAgentBuilder}>Criar agente detalhadamente</button>
              <button className="tb-btn primary" onClick={createManualAgent}>Criar</button>
            </div>
          </div>
        </div>
      )}

      {modalMode === 'detail' && <DetailedBuilder
        detailIndex={detailIndex}
        setDetailIndex={setDetailIndex}
        answers={detailAnswers}
        setAnswers={setDetailAnswers}
        working={detailWorking}
        error={detailError}
        created={detailCreated}
        onNext={nextDetailedBuilder}
        onClose={closeDetailedBuilder}
        onOpenCreated={openCreatedAgent}
      />}

      {createdGuide && (
        <div className="modal-backdrop open">
          <div className="create-modal success-modal">
            <div className="success-mark"><Icon name="check" size={18}/></div>
            <div className="create-title">Bot criado</div>
            <div className="create-sub">"{createdGuide.name}" está em rascunho. Siga o setup para conectar WhatsApp, testar e publicar.</div>
            <div className="next-steps">
              <button onClick={() => { setCreatedGuide(null); onOpenAgent(createdGuide.id); }}>
                <span className="pill pill-warn">1</span>
                <strong>Abrir setup</strong>
                <small>Checklist, pendências e publicação.</small>
              </button>
              <button onClick={() => { const agent = (window.MOCK.agents || []).find(item => String(item.id) === String(createdGuide.id)); if (agent) openQr(agent); setCreatedGuide(null); }}>
                <span className="pill pill-warn">2</span>
                <strong>Conectar WhatsApp</strong>
                <small>Gerar QR e vincular aparelho.</small>
              </button>
              <button onClick={() => { setCreatedGuide(null); onOpenAgent(createdGuide.id); }}>
                <span className="pill pill-muted">3</span>
                <strong>Testar respostas</strong>
                <small>Use o sandbox antes de publicar.</small>
              </button>
            </div>
            <div className="create-actions">
              <button className="tb-btn" onClick={() => setCreatedGuide(null)}>Depois</button>
              <button className="tb-btn primary" onClick={() => { setCreatedGuide(null); onOpenAgent(createdGuide.id); }}>Começar setup</button>
            </div>
          </div>
        </div>
      )}

      {qrAgent && (
        <div className="modal-backdrop open" id="qr-modal">
          <div className="create-modal qr-modal-card">
            {(() => {
              const liveAgent = (window.MOCK?.agents || []).find(item => String(item.id) === String(qrAgent.id)) || qrAgent;
              const connected = liveAgent.status === 'online';
              return (
                <>
            <div className="create-head">
              <div>
                <div className="create-title">Vincular WhatsApp</div>
                <div className="create-sub">{qrAgent.name} - escaneie pelo app do WhatsApp. Válido por {qrCountdown}s.</div>
              </div>
              <button className="tb-btn ghost" onClick={closeQr}>Fechar</button>
            </div>
            <div className="qr-panel">
              <div className={`qr-status ${qrData?.error ? 'bad' : connected ? 'ok' : ''}`}>
                <span>{connected ? 'WhatsApp conectado' : qrData?.error ? 'Falha ao gerar QR' : qrData ? 'Aguardando confirmação...' : 'Gerando QR...'}</span>
                <span className="mono">{connected ? 'pronto' : `renova em ${qrCountdown}s`}</span>
              </div>
              <div className="progress qr-progress"><span style={{width: `${Math.max((qrCountdown / 30) * 100, 0)}%`}}></span></div>
              <div className="qrbox" id="qr-modal-box">
                {connected
                  ? <div className="qr-success"><div className="success-mark"><Icon name="check" size={18}/></div><strong>Conectado</strong><span>Agora teste o bot e publique quando estiver pronto.</span></div>
                  : qrData?.base64 || qrData?.qrcode
                  ? <img alt="QR Code WhatsApp" src={qrSrc(qrData)}/>
                  : <div className="empty">{qrData?.error || 'Gerando QR Code...'}</div>}
              </div>
              <div className="qr-help">WhatsApp > Aparelhos conectados > Conectar aparelho. Se expirar, gere outro QR.</div>
            </div>
            <div className="create-actions">
              <button className="tb-btn" onClick={closeQr}>Fechar</button>
              <button className="tb-btn primary" onClick={() => refreshQr()} disabled={qrLoading || connected}>{qrLoading ? 'Gerando...' : 'Gerar novo QR'}</button>
            </div>
                </>
              );
            })()}
          </div>
        </div>
      )}
    </>
  );
};

function DetailedBuilder({ detailIndex, setDetailIndex, answers, setAnswers, working, error, created, onNext, onClose, onOpenCreated }) {
  const questions = window.WA.DETAIL_BUILDER_QUESTIONS;
  const q = questions[detailIndex];
  const isKbStep = q.kind === 'kb';
  const completion = Math.round(((detailIndex + 1) / questions.length) * 100);
  if (created) {
    return (
      <div className="modal-backdrop open">
        <div className="create-modal success-modal" id="create-detail-success">
          <div className="success-mark"><Icon name="check" size={18}/></div>
          <div className="create-title">Agente criado</div>
          <div className="create-sub">"{created.name}" foi salvo no backend. {created.kbCount ? `${created.kbCount} fonte(s) de KB foram anexadas.` : 'Nenhuma KB foi anexada.'}</div>
          <div className="success-facts">
            <span><b>{created.memoryCount || 0}</b> memorias</span>
            <span><b>{created.kbCount || 0}</b> fontes KB</span>
            <span><b>{created.id || '--'}</b> ID</span>
          </div>
          <div className="create-actions">
            <button className="tb-btn" onClick={onClose}>Voltar para lista</button>
            <button className="tb-btn primary" onClick={onOpenCreated}>Abrir perfil</button>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="modal-backdrop open">
      <div className="create-modal wide" id="create-detail-step">
        <div className="create-head">
          <div>
            <div className="detail-progress">{detailIndex + 1} de {questions.length} - {completion}% completo</div>
            <div className="create-title">Criar agente detalhadamente</div>
            <div className="create-sub">Responda por etapas. Builder cria persona, prompt, regras, ferramentas e condicionais. KB e anexos são opcionais.</div>
          </div>
          <button className="tb-btn ghost" disabled={working} onClick={onClose}>Fechar</button>
        </div>
        <div className="builder-progress-track" style={{'--progress': `${completion}%`}}>
          <span></span>
        </div>
        <div className="builder-stepbar">
          {questions.map((item, idx) => (
            <button
              key={item.id}
              type="button"
              className={`${idx < detailIndex ? 'done' : ''} ${idx === detailIndex ? 'active' : ''}`}
              disabled={working}
              onClick={() => setDetailIndex(idx)}
            >
              <span>{idx + 1}</span>
              <em>{item.optional ? 'Opcional' : stepLabel(item)}</em>
            </button>
          ))}
        </div>
        <div className="create-body">
          {isKbStep ? (
            <div className="builder-kb-step">
              <div className="kb-drop-card">
                <div>
                  <div className="panel-title">Bases opcionais do agente</div>
                  <p>Cole links, textos curtos ou anexe arquivos. Se deixar vazio, o agente será criado sem KB inicial.</p>
                </div>
                <span className="badge accent">Opcional</span>
              </div>
              <label className="fg">
                <span className="fl">URLs ou textos</span>
                <textarea
                  className="input prose-input"
                  rows="7"
                  value={answers.kb_sources || ''}
                  onChange={e => setAnswers(prev => ({ ...prev, kb_sources: e.target.value }))}
                  placeholder={"https://site.com/manual\nTexto interno importante..."}
                />
              </label>
              <label className="fg">
                <span className="fl">Anexos</span>
                <input className="input file-input" type="file" multiple onChange={e => setAnswers(prev => ({ ...prev, kb_files: Array.from(e.target.files || []) }))}/>
                <span className="field-hint">{(answers.kb_files || []).length ? `${answers.kb_files.length} arquivo(s) selecionado(s)` : 'Opcional. PDF, DOCX ou texto.'}</span>
              </label>
            </div>
          ) : (
            <label className="fg">
              <span className="fl">{q.label}</span>
              <textarea
                className="input prose-input"
                style={{minHeight:180}}
                value={answers[q.id] || ''}
                onChange={e => setAnswers(prev => ({ ...prev, [q.id]: e.target.value }))}
                placeholder="Responda esta etapa."
              />
            </label>
          )}
          <div className="fg">
            <label className="fl">Memória contextual sugerida</label>
            <div id="builder-memory-cards" className="builder-memory-grid">
              {(parseMemoryVariables(answers.client_info).length ? parseMemoryVariables(answers.client_info).map(item => item.name) : ['nome','telefone','email','necessidade']).slice(0, 6).map(name => <div className="builder-memory-card" key={name}><div className="builder-memory-name">@{name} <span>text</span></div><div className="builder-memory-desc">contextual_memory</div></div>)}
            </div>
          </div>
          {error && <div className="inline-error">{error}</div>}
          {working && <div className="builder-working"><span></span><div><b>Criando agente...</b><em>Gerando prompt, ferramentas, condicionais e salvando no backend.</em></div></div>}
        </div>
        <div className="create-actions">
          <button className="tb-btn" disabled={detailIndex === 0 || working} onClick={() => setDetailIndex(detailIndex - 1)}>Voltar</button>
          <button className="tb-btn primary" disabled={working} onClick={() => onNext()}>{working ? 'Criando...' : detailIndex === questions.length - 1 ? 'Criar agente' : isKbStep ? 'Salvar KB e avancar' : 'Avancar'}</button>
        </div>
      </div>
    </div>
  );
}

function stepLabel(item) {
  const map = {
    goal: 'Objetivo',
    audience: 'Público',
    client_info: 'Coleta',
    tone: 'Tom',
    rules: 'Regras',
    knowledge: 'Conhecimento',
    kb_sources: 'KB',
    handoff: 'Humano',
    success: 'Sucesso',
  };
  return map[item.id] || item.label;
}

function titleFromDescription(text) {
  const first = String(text || 'Novo agente').split(/\s+/).filter(Boolean).slice(0, 4).join(' ');
  return first || 'Novo agente';
}

function toolsFromSuggested(items, memoryVariables = [], hasKbSources = false) {
  const tools = {
    contextual_memory: { enabled: true, variables: memoryVariables, mode: 'persistent' },
    ticket_creation: { enabled: true },
    knowledge_base: { enabled: hasKbSources },
  };
  (items || []).forEach(item => {
    const key = typeof item === 'string' ? item : item.name || item.type || item.tool_type;
    if (!key) return;
    if (key === 'contextual_memory') {
      const config = typeof item === 'object' && item ? (item.config || {}) : {};
      const variables = memoryVariables.length ? memoryVariables : (item.variables || config.variables || []);
      tools.contextual_memory = { enabled: true, variables, mode: config.mode || 'persistent' };
      return;
    }
    tools[key] = { ...(tools[key] || {}), enabled: true };
  });
  if (hasKbSources) tools.knowledge_base = { enabled: true };
  return tools;
}

function normalizeBuilderList(value) {
  const items = Array.isArray(value) ? value : value ? [value] : [];
  return items.map(item => {
    if (item == null) return '';
    if (typeof item === 'string') return item;
    if (typeof item === 'number' || typeof item === 'boolean') return String(item);
    return item.text || item.goal || item.rule || item.description || item.content || item.value || item.name || window.prettyStudioValue?.(item) || String(item);
  }).map(String).map(item => item.trim()).filter(Boolean);
}

function qrSrc(data) {
  const qr = data?.base64 || data?.qrcode || data?.qrCode || data?.code || '';
  return String(qr).startsWith('data:image') ? qr : `data:image/png;base64,${qr}`;
}

function InfoPanel({ title, rows }) {
  return (
    <div className="panel">
      <div className="panel-head"><div className="panel-title">{title}</div></div>
      <div className="stack-list">
        {rows.map((row, i) => <div className="soft-row" key={i}>{row}</div>)}
      </div>
    </div>
  );
}
