const { useState, useEffect, useCallback, useRef } = React;

// ============================================================
// CONFIG & HELPERS
// ============================================================
const API = '';
const CORES_CATEGORIA = {
  marketplace_suspensao: '#e74c3c',
  marketplace_retencao: '#e67e22',
  marca_inpi: '#9b59b6',
  plano_saude: '#2ecc71',
  consumidor_geral: '#3498db',
  trabalhista: '#f39c12',
  outro: '#95a5a6'
};
const CAMPO_CONTEXTUAL = {
  marketplace_suspensao: { key: 'motivo_suspensao', label: 'Motivo da Suspensão' },
  marketplace_retencao: { key: 'motivo_retencao', label: 'Motivo da Retenção' },
  marca_inpi: { key: 'motivo_oposicao', label: 'Motivo da Oposição' },
  plano_saude: { key: 'motivo_negativa', label: 'Motivo da Negativa' },
  consumidor_geral: { key: 'fato_gerador', label: 'Fato Gerador' },
  trabalhista: { key: 'fato_gerador', label: 'Fato Gerador' },
  outro: { key: 'fato_gerador', label: 'Fato Gerador' }
};

function getToken() { return localStorage.getItem('gerador_token'); }
function setToken(t) { localStorage.setItem('gerador_token', t); }
function clearToken() { localStorage.removeItem('gerador_token'); }

async function apiFetch(path, opts = {}) {
  const headers = { 'Content-Type': 'application/json', ...opts.headers };
  const token = getToken();
  if (token) headers['Authorization'] = `Bearer ${token}`;
  const res = await fetch(API + path, { ...opts, headers });
  if (res.status === 401) { clearToken(); window.location.reload(); }
  return res;
}

