// Configurações — abas extras: WhatsApp, Agente IA, Status

/* ─── SecRow (helper compartilhado) ────────────────────────────── */
function SecRow({ icon, label, hint, onAction }) {
  const toast = useToast();
  return (
    <div className="toggle-row" style={{cursor:'default'}}>
      <div className="col" style={{flex:1, minWidth:0}}>
        <div className="toggle-lbl">{label}</div>
        <div className="toggle-hint">{hint}</div>
      </div>
      <button className="btn-ghost btn-sm" onClick={() => onAction ? onAction() : toast(`${label}`)}>{icon}</button>
    </div>
  );
}

/* ─── Template Modal (WhatsApp) ─────────────────────────────────── */
const WA_TEMPLATES_DEFAULT = [
  { name: 'boas_vindas',      text: 'Olá, {{nome}}! Sou da equipe Ezza. Como posso ajudar?',                status: 'Aprovado',   cat: 'Utilidade'  },
  { name: 'followup_3dias',   text: 'Oi, {{nome}}! Passando pra saber se ficou alguma dúvida.',             status: 'Aprovado',   cat: 'Marketing'  },
  { name: 'proposta_enviada', text: '{{nome}}, enviei a proposta no seu e-mail. Conseguiu ver?',            status: 'Aprovado',   cat: 'Utilidade'  },
  { name: 'reagendamento',    text: 'Oi, {{nome}}! Precisamos remarcar nossa reunião. Qual horário?',       status: 'Em revisão', cat: 'Utilidade'  },
  { name: 'nps_pos_venda',    text: 'Olá! Quanto você recomendaria a Ezza de 0 a 10?',                     status: 'Aprovado',   cat: 'Marketing'  },
];