// ============================================================
// STYLES
// ============================================================
const S = {
  app: { minHeight: '100vh', background: '#1a1a2e', color: '#e0e0e0', fontFamily: "'Segoe UI', Tahoma, sans-serif" },
  topBar: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 24px', background: '#16213e', borderBottom: '2px solid #c9a84c' },
  logo: { color: '#c9a84c', fontSize: 20, fontWeight: 700, letterSpacing: 1 },
  tabs: { display: 'flex', gap: 0 },
  tab: (active) => ({ padding: '8px 24px', cursor: 'pointer', background: active ? '#1a1a2e' : 'transparent', color: active ? '#c9a84c' : '#888', borderBottom: active ? '2px solid #c9a84c' : '2px solid transparent', fontWeight: active ? 700 : 400, fontSize: 14, transition: 'all 0.2s' }),
  logoutBtn: { background: 'none', border: '1px solid #555', color: '#aaa', padding: '6px 16px', borderRadius: 4, cursor: 'pointer', fontSize: 13 },
  container: { maxWidth: 1200, margin: '0 auto', padding: '24px' },
  // Login
  loginWrap: { display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: '#1a1a2e' },
  loginBox: { background: '#16213e', padding: 40, borderRadius: 8, width: 380, border: '1px solid #c9a84c33' },
  loginTitle: { color: '#c9a84c', fontSize: 22, fontWeight: 700, marginBottom: 8, textAlign: 'center' },
  loginSub: { color: '#888', fontSize: 13, textAlign: 'center', marginBottom: 24 },
  label: { color: '#c9a84c', fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4, marginTop: 16 },
  input: { width: '100%', padding: '10px 12px', background: '#1a1a2e', border: '1px solid #333', borderRadius: 4, color: '#e0e0e0', fontSize: 14, outline: 'none' },
  textarea: { width: '100%', padding: '10px 12px', background: '#1a1a2e', border: '1px solid #333', borderRadius: 4, color: '#e0e0e0', fontSize: 14, outline: 'none', resize: 'vertical', minHeight: 80, fontFamily: 'inherit' },
  btnPrimary: { width: '100%', padding: '12px', background: '#c9a84c', color: '#1a1a2e', border: 'none', borderRadius: 4, fontSize: 15, fontWeight: 700, cursor: 'pointer', marginTop: 24 },
  btnSecondary: { padding: '8px 16px', background: '#c9a84c', color: '#1a1a2e', border: 'none', borderRadius: 4, fontSize: 13, fontWeight: 600, cursor: 'pointer' },
  btnDanger: { padding: '8px 16px', background: '#e74c3c', color: '#fff', border: 'none', borderRadius: 4, fontSize: 13, fontWeight: 600, cursor: 'pointer' },
  btnOutline: { padding: '8px 16px', background: 'transparent', color: '#c9a84c', border: '1px solid #c9a84c', borderRadius: 4, fontSize: 13, fontWeight: 600, cursor: 'pointer' },
  error: { color: '#e74c3c', fontSize: 13, marginTop: 8, textAlign: 'center' },
  // Templates
  filterBar: { display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20, alignItems: 'center' },
  chip: (active, cor) => ({ padding: '6px 14px', borderRadius: 20, fontSize: 12, fontWeight: 600, cursor: 'pointer', background: active ? (cor || '#c9a84c') : 'transparent', color: active ? '#fff' : '#aaa', border: `1px solid ${active ? (cor || '#c9a84c') : '#444'}`, transition: 'all 0.2s' }),
  grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340, 1fr))', gap: 16 },
  card: { background: '#16213e', borderRadius: 8, padding: 20, border: '1px solid #2a2a4a', cursor: 'pointer', transition: 'border-color 0.2s' },
  cardId: { fontSize: 11, fontFamily: 'monospace', color: '#888', marginBottom: 6 },
  cardNome: { fontSize: 16, fontWeight: 600, color: '#e0e0e0', marginBottom: 8 },
  cardTese: { fontSize: 13, color: '#999', lineHeight: 1.4, marginBottom: 10, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' },
  badge: (cor) => ({ display: 'inline-block', padding: '3px 10px', borderRadius: 12, fontSize: 11, fontWeight: 600, color: '#fff', background: cor || '#555', marginRight: 6 }),
  statusBadge: (status) => ({ display: 'inline-block', padding: '3px 10px', borderRadius: 12, fontSize: 11, fontWeight: 600, color: status === 'completo' ? '#2ecc71' : '#f39c12', border: `1px solid ${status === 'completo' ? '#2ecc71' : '#f39c12'}`, background: 'transparent' }),
  cardFooter: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 },
  // Panel lateral
  overlay: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100 },
  panel: { position: 'fixed', top: 0, right: 0, bottom: 0, width: 560, background: '#16213e', zIndex: 101, overflowY: 'auto', borderLeft: '2px solid #c9a84c', padding: 0 },
  panelHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 24px', borderBottom: '1px solid #2a2a4a', position: 'sticky', top: 0, background: '#16213e', zIndex: 1 },
  panelTitle: { color: '#c9a84c', fontSize: 18, fontWeight: 700 },
  panelBody: { padding: '24px' },
  panelSection: { marginBottom: 24 },
  panelSectionTitle: { color: '#c9a84c', fontSize: 13, fontWeight: 700, textTransform: 'uppercase', marginBottom: 12, letterSpacing: 1 },
  lockedBg: { background: '#1a1a2e', borderRadius: 6, padding: 16, border: '1px solid #c9a84c33', marginBottom: 12 },
  lockedLabel: { color: '#c9a84c88', fontSize: 11, fontWeight: 600, marginBottom: 2 },
  lockedValue: { color: '#e0e0e0', fontSize: 14, lineHeight: 1.5 },
  secaoRow: { display: 'flex', gap: 8, alignItems: 'flex-start', marginBottom: 8 },
  secaoNum: { color: '#c9a84c', fontWeight: 700, fontSize: 14, minWidth: 24, paddingTop: 8 },
  removeBtn: { background: 'none', border: 'none', color: '#e74c3c', fontSize: 18, cursor: 'pointer', padding: '6px' },
  addBtn: { background: 'none', border: '1px dashed #555', color: '#888', padding: '8px 16px', borderRadius: 4, cursor: 'pointer', fontSize: 13, width: '100%', marginTop: 4 },
  tagContainer: { display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 },
  tag: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 10px', background: '#1a1a2e', border: '1px solid #444', borderRadius: 16, fontSize: 12, color: '#e0e0e0' },
  tagRemove: { background: 'none', border: 'none', color: '#e74c3c', fontSize: 14, cursor: 'pointer', padding: 0, lineHeight: 1 },
  searchInput: { padding: '8px 14px', background: '#1a1a2e', border: '1px solid #333', borderRadius: 20, color: '#e0e0e0', fontSize: 13, outline: 'none', width: 220 },
  emptyState: { textAlign: 'center', padding: 60, color: '#666' },
  select: { width: '100%', padding: '10px 12px', background: '#1a1a2e', border: '1px solid #333', borderRadius: 4, color: '#e0e0e0', fontSize: 14, outline: 'none' },
  panelActions: { display: 'flex', gap: 8, padding: '16px 24px', borderTop: '1px solid #2a2a4a', position: 'sticky', bottom: 0, background: '#16213e' },
  confirmOverlay: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.7)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  confirmBox: { background: '#16213e', borderRadius: 8, padding: 32, border: '1px solid #c9a84c', maxWidth: 400, textAlign: 'center' },
};

// ============================================================
// LOGIN
// ============================================================
function LoginScreen({ onLogin }) {
  const [email, setEmail] = useState('');
  const [senha, setSenha] = useState('');
  const [erro, setErro] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleLogin(e) {
    e.preventDefault();
    setErro(''); setLoading(true);
    try {
      const res = await fetch(API + '/api/auth/login', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, senha })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      setToken(data.token);
      onLogin(data.user);
    } catch (err) { setErro(err.message); }
    setLoading(false);
  }

  return (
    <div style={S.loginWrap}>
      <form style={S.loginBox} onSubmit={handleLogin}>
        <div style={S.loginTitle}>GERADOR MA</div>
        <div style={S.loginSub}>Squad de IA para Peticoes</div>
        <label style={S.label}>E-MAIL</label>
        <input style={S.input} type="email" value={email} onChange={e => setEmail(e.target.value)} required autoFocus />
        <label style={S.label}>SENHA</label>
        <input style={S.input} type="password" value={senha} onChange={e => setSenha(e.target.value)} required />
        {erro && <div style={S.error}>{erro}</div>}
        <button style={{ ...S.btnPrimary, opacity: loading ? 0.6 : 1 }} disabled={loading}>
          {loading ? 'Entrando...' : 'ENTRAR'}
        </button>
      </form>
    </div>
  );
}

// ============================================================
// TAG INPUT
// ============================================================
function TagInput({ tags, onChange, placeholder }) {
  const [input, setInput] = useState('');
  function addTag(e) {
    if (e.key === 'Enter' && input.trim()) {
      e.preventDefault();
      if (!tags.includes(input.trim())) onChange([...tags, input.trim()]);
      setInput('');
    }
  }
  function removeTag(t) { onChange(tags.filter(x => x !== t)); }
  return (
    <>
      <div style={S.tagContainer}>
        {tags.map(t => (
          <span key={t} style={S.tag}>{t}<button style={S.tagRemove} onClick={() => removeTag(t)}>x</button></span>
        ))}
      </div>
      <input style={S.input} value={input} onChange={e => setInput(e.target.value)} onKeyDown={addTag} placeholder={placeholder || 'Digite e pressione Enter'} />
    </>
  );
}