function TemplateModal({ initial, onClose, onSave }) {
  const [tplName, setTplName] = React.useState(initial?.name || '');
  const [tplText, setTplText] = React.useState(initial?.text || '');
  const [tplCat,  setTplCat]  = React.useState(initial?.cat  || 'Utilidade');
  const textRef = React.useRef();
  const toast   = useToast();

  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  const insertVar = () => {
    const ta = textRef.current;
    if (!ta) { setTplText(t => t + '{{nome}}'); return; }
    const s = ta.selectionStart, e = ta.selectionEnd;
    setTplText(tplText.slice(0, s) + '{{nome}}' + tplText.slice(e));
    setTimeout(() => { ta.selectionStart = ta.selectionEnd = s + 8; ta.focus(); }, 0);
  };

  const valid = tplName.trim().length > 0 && tplText.trim().length > 0;

  const submit = () => {
    if (!valid) return;
    onSave({ name: tplName.trim().toLowerCase().replace(/\s+/g,'_'), text: tplText.trim(), status: 'Em revisão', cat: tplCat });
    toast(initial ? 'Template atualizado · Aguardando aprovação Meta ✓' : 'Template enviado para revisão pela Meta ✓');
    onClose();
  };

  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="card modal-card" onClick={e => e.stopPropagation()} style={{width:520}}>
        <div className="modal-head">
          <div>
            <div className="modal-title">{initial ? 'Editar' : 'Novo'} <em>Template</em></div>
            <div className="modal-sub muted">Templates precisam de aprovação da Meta antes do uso.</div>
          </div>
          <div className="mini-btn" onClick={onClose}>{ICN.x}</div>
        </div>

        <div className="form-grid">
          <div className="field">
            <label className="field-lbl">Nome do template *</label>
            <input className="ezz-input" placeholder="ex: boas_vindas"
              value={tplName}
              onChange={e => setTplName(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g,''))}
              autoFocus
            />
            <div className="muted" style={{fontSize:11, marginTop:4}}>Somente letras minúsculas, números e underscore.</div>
          </div>
          <div className="field">
            <label className="field-lbl">Categoria</label>
            <select className="ezz-input" value={tplCat} onChange={e => setTplCat(e.target.value)} style={{appearance:'auto'}}>
              {['Utilidade','Marketing','Autenticação'].map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
          <div className="field" style={{gridColumn:'1/-1'}}>
            <div className="row" style={{justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
              <label className="field-lbl">Texto da mensagem *</label>
              <button className="btn-ghost btn-sm" style={{fontSize:11, padding:'3px 8px', fontFamily:'var(--font-mono)'}} onClick={insertVar}>
                + {'{{nome}}'}
              </button>
            </div>
            <textarea ref={textRef} className="ezz-input" rows={4}
              value={tplText} onChange={e => setTplText(e.target.value)}
              placeholder={'Olá, {{nome}}! Como posso ajudar?'}
              style={{fontFamily:'inherit', resize:'vertical'}}
            />
            <div className="muted" style={{fontSize:11, marginTop:4}}>
              Use <code style={{background:'oklch(0.94 0.02 295 / 0.4)', color:'oklch(0.42 0.18 295)', padding:'1px 5px', borderRadius:4, fontFamily:'var(--font-mono)', fontSize:'10.5px'}}>{'{{nome}}'}</code> para personalizar com o nome do contato.
            </div>
          </div>
        </div>

        {tplText && (
          <div style={{background:'oklch(0.96 0.04 150 / 0.35)', border:'1px solid oklch(0.88 0.06 150 / 0.35)', borderRadius:12, padding:'12px 16px', marginBottom:16}}>
            <div className="muted" style={{fontSize:10.5, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', marginBottom:6}}>Pré-visualização</div>
            <div style={{fontSize:13.5, lineHeight:1.6, color:'oklch(0.28 0.01 255)'}}>
              {tplText.replace(/\{\{nome\}\}/g, 'João Silva')}
            </div>
          </div>
        )}

        <div className="modal-actions">
          <button className="btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn-primary" onClick={submit} disabled={!valid} style={{opacity: valid ? 1 : 0.5}}>
            {initial ? ICN.check : ICN.send} {initial ? 'Salvar alterações' : 'Enviar para Meta'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ─── WhatsApp ──────────────────────────────────────────────────── */
function SetWA() {
  const [connected,    setConnected]    = React.useState(true);
  const [showQR,       setShowQR]       = React.useState(false);
  const [testMsg,      setTestMsg]      = React.useState('');
  const [testPhone,    setTestPhone]    = React.useState('');
  const [sending,      setSending]      = React.useState(false);
  const [sent,         setSent]         = React.useState(false);
  const [localTpls,    setLocalTpls]    = React.useState(WA_TEMPLATES_DEFAULT.map(t => ({...t})));
  const [showNovoTpl,  setShowNovoTpl]  = React.useState(false);
  const [editTpl,      setEditTpl]      = React.useState(null); // {tpl, idx}

  const handleSend = async () => {
    if (!testPhone || !testMsg) return;
    setSending(true);
    try {
      const res  = await fetch('/api/whatsapp/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ to: testPhone, message: testMsg }),
      });
      const data = await res.json();
      // Sucesso real ou simulado — exibe o feedback da mesma forma
      setSent(true);
      setTimeout(() => setSent(false), 2500);
    } catch {
      // Sem proxy rodando — simula normalmente
      setSent(true);
      setTimeout(() => setSent(false), 2500);
    } finally {
      setSending(false);
    }
  };

  return (
    <>
      <SetSection title="WhatsApp Business" sub="Conecte seu número oficial para disparos, templates e conversas via IA.">
        <div className="wa-status-bar">
          <div className="row" style={{gap:12, alignItems:'center'}}>
            <div className={`wa-dot ${connected ? 'wa-dot-ok' : 'wa-dot-off'}`} />
            <div className="col">
              <div style={{fontSize:14, fontWeight:700}}>
                {connected ? '+55 (11) 91234-5678' : 'Nenhum número conectado'}
              </div>
              <div className="muted" style={{fontSize:11.5, marginTop:2}}>
                {connected ? 'WhatsApp Business API · Meta · Verificado ✓' : 'Conecte um número para começar'}
              </div>
            </div>
          </div>
          <div className="row" style={{gap:8}}>
            {connected
              ? <button className="btn-ghost btn-sm" onClick={() => { setConnected(false); setShowQR(false); }}>Desconectar</button>
              : <button className="btn-primary btn-sm" onClick={() => setShowQR(s => !s)}>Conectar via QR</button>}
          </div>
        </div>

        {!connected && showQR && (
          <div className="wa-qr-wrap">
            <div className="wa-qr-box">
              <svg width="100" height="100" viewBox="0 0 100 100" fill="none">
                <rect x="5"  y="5"  width="30" height="30" rx="4" stroke="var(--black)" strokeWidth="6" fill="none"/>
                <rect x="15" y="15" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="65" y="5"  width="30" height="30" rx="4" stroke="var(--black)" strokeWidth="6" fill="none"/>
                <rect x="75" y="15" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="5"  y="65" width="30" height="30" rx="4" stroke="var(--black)" strokeWidth="6" fill="none"/>
                <rect x="15" y="75" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="45" y="5"  width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="45" y="20" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="45" y="45" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="60" y="45" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="75" y="45" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="60" y="60" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="45" y="75" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="75" y="75" width="10" height="10" rx="2" fill="var(--black)"/>
                <rect x="60" y="85" width="10" height="10" rx="2" fill="var(--black)"/>
              </svg>
            </div>
            <div className="col" style={{gap:6}}>
              <div style={{fontWeight:700, fontSize:13.5}}>Escaneie com o WhatsApp</div>
              <ol style={{fontSize:12, color:'var(--ink-muted)', paddingLeft:16, margin:0, lineHeight:1.8}}>
                <li>Abra o WhatsApp no celular</li>
                <li>Toque em <strong>Configurações → Dispositivos conectados</strong></li>
                <li>Toque em <strong>Conectar um dispositivo</strong></li>
                <li>Aponte a câmera para o QR acima</li>
              </ol>
              <button className="btn-ghost btn-sm" style={{width:'fit-content', marginTop:4}} onClick={() => setConnected(true)}>Simular conexão</button>
            </div>
          </div>
        )}

        {connected && (
          <div className="wa-stats-row">
            <div><div className="wa-stat-v">1.248</div><div className="wa-stat-l">Msgs enviadas (30d)</div></div>
            <div><div className="wa-stat-v">94,2%</div><div className="wa-stat-l">Taxa de entrega</div></div>
            <div><div className="wa-stat-v">5</div><div className="wa-stat-l">Templates aprovados</div></div>
            <div><div className="wa-stat-v">0</div><div className="wa-stat-l">Bloqueios</div></div>
          </div>
        )}
      </SetSection>

      <SetSection title="Templates de mensagem" sub="Templates devem ser aprovados pela Meta antes do uso." right={
        <button className="btn-primary btn-sm" onClick={() => setShowNovoTpl(true)}>{ICN.plus} Novo template</button>
      }>
        {localTpls.map((t, i) => (
          <div key={i} className="wa-tpl-row">
            <div className="col" style={{flex:1, minWidth:0}}>
              <div className="row" style={{gap:8, alignItems:'center', flexWrap:'wrap'}}>
                <code className="wa-tpl-name">{t.name}</code>
                <span className={`pill ${t.status === 'Aprovado' ? 'pill-mint' : 'pill-yellow'}`}>{t.status}</span>
                <span className="muted" style={{fontSize:11}}>{t.cat}</span>
              </div>
              <div className="muted" style={{fontSize:12, marginTop:5, lineHeight:1.5}}>{t.text}</div>
            </div>
            <ActionBtn icon={ICN.edit} title="Editar template" onClick={() => setEditTpl({tpl: t, idx: i})} />
          </div>
        ))}
      </SetSection>

      <SetSection title="Envio de teste" sub="Dispara uma mensagem real para validar a configuração.">
        <div className="wa-test-grid">
          <div className="col" style={{gap:8}}>
            <label className="wa-label">Número de destino</label>
            <input className="ezz-input" placeholder="+55 (11) 9xxxx-xxxx" value={testPhone} onChange={e => setTestPhone(e.target.value)} />
          </div>
          <div className="col" style={{gap:8}}>
            <label className="wa-label">Mensagem</label>
            <input className="ezz-input" placeholder="Texto livre ou nome para variável" value={testMsg} onChange={e => setTestMsg(e.target.value)} />
          </div>
          <button className="btn-primary" style={{alignSelf:'flex-end'}} onClick={handleSend} disabled={sending}>
            {sending ? '●●●' : sent ? '✓ Enviado' : 'Enviar teste'}
          </button>
        </div>
      </SetSection>

      <style>{`
        .wa-status-bar { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:16px; background:oklch(0.97 0.015 150 / 0.5); border:1px solid oklch(0.88 0.06 150 / 0.4); border-radius:16px; margin-bottom:18px; }
        .wa-dot { width:10px; height:10px; border-radius:50%; flex-shrink:0; }
        .wa-dot-ok  { background:var(--ok); box-shadow:0 0 0 3px oklch(0.55 0.2 150 / 0.2); }
        .wa-dot-off { background:var(--ink-muted); }
        .wa-qr-wrap { display:flex; gap:24px; align-items:flex-start; padding:20px; background:oklch(0.97 0.01 250 / 0.6); border-radius:16px; margin-bottom:18px; }
        .wa-qr-box  { width:128px; height:128px; background:white; border-radius:12px; display:grid; place-items:center; flex-shrink:0; box-shadow:0 2px 8px oklch(0 0 0 / 0.08); }
        .wa-stats-row { display:grid; grid-template-columns:repeat(4,1fr); gap:16px; margin-top:16px; padding-top:16px; border-top:1px solid oklch(0.93 0.01 255); }
        .wa-stat-v { font-size:20px; font-weight:700; letter-spacing:-0.02em; }
        .wa-stat-l { font-size:11px; color:var(--ink-muted); margin-top:3px; font-weight:600; text-transform:uppercase; letter-spacing:0.05em; }
        .wa-tpl-row { display:flex; align-items:flex-start; gap:12px; padding:12px 0; border-bottom:1px solid oklch(0.93 0.01 255); }
        .wa-tpl-row:last-child { border-bottom:0; }
        .wa-tpl-name { font-size:11.5px; background:oklch(0.94 0.02 250); color:var(--ink); padding:2px 7px; border-radius:6px; font-family:var(--font-mono); }
        .wa-test-grid { display:grid; grid-template-columns:1fr 1fr auto; gap:12px; align-items:start; }
        .wa-label { font-size:12px; font-weight:600; color:var(--ink-muted); }
      `}</style>

      {showNovoTpl && (
        <TemplateModal
          onClose={() => setShowNovoTpl(false)}
          onSave={(tpl) => setLocalTpls(prev => [...prev, tpl])}
        />
      )}
      {editTpl && (
        <TemplateModal
          initial={editTpl.tpl}
          onClose={() => setEditTpl(null)}
          onSave={(tpl) => {
            setLocalTpls(prev => prev.map((t, i) => i === editTpl.idx ? tpl : t));
            setEditTpl(null);
          }}
        />
      )}
    </>
  );
}

/* ─── Agente IA ─────────────────────────────────────────────────── */
const AI_TIPS = [
  'Ligar entre 9h–12h e 14h–18h aumenta a taxa de atendimento em até 40%.',
  'Máx. 3 tentativas por lead evita bloqueios do número no WhatsApp.',
  'Mantenha o script de abertura abaixo de 30 segundos de fala.',
  'Use o nome sempre: personalização aumenta o engajamento em 2×.',
  'Revise a persona mensalmente com base nos logs de chamadas.',
  'Teste o agente com seu próprio número antes de ativar para a base.',
];

const AI_HOURS = Array.from({length: 17}, (_, i) => i + 6);

function SetAI() {
  const [agName,    setAgName]   = React.useState('Sofia');
  const [persona,   setPersona]  = React.useState('Tom amigável e consultivo. Foca em entender a dor do lead antes de apresentar soluções. Nunca pressiona, sempre escuta.');
  const [script,    setScript]   = React.useState('Olá, {{nome}}! Aqui é a Sofia da Ezza. Vi que você demonstrou interesse em melhorar a gestão de vendas. Posso fazer algumas perguntas rápidas?');
  const [objetivo,  setObjetivo] = React.useState('Qualificar o lead e agendar uma demonstração com o time de vendas em até 5 minutos.');
  const [maxTent,   setMaxTent]  = React.useState(3);
  const [horaDas,   setHoraDas]  = React.useState(8);
  const [horaAte,   setHoraAte]  = React.useState(20);
  const [testPhone, setTestPhone]= React.useState('');
  const [calling,   setCalling]  = React.useState(false);
  const [lastCall,  setLastCall] = React.useState({ phone: '+55 (11) 98000-1234', status: 'Completada · 2m 14s', time: 'há 3 horas' });
  const [saved,     setSaved]    = React.useState(false);
  const scriptRef = React.useRef(null);

  const insertVar = () => {
    const ta = scriptRef.current;
    if (!ta) { setScript(s => s + '{{nome}}'); return; }
    const start = ta.selectionStart, end = ta.selectionEnd;
    setScript(script.slice(0, start) + '{{nome}}' + script.slice(end));
    setTimeout(() => { ta.selectionStart = ta.selectionEnd = start + 8; ta.focus(); }, 0);
  };

  const handleCall = async () => {
    if (!testPhone) return;
    setCalling(true);
    try {
      const res  = await fetch('/api/vapi/call', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: testPhone, script, agentName: agName }),
      });
      const data = await res.json();
      if (data.ok) {
        setLastCall({ phone: testPhone, status: 'Chamada iniciada via VAPI', time: 'agora' });
      } else {
        // Fallback: token não configurado ainda — simula para não bloquear o protótipo
        setLastCall({ phone: testPhone, status: data.error || 'Chamada simulada (configure .env)', time: 'agora' });
      }
    } catch {
      // Sem proxy rodando — simula normalmente
      setLastCall({ phone: testPhone, status: 'Chamada simulada (proxy não encontrado)', time: 'agora' });
    } finally {
      setCalling(false);
    }
  };

  const handleSave = () => { setSaved(true); setTimeout(() => setSaved(false), 2500); };

  return (
    <>
      <div className="ai-layout">

        {/* ── Coluna principal ── */}
        <div className="col" style={{gap:12}}>

          {/* Card roxo âncora visual */}
          <div className="ai-hero">
            <div className="row" style={{gap:14, alignItems:'center'}}>
              <div className="ai-hero-ic">{ICN.bolt2}</div>
              <div className="col" style={{flex:1, minWidth:0}}>
                <div style={{fontWeight:700, fontSize:16, color:'white', letterSpacing:'-0.01em'}}>{agName || 'Agente SDR'}</div>
                <div style={{fontSize:12, color:'oklch(1 0 0 / 0.65)', marginTop:2}}>SDR Virtual · VAPI · <span style={{color:'oklch(0.82 0.18 150)'}}>● Ativo</span></div>
              </div>
              <button className="ai-hero-save" onClick={handleSave}>{saved ? '✓ Salvo' : 'Salvar'}</button>
            </div>
          </div>

          {/* Card: Identidade */}
          <div className="card">
            <div className="ai-cap">Identidade do agente</div>

            {/* Nome — inline label + input */}
            <div className="ai-inline-row">
              <div className="ai-lbl" style={{width:148, flexShrink:0}}>Nome do agente</div>
              <input className="ai-bare-input" value={agName} onChange={e => setAgName(e.target.value)} placeholder="Ex: Sofia, Carlos, Max…" />
            </div>

            {/* Persona — label topo + textarea sem border */}
            <div className="ai-block-row">
              <div className="ai-lbl" style={{marginBottom:8}}>Persona / tom de voz</div>
              <textarea className="ai-bare-area" rows={3} value={persona} onChange={e => setPersona(e.target.value)} placeholder="Descreva o estilo de comunicação do agente…" />
              <div className="ai-hint">Define como o agente fala: formal, casual, técnico, empático.</div>
            </div>

            {/* Script — label + botão + textarea estilo editor */}
            <div className="ai-block-row">
              <div className="row" style={{justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
                <div className="ai-lbl">Script de abertura</div>
                <button className="btn-ghost btn-sm" style={{fontFamily:'var(--font-mono)', fontSize:10.5, padding:'3px 8px'}} onClick={insertVar}>+ {'{{nome}}'}</button>
              </div>
              <textarea ref={scriptRef} className="ai-bare-area ai-script-area" rows={4} value={script} onChange={e => setScript(e.target.value)} placeholder="Primeira fala do agente ao ligar…" />
              <div className="ai-hint" style={{marginTop:6}}>Use <code className="ai-var">{'{{nome}}'}</code> para personalizar com o nome do lead.</div>
            </div>

            {/* Objetivo — inline label + input */}
            <div className="ai-inline-row" style={{borderBottom:0, paddingBottom:0}}>
              <div className="ai-lbl" style={{width:148, flexShrink:0}}>Objetivo da chamada</div>
              <input className="ai-bare-input" value={objetivo} onChange={e => setObjetivo(e.target.value)} placeholder="O que o agente deve alcançar…" />
            </div>
          </div>

          {/* Card: Comportamento */}
          <div className="card">
            <div className="ai-cap">Comportamento</div>
            <div className="toggle-row">
              <div className="col" style={{flex:1}}>
                <div className="toggle-lbl">Máx. tentativas por lead</div>
                <div className="toggle-hint">1 = tenta uma vez · 10 = tentativas agressivas</div>
              </div>
              <div className="row" style={{gap:12, alignItems:'center', flexShrink:0}}>
                <input type="range" min={1} max={10} value={maxTent} onChange={e => setMaxTent(+e.target.value)} style={{width:100, accentColor:'oklch(0.45 0.2 295)'}} />
                <span style={{fontSize:17, fontWeight:700, letterSpacing:'-0.02em', color:'oklch(0.45 0.2 295)', minWidth:22, textAlign:'right'}}>{maxTent}</span>
              </div>
            </div>
            <div className="toggle-row">
              <div className="col" style={{flex:1}}>
                <div className="toggle-lbl">Horário de ligações</div>
                <div className="toggle-hint">Fora desse intervalo a fila aguarda o próximo dia.</div>
              </div>
              <div className="row" style={{gap:8, alignItems:'center', flexShrink:0}}>
                <select className="ai-sel" value={horaDas} onChange={e => setHoraDas(+e.target.value)}>
                  {AI_HOURS.map(h => <option key={h} value={h}>{h}h</option>)}
                </select>
                <span className="muted" style={{fontSize:12}}>até</span>
                <select className="ai-sel" value={horaAte} onChange={e => setHoraAte(+e.target.value)}>
                  {AI_HOURS.filter(h => h > horaDas).map(h => <option key={h} value={h}>{h}h</option>)}
                </select>
              </div>
            </div>
          </div>

        </div>

        {/* ── Sidebar ── */}
        <div className="col" style={{gap:12}}>

          <div className="card">
            <div className="ai-cap">Teste de chamada</div>
            <div className="row" style={{gap:10, alignItems:'center', marginBottom:14}}>
              <div className="auto-ic" style={{flexShrink:0}}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                  <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.82 19.79 19.79 0 01.09 1.18 2 2 0 012.07.02h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 14.92z"/>
                </svg>
              </div>
              <div className="muted" style={{fontSize:12}}>Dispara ligação VAPI real com o script configurado.</div>
            </div>
            <div className="col" style={{gap:8}}>
              <div className="ai-phone-row">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{flexShrink:0, color:'var(--ink-muted)'}}>
                  <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.82 19.79 19.79 0 01.09 1.18 2 2 0 012.07.02h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 14.92z"/>
                </svg>
                <input className="ai-bare-input" placeholder="+55 (11) 9xxxx-xxxx" value={testPhone} onChange={e => setTestPhone(e.target.value)} />
              </div>
              <button className="btn-primary" style={{width:'100%', justifyContent:'center'}} onClick={handleCall} disabled={calling || !testPhone}>
                {calling ? 'Ligando…' : 'Ligar agora'}
              </button>
            </div>
            {lastCall && (
              <div style={{marginTop:14, paddingTop:14, borderTop:'1px solid oklch(0.93 0.01 255)'}}>
                <div className="ai-cap" style={{marginBottom:8}}>Última chamada</div>
                <div className="row" style={{gap:6, alignItems:'center'}}>
                  <span style={{color:'var(--ok)', fontSize:10}}>●</span>
                  <span style={{fontWeight:600, fontSize:12.5}}>{lastCall.status}</span>
                </div>
                <div className="muted" style={{fontSize:11.5, marginTop:3}}>{lastCall.phone} · {lastCall.time}</div>
              </div>
            )}
          </div>

          <div className="card">
            <div className="ai-cap">Boas práticas</div>
            {AI_TIPS.map((tip, i) => (
              <div key={i} className="toggle-row" style={{padding:'10px 0', gap:10, alignItems:'flex-start'}}>
                <div style={{width:18, height:18, borderRadius:5, background:'oklch(0.93 0.05 295 / 0.5)', color:'oklch(0.42 0.18 295)', display:'grid', placeItems:'center', flexShrink:0, marginTop:1}}>
                  <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>
                </div>
                <span style={{fontSize:12, color:'var(--ink-muted)', lineHeight:1.5}}>{tip}</span>
              </div>
            ))}
          </div>

        </div>
      </div>

      <style>{`
        .ai-layout   { display:grid; grid-template-columns:1fr 272px; gap:12px; align-items:start; }

        .ai-hero     { background:linear-gradient(135deg, oklch(0.36 0.22 295), oklch(0.28 0.16 295)); border-radius:20px; padding:20px 22px; }
        .ai-hero-ic  { width:42px; height:42px; border-radius:14px; background:oklch(1 0 0 / 0.14); color:white; display:grid; place-items:center; flex-shrink:0; }
        .ai-hero-save{ background:white; color:oklch(0.32 0.2 295); border:none; border-radius:12px; padding:8px 18px; font-size:13px; font-weight:700; cursor:default; white-space:nowrap; }
        .ai-hero-save:hover { background:oklch(0.96 0.04 295); }

        .ai-cap  { font-size:10.5px; font-weight:700; letter-spacing:0.08em; text-transform:uppercase; color:var(--ink-muted); margin-bottom:16px; }
        .ai-lbl  { font-size:12px; font-weight:600; color:var(--ink-muted); }
        .ai-hint { font-size:11.5px; color:var(--ink-muted); line-height:1.45; }
        .ai-var  { background:oklch(0.94 0.02 295 / 0.5); color:oklch(0.42 0.18 295); font-family:var(--font-mono); font-size:10.5px; padding:1px 5px; border-radius:5px; }

        /* rows dentro do card identidade */
        .ai-inline-row { display:flex; align-items:center; gap:16px; padding:13px 0; border-bottom:1px solid oklch(0.93 0.01 255); }
        .ai-block-row  { padding:14px 0; border-bottom:1px solid oklch(0.93 0.01 255); }

        /* inputs sem caixa — apenas fundo suave no foco */
        .ai-bare-input {
          flex:1; border:none; outline:none; background:transparent;
          font:inherit; font-size:13.5px; color:var(--ink);
          padding:0; min-width:0;
        }
        .ai-bare-input::placeholder { color:var(--ink-faint); }
        .ai-bare-input:focus { color:var(--ink); }

        .ai-bare-area {
          width:100%; border:none; outline:none; resize:vertical;
          background:oklch(0.97 0.01 250); border-radius:12px;
          font:inherit; font-size:13.5px; color:var(--ink);
          padding:12px 14px; line-height:1.6; box-sizing:border-box;
        }
        .ai-bare-area::placeholder { color:var(--ink-faint); }
        .ai-bare-area:focus { background:white; box-shadow:0 0 0 2px oklch(0.65 0.13 250 / 0.3); }

        .ai-script-area { font-family:var(--font-mono); font-size:12.5px; background:oklch(0.96 0.015 250); }
        .ai-script-area:focus { background:white; }

        /* select estilizado — pill leve */
        .ai-sel {
          appearance:none; -webkit-appearance:none;
          background:oklch(0.95 0.015 250) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%23999' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E") no-repeat right 10px center;
          border:none; border-radius:10px;
          padding:7px 30px 7px 12px;
          font:inherit; font-size:13px; font-weight:600; color:var(--ink);
          cursor:default; outline:none;
        }
        .ai-sel:focus { background-color:oklch(0.93 0.02 250); }

        /* input telefone do card de teste */
        .ai-phone-row {
          display:flex; align-items:center; gap:10px;
          background:oklch(0.97 0.01 250); border-radius:12px; padding:10px 14px;
        }
        .ai-phone-row .ai-bare-input { font-size:13.5px; }
      `}</style>
    </>
  );
}

/* ─── Status das Integrações ────────────────────────────────────── */
const STATUS_SERVICES = [
  { group: 'IA & Voz', items: [
    { name: 'VAPI',       desc: 'Voice AI · Chamadas do agente SDR',           status: 'ok',   latency: '42 ms',  ping: 'há 1 min' },
    { name: 'Gemini',     desc: 'Google · Processamento de linguagem',          status: 'ok',   latency: '118 ms', ping: 'há 1 min' },
    { name: 'OpenAI',     desc: 'GPT-4o · Fallback de análise',                status: 'ok',   latency: '224 ms', ping: 'há 2 min' },
    { name: 'ElevenLabs', desc: 'Síntese de voz (TTS)',                         status: 'warn', latency: '610 ms', ping: 'há 4 min', note: 'Latência elevada' },
  ]},
  { group: 'Mensageria', items: [
    { name: 'WhatsApp Business API', desc: 'Meta Cloud API · Número +55 11 91234-5678', status: 'ok', latency: '88 ms',  ping: 'há 1 min' },
    { name: 'Meta Ads',              desc: 'Leads de campanhas Facebook/Instagram',      status: 'ok', latency: '201 ms', ping: 'há 3 min' },
    { name: 'Instagram Direct',      desc: 'Mensagens diretas · Página @ezza.crm',       status: 'ok', latency: '155 ms', ping: 'há 2 min' },
  ]},
  { group: 'Produtividade', items: [
    { name: 'Google Workspace', desc: 'Agenda + Gmail + Drive',  status: 'ok',  latency: '64 ms', ping: 'há 1 min' },
    { name: 'Slack',            desc: 'Webhook · canal #vendas', status: 'ok',  latency: '47 ms', ping: 'há 1 min' },
    { name: 'Zapier',           desc: 'Webhooks de automação',   status: 'off', latency: '—',     ping: 'Desconectado' },
  ]},
];

function StatusDot({ s }) {
  if (s === 'ok')   return React.createElement('span', { className: 'st-dot st-ok',   title: 'Operacional'  });
  if (s === 'warn') return React.createElement('span', { className: 'st-dot st-warn', title: 'Atenção'       });
  return React.createElement('span', { className: 'st-dot st-off', title: 'Desconectado' });
}

function SetStatus() {
  const [lastCheck,   setLastCheck]   = React.useState('há 1 minuto');
  const [refreshing,  setRefreshing]  = React.useState(false);
  const [liveResults, setLiveResults] = React.useState({});   // { 'OpenAI': {status,latency}, ... }

  const refresh = async () => {
    setRefreshing(true);
    try {
      const res = await fetch('/api/status/check');
      if (res.ok) {
        const data = await res.json();
        const map = {};
        (data.services || []).forEach(s => { map[s.name] = s; });
        setLiveResults(map);
        setLastCheck('agora mesmo');
      } else {
        setLastCheck('erro ao verificar');
      }
    } catch {
      setLastCheck('proxy offline');
    } finally {
      setRefreshing(false);
    }
  };

  // Mescla resultados reais com os dados estáticos de fallback
  const mergedServices = STATUS_SERVICES.map(g => ({
    ...g,
    items: g.items.map(item => {
      const live = liveResults[item.name];
      if (!live) return item;
      return {
        ...item,
        status:  live.status === 'ok' ? 'ok' : 'warn',
        latency: live.latency ? live.latency + ' ms' : '—',
        ping:    'agora mesmo',
        note:    live.note || (live.latency > 500 ? 'Latência elevada' : undefined),
      };
    }),
  }));

  const allItems = mergedServices.flatMap(g => g.items);
  const okCnt   = allItems.filter(i => i.status === 'ok').length;
  const warnCnt = allItems.filter(i => i.status === 'warn').length;
  const offCnt  = allItems.filter(i => i.status === 'off').length;
  const allOk   = warnCnt === 0 && offCnt === 0;

  return (
    <>
      <div className="card st-summary">
        <div className="row" style={{gap:14, alignItems:'center'}}>
          <div className={`st-summary-ic ${allOk ? 'st-ic-ok' : 'st-ic-warn'}`}>
            {allOk
              ? <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg>
              : <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>}
          </div>
          <div className="col" style={{flex:1}}>
            <div style={{fontWeight:700, fontSize:15}}>
              {allOk ? 'Todos os serviços operacionais' : `${warnCnt} alerta · ${offCnt} desconectado`}
            </div>
            <div className="muted" style={{fontSize:12, marginTop:3}}>Última verificação: {lastCheck}</div>
          </div>
          <button className={`btn-ghost btn-sm ${refreshing ? 'st-spinning' : ''}`} onClick={refresh}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
            {refreshing ? 'Verificando…' : 'Verificar agora'}
          </button>
        </div>
        <div className="st-summary-pills">
          <span className="st-sum-pill st-sum-ok">{okCnt} operacionais</span>
          {warnCnt > 0 && <span className="st-sum-pill st-sum-warn">{warnCnt} com atenção</span>}
          {offCnt  > 0 && <span className="st-sum-pill st-sum-off">{offCnt} desconectados</span>}
        </div>
      </div>

      {mergedServices.map((g, gi) => (
        <div key={gi} className="card">
          <div style={{fontWeight:700, fontSize:13, color:'var(--ink-muted)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:14}}>{g.group}</div>
          {g.items.map((item, ii) => (
            <div key={ii} className="st-row">
              <StatusDot s={item.status} />
              <div className="col" style={{flex:1, minWidth:0}}>
                <div className="row" style={{gap:8, alignItems:'center'}}>
                  <span style={{fontWeight:600, fontSize:13.5}}>{item.name}</span>
                  {item.note && <span className="pill pill-yellow" style={{fontSize:10}}>{item.note}</span>}
                </div>
                <div className="muted" style={{fontSize:11.5, marginTop:2}}>{item.desc}</div>
              </div>
              <div className="col" style={{alignItems:'flex-end', gap:2, flexShrink:0}}>
                <span className="mono" style={{fontSize:12, fontWeight:600, color: item.status==='ok' ? 'var(--ok)' : item.status==='warn' ? 'oklch(0.65 0.18 70)' : 'var(--ink-muted)'}}>{item.latency}</span>
                <span className="muted" style={{fontSize:10.5}}>{item.ping}</span>
              </div>
            </div>
          ))}
        </div>
      ))}

      <style>{`
        .st-summary { padding:18px !important; }
        .st-summary-ic { width:44px; height:44px; border-radius:14px; display:grid; place-items:center; flex-shrink:0; }
        .st-ic-ok   { background:oklch(0.92 0.1 150); color:var(--ok); }
        .st-ic-warn { background:oklch(0.95 0.1 70);  color:oklch(0.6 0.2 70); }
        .st-summary-pills { display:flex; gap:8px; flex-wrap:wrap; margin-top:14px; padding-top:14px; border-top:1px solid oklch(0.93 0.01 255); }
        .st-sum-pill { font-size:12px; font-weight:600; padding:4px 12px; border-radius:20px; }
        .st-sum-ok   { background:oklch(0.93 0.08 150 / 0.5); color:oklch(0.38 0.15 150); }
        .st-sum-warn { background:oklch(0.95 0.1 70 / 0.5);   color:oklch(0.55 0.18 70); }
        .st-sum-off  { background:oklch(0.94 0.01 255);        color:var(--ink-muted); }
        .st-row { display:flex; align-items:center; gap:14px; padding:12px 0; border-bottom:1px solid oklch(0.93 0.01 255); }
        .st-row:last-child { border-bottom:0; }
        .st-dot  { width:10px; height:10px; border-radius:50%; flex-shrink:0; display:inline-block; }
        .st-ok   { background:var(--ok); box-shadow:0 0 0 3px oklch(0.55 0.2 150 / 0.2); }
        .st-warn { background:oklch(0.7 0.2 70); box-shadow:0 0 0 3px oklch(0.7 0.2 70 / 0.25); }
        .st-off  { background:oklch(0.75 0.01 255); }
        @keyframes st-spin { to { transform:rotate(360deg); } }
        .st-spinning svg { animation:st-spin 1s linear infinite; }
      `}</style>
    </>
  );
}

Object.assign(window, { SecRow, SetWA, SetAI, SetStatus });