// ============================================================
// CONFIRM DIALOG
// ============================================================
function ConfirmDialog({ message, onConfirm, onCancel }) {
  return (
    <div style={S.confirmOverlay}>
      <div style={S.confirmBox}>
        <div style={{ fontSize: 15, marginBottom: 20, lineHeight: 1.5 }}>{message}</div>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          <button style={S.btnDanger} onClick={onConfirm}>Confirmar</button>
          <button style={S.btnOutline} onClick={onCancel}>Cancelar</button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// TEMPLATE PANEL (Create / Edit)
// ============================================================
function TemplatePanel({ template, categorias, onSave, onClose }) {
  const isEdit = !!template?.id;
  const [form, setForm] = useState(() => {
    if (template) return JSON.parse(JSON.stringify(template));
    return {
      id: '', nome: '', categoria: 'marketplace_suspensao',
      classificacao: { tipo_acao: '', tese_central: '', problema_juridico: '' },
      plataformas: [], keywords: [], quando_usar: '',
      secoes_padrao: [{ id: 1, titulo: '', descricao: '' }],
      jurisprudencia_base: []
    };
  });
  const [classLocked, setClassLocked] = useState(isEdit);
  const [confirmUnlock, setConfirmUnlock] = useState(false);
  const [saving, setSaving] = useState(false);
  const [juri, setJuri] = useState((template?.jurisprudencia_base || []).join('\n'));

  const campoCtx = CAMPO_CONTEXTUAL[form.categoria] || CAMPO_CONTEXTUAL.outro;

  function updateForm(path, value) {
    setForm(prev => {
      const next = JSON.parse(JSON.stringify(prev));
      const parts = path.split('.');
      let obj = next;
      for (let i = 0; i < parts.length - 1; i++) obj = obj[parts[i]];
      obj[parts[parts.length - 1]] = value;
      return next;
    });
  }

  function addSecao() {
    setForm(prev => ({
      ...prev,
      secoes_padrao: [...prev.secoes_padrao, { id: prev.secoes_padrao.length + 1, titulo: '', descricao: '' }]
    }));
  }

  function removeSecao(idx) {
    setForm(prev => ({
      ...prev,
      secoes_padrao: prev.secoes_padrao.filter((_, i) => i !== idx).map((s, i) => ({ ...s, id: i + 1 }))
    }));
  }

  function updateSecao(idx, field, value) {
    setForm(prev => {
      const secoes = [...prev.secoes_padrao];
      secoes[idx] = { ...secoes[idx], [field]: value };
      return { ...prev, secoes_padrao: secoes };
    });
  }

  async function handleSave() {
    if (!form.id.trim() || !form.nome.trim()) return alert('ID e Nome sao obrigatorios');
    setSaving(true);
    const body = {
      ...form,
      jurisprudencia_base: juri.split('\n').map(l => l.trim()).filter(Boolean)
    };
    // Limpar campo contextual antigo se categoria mudou
    const ctxKey = campoCtx.key;
    const cleanClass = { ...body.classificacao };
    Object.keys(CAMPO_CONTEXTUAL).forEach(cat => {
      const k = CAMPO_CONTEXTUAL[cat].key;
      if (k !== ctxKey && k !== 'tipo_acao' && k !== 'tese_central' && k !== 'problema_juridico') {
        delete cleanClass[k];
      }
    });
    body.classificacao = cleanClass;

    try {
      await onSave(body, isEdit);
      onClose();
    } catch (err) {
      alert(err.message);
    }
    setSaving(false);
  }

  return (
    <>
      <div style={S.overlay} onClick={onClose} />
      <div style={S.panel}>
        <div style={S.panelHeader}>
          <span style={S.panelTitle}>{isEdit ? 'Editar Template' : 'Novo Template'}</span>
          <button style={{ ...S.logoutBtn, fontSize: 18, border: 'none', padding: '4px 8px' }} onClick={onClose}>X</button>
        </div>

        <div style={S.panelBody}>
          {/* IDENTIFICACAO */}
          <div style={S.panelSection}>
            <div style={S.panelSectionTitle}>Identificacao</div>
            <label style={S.label}>ID DO TEMPLATE</label>
            <input style={{ ...S.input, ...(isEdit ? { opacity: 0.5 } : {}) }} value={form.id} onChange={e => updateForm('id', e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, ''))} disabled={isEdit} placeholder="ML_SUSP_001" />
            <label style={S.label}>NOME</label>
            <input style={S.input} value={form.nome} onChange={e => updateForm('nome', e.target.value)} placeholder="Acao de Obrigacao de Fazer — Suspensao ML" />
            <label style={S.label}>CATEGORIA</label>
            <select style={S.select} value={form.categoria} onChange={e => updateForm('categoria', e.target.value)}>
              {categorias.map(c => <option key={c.id} value={c.id}>{c.nome}</option>)}
            </select>
          </div>

          {/* CLASSIFICACAO */}
          <div style={S.panelSection}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <span style={S.panelSectionTitle}>Classificacao (Identidade)</span>
              {isEdit && classLocked && (
                <button style={{ ...S.btnOutline, fontSize: 11, padding: '4px 10px' }} onClick={() => setConfirmUnlock(true)}>Editar classificacao</button>
              )}
            </div>

            {confirmUnlock && (
              <ConfirmDialog
                message="Tem certeza? Isso altera a identidade do template e pode afetar a selecao automatica pelo agente."
                onConfirm={() => { setClassLocked(false); setConfirmUnlock(false); }}
                onCancel={() => setConfirmUnlock(false)}
              />
            )}

            {classLocked ? (
              <div style={S.lockedBg}>
                <div style={{ marginBottom: 12 }}>
                  <div style={S.lockedLabel}>TIPO DE ACAO</div>
                  <div style={S.lockedValue}>{form.classificacao.tipo_acao || '—'}</div>
                </div>
                <div style={{ marginBottom: 12 }}>
                  <div style={S.lockedLabel}>TESE CENTRAL</div>
                  <div style={S.lockedValue}>{form.classificacao.tese_central || '—'}</div>
                </div>
                <div style={{ marginBottom: 12 }}>
                  <div style={S.lockedLabel}>PROBLEMA JURIDICO</div>
                  <div style={S.lockedValue}>{form.classificacao.problema_juridico || '—'}</div>
                </div>
                <div>
                  <div style={S.lockedLabel}>{campoCtx.label.toUpperCase()}</div>
                  <div style={S.lockedValue}>{form.classificacao[campoCtx.key] || '—'}</div>
                </div>
              </div>
            ) : (
              <>
                <label style={S.label}>TIPO DE ACAO</label>
                <input style={S.input} value={form.classificacao.tipo_acao || ''} onChange={e => updateForm('classificacao.tipo_acao', e.target.value)} placeholder="Acao de obrigacao de fazer c/c indenizacao..." />
                <label style={S.label}>TESE CENTRAL</label>
                <textarea style={S.textarea} value={form.classificacao.tese_central || ''} onChange={e => updateForm('classificacao.tese_central', e.target.value)} placeholder="Suspensao abusiva de conta..." />
                <label style={S.label}>PROBLEMA JURIDICO</label>
                <textarea style={S.textarea} value={form.classificacao.problema_juridico || ''} onChange={e => updateForm('classificacao.problema_juridico', e.target.value)} placeholder="Responsabilizacao do vendedor..." />
                <label style={S.label}>{campoCtx.label.toUpperCase()}</label>
                <textarea style={S.textarea} value={form.classificacao[campoCtx.key] || ''} onChange={e => updateForm(`classificacao.${campoCtx.key}`, e.target.value)} placeholder={`Descreva o ${campoCtx.label.toLowerCase()}...`} />
              </>
            )}
          </div>

          {/* CONTEXTO */}
          <div style={S.panelSection}>
            <div style={S.panelSectionTitle}>Contexto</div>
            <label style={S.label}>PLATAFORMAS</label>
            <TagInput tags={form.plataformas || []} onChange={v => updateForm('plataformas', v)} placeholder="Ex: mercado_livre, amazon..." />
            <label style={{ ...S.label, marginTop: 12 }}>KEYWORDS</label>
            <TagInput tags={form.keywords || []} onChange={v => updateForm('keywords', v)} placeholder="Ex: suspensao, conta, ANATEL..." />
            <label style={{ ...S.label, marginTop: 12 }}>QUANDO USAR</label>
            <textarea style={S.textarea} value={form.quando_usar || ''} onChange={e => updateForm('quando_usar', e.target.value)} placeholder="Descreva quando este template deve ser usado..." />
          </div>

          {/* SECOES */}
          <div style={S.panelSection}>
            <div style={S.panelSectionTitle}>Secoes Padrao</div>
            {(form.secoes_padrao || []).map((sec, idx) => (
              <div key={idx} style={S.secaoRow}>
                <span style={S.secaoNum}>{idx + 1}.</span>
                <div style={{ flex: 1 }}>
                  <input style={{ ...S.input, marginBottom: 4 }} value={sec.titulo} onChange={e => updateSecao(idx, 'titulo', e.target.value)} placeholder="DA COMPETENCIA JURISDICIONAL" />
                  <input style={{ ...S.input, fontSize: 12 }} value={sec.descricao} onChange={e => updateSecao(idx, 'descricao', e.target.value)} placeholder="Foro, clausula contratual, art. 63 CPC" />
                </div>
                {form.secoes_padrao.length > 1 && (
                  <button style={S.removeBtn} onClick={() => removeSecao(idx)}>x</button>
                )}
              </div>
            ))}
            <button style={S.addBtn} onClick={addSecao}>+ Adicionar secao</button>
          </div>

          {/* JURISPRUDENCIA */}
          <div style={S.panelSection}>
            <div style={S.panelSectionTitle}>Jurisprudencia Base</div>
            <textarea style={{ ...S.textarea, minHeight: 120 }} value={juri} onChange={e => setJuri(e.target.value)} placeholder="Um acordao por linha:&#10;TJ-SP AC 1043405-90.2024 — suspensao abusiva ML&#10;TJ-SP AC 1039622-xx — retencao desproporcional" />
          </div>
        </div>

        <div style={S.panelActions}>
          <button style={{ ...S.btnPrimary, width: 'auto', flex: 1, marginTop: 0 }} onClick={handleSave} disabled={saving}>
            {saving ? 'Salvando...' : (isEdit ? 'Salvar Alteracoes' : 'Criar Template')}
          </button>
          <button style={{ ...S.btnOutline, marginTop: 0 }} onClick={onClose}>Cancelar</button>
        </div>
      </div>
    </>
  );
}

// ============================================================
// TEMPLATES TAB
// ============================================================
function TemplatesTab() {
  const [templates, setTemplates] = useState([]);
  const [categorias, setCategorias] = useState([]);
  const [filtroCategoria, setFiltroCategoria] = useState(null);
  const [busca, setBusca] = useState('');
  const [panelOpen, setPanelOpen] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState(null);
  const [loading, setLoading] = useState(true);

  const loadTemplates = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (filtroCategoria) params.set('categoria', filtroCategoria);
      if (busca) params.set('busca', busca);
      const res = await apiFetch(`/api/templates?${params}`);
      const data = await res.json();
      setTemplates(data);
    } catch (err) { console.error(err); }
    setLoading(false);
  }, [filtroCategoria, busca]);

  useEffect(() => {
    apiFetch('/api/templates/categorias').then(r => r.json()).then(setCategorias);
  }, []);

  useEffect(() => { loadTemplates(); }, [loadTemplates]);

  function openNew() { setEditingTemplate(null); setPanelOpen(true); }
  function openEdit(t) { setEditingTemplate(t); setPanelOpen(true); }

  async function handleSave(body, isEdit) {
    const url = isEdit ? `/api/templates/${body.id}` : '/api/templates';
    const method = isEdit ? 'PUT' : 'POST';
    const res = await apiFetch(url, { method, body: JSON.stringify(body) });
    if (!res.ok) { const d = await res.json(); throw new Error(d.error); }
    await loadTemplates();
  }

  async function handleDelete(id) {
    await apiFetch(`/api/templates/${id}`, { method: 'DELETE' });
    setConfirmDelete(null);
    await loadTemplates();
  }

  async function handleDuplicate(t) {
    const newId = prompt('ID do novo template (ex: ML_SUSP_003):');
    if (!newId) return;
    const res = await apiFetch(`/api/templates/${t.id}/duplicar`, {
      method: 'POST', body: JSON.stringify({ novo_id: newId.toUpperCase().replace(/[^A-Z0-9_]/g, '') })
    });
    if (!res.ok) { const d = await res.json(); alert(d.error); return; }
    await loadTemplates();
  }

  const catMap = {};
  categorias.forEach(c => { catMap[c.id] = c; });

  return (
    <div style={S.container}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <div>
          <h2 style={{ color: '#c9a84c', fontSize: 22, fontWeight: 700, marginBottom: 4 }}>Templates de Peticoes</h2>
          <span style={{ color: '#888', fontSize: 13 }}>{templates.length} template{templates.length !== 1 ? 's' : ''}</span>
        </div>
        <button style={S.btnSecondary} onClick={openNew}>+ Novo Template</button>
      </div>

      {/* Filters */}
      <div style={S.filterBar}>
        <span style={S.chip(!filtroCategoria, '#c9a84c')} onClick={() => setFiltroCategoria(null)}>Todos</span>
        {categorias.map(c => {
          const count = templates.filter(t => t.categoria === c.id).length;
          return (
            <span key={c.id} style={S.chip(filtroCategoria === c.id, c.cor)} onClick={() => setFiltroCategoria(filtroCategoria === c.id ? null : c.id)}>
              {c.nome} {count > 0 && `(${count})`}
            </span>
          );
        })}
        <div style={{ flex: 1 }} />
        <input style={S.searchInput} placeholder="Buscar por nome, ID, keyword..." value={busca} onChange={e => setBusca(e.target.value)} />
      </div>

      {/* Grid */}
      {loading ? (
        <div style={S.emptyState}>Carregando...</div>
      ) : templates.length === 0 ? (
        <div style={S.emptyState}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>{ busca || filtroCategoria ? '0' : '0'}</div>
          <div>{busca || filtroCategoria ? 'Nenhum template encontrado com esses filtros' : 'Nenhum template cadastrado'}</div>
          {!busca && !filtroCategoria && <button style={{ ...S.btnSecondary, marginTop: 16 }} onClick={openNew}>Criar primeiro template</button>}
        </div>
      ) : (
        <div style={S.grid}>
          {templates.map(t => {
            const cat = catMap[t.categoria];
            return (
              <div key={t.id} style={S.card} onClick={() => openEdit(t)} onMouseOver={e => e.currentTarget.style.borderColor = '#c9a84c'} onMouseOut={e => e.currentTarget.style.borderColor = '#2a2a4a'}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
                  <span style={S.cardId}>{t.id}</span>
                  <span style={S.statusBadge(t.status || 'rascunho')}>{t.status || 'rascunho'}</span>
                </div>
                <div style={S.cardNome}>{t.nome}</div>
                {t.classificacao?.tipo_acao && (
                  <div style={{ fontSize: 12, color: '#c9a84c', marginBottom: 6, fontWeight: 600 }}>{t.classificacao.tipo_acao}</div>
                )}
                <div style={S.cardTese}>{t.classificacao?.tese_central || 'Sem tese definida'}</div>
                <div style={S.cardFooter}>
                  {cat && <span style={S.badge(cat.cor)}>{cat.nome}</span>}
                  <span style={{ fontSize: 11, color: '#666' }}>{(t.secoes_padrao || []).length} secoes</span>
                  <span style={{ fontSize: 11, color: '#666' }}>v{t.versao || 1}</span>
                  <div style={{ flex: 1 }} />
                  <button style={{ ...S.btnOutline, fontSize: 11, padding: '3px 8px' }} onClick={e => { e.stopPropagation(); handleDuplicate(t); }}>Duplicar</button>
                  <button style={{ ...S.removeBtn, fontSize: 14 }} onClick={e => { e.stopPropagation(); setConfirmDelete(t.id); }}>Excluir</button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Panel */}
      {panelOpen && (
        <TemplatePanel
          template={editingTemplate}
          categorias={categorias}
          onSave={handleSave}
          onClose={() => { setPanelOpen(false); setEditingTemplate(null); }}
        />
      )}

      {/* Confirm delete */}
      {confirmDelete && (
        <ConfirmDialog
          message={`Excluir template ${confirmDelete}? Esta acao nao pode ser desfeita.`}
          onConfirm={() => handleDelete(confirmDelete)}
          onCancel={() => setConfirmDelete(null)}
        />
      )}
    </div>
  );
}

// ============================================================
// GERADOR TAB (placeholder)
// ============================================================
function GeradorTab() {
  return (
    <div style={S.container}>
      <div style={S.emptyState}>
        <div style={{ fontSize: 48, marginBottom: 16 }}>SQUAD</div>
        <div style={{ fontSize: 16, color: '#888', marginBottom: 8 }}>Gerador de Peticoes</div>
        <div style={{ fontSize: 13, color: '#666' }}>Em breve — Fase 2 a 4 do roadmap</div>
      </div>
    </div>
  );
}

// ============================================================
// APP
// ============================================================
function App() {
  const [user, setUser] = useState(null);
  const [tab, setTab] = useState('templates');
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) { setChecking(false); return; }
    apiFetch('/api/auth/verify')
      .then(r => r.json())
      .then(d => { if (d.valid) setUser(d.user); })
      .finally(() => setChecking(false));
  }, []);

  if (checking) return <div style={{ ...S.loginWrap, justifyContent: 'center' }}><span style={{ color: '#c9a84c' }}>Carregando...</span></div>;
  if (!user) return <LoginScreen onLogin={setUser} />;

  return (
    <div style={S.app}>
      <div style={S.topBar}>
        <span style={S.logo}>GERADOR MA</span>
        <div style={S.tabs}>
          <span style={S.tab(tab === 'templates')} onClick={() => setTab('templates')}>Templates</span>
          <span style={S.tab(tab === 'gerador')} onClick={() => setTab('gerador')}>Gerador</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ color: '#888', fontSize: 13 }}>{user.nome}</span>
          <button style={S.logoutBtn} onClick={() => { clearToken(); setUser(null); }}>Sair</button>
        </div>
      </div>
      {tab === 'templates' && <TemplatesTab />}
      {tab === 'gerador' && <GeradorTab />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
