// Publicações — Diários judiciais e INPI

// ============================================================
// Constants & helpers
// ============================================================

const TIPO_COMUNICACAO_COLOR = {
  'Intimação':               { bg: 'rgba(234,88,12,.1)',   color: '#EA580C' },
  'Decisão':                 { bg: 'rgba(220,38,38,.1)',   color: '#DC2626' },
  'Despacho':                { bg: 'rgba(202,138,4,.1)',   color: '#CA8A04' },
  'Sentença':                { bg: 'rgba(153,27,27,.1)',   color: '#991B1B' },
  'Acórdão':                 { bg: 'rgba(30,64,175,.1)',   color: '#1E40AF' },
  'Deferimento':             { bg: 'rgba(21,128,61,.1)',   color: '#157F3D' },
  'Indeferimento':           { bg: 'rgba(107,114,128,.1)', color: '#6B7280' },
  'Concessão de registro':   { bg: 'rgba(5,102,65,.1)',    color: '#056641' },
  'Exigência de mérito':     { bg: 'rgba(161,98,7,.1)',    color: '#A16207' },
  'Publicação para oposição':{ bg: 'rgba(109,40,217,.1)', color: '#6D28D9' },
};

const STATUS_COLOR = {
  nova:        '#0D0D6B',
  lida:        '#6B7280',
  sem_vinculo: '#EA580C',
};

const STATUS_LABEL = {
  nova:        'Nova',
  lida:        'Lida',
  sem_vinculo: 'Sem vínculo',
};

const TIPO_LABEL = {
  judicial: 'Judicial',
  inpi:     'INPI',
};

function fmtDate(d) {
  if (!d) return '—';
  const parts = d.split('-');
  if (parts.length !== 3) return d;
  return `${parts[2]}/${parts[1]}/${parts[0]}`;
}

function daysUntil(dateStr) {
  if (!dateStr) return null;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const target = new Date(dateStr);
  target.setHours(0, 0, 0, 0);
  return Math.round((target - today) / 86400000);
}

function PrazoAlert({ dataLimite, prazoDias, prazoNatureza }) {
  if (!dataLimite) return null;
  const days = daysUntil(dataLimite);
  if (days === null) return null;

  let bg, color, icon;
  if (days < 0) {
    bg = 'rgba(220,38,38,.08)'; color = '#DC2626'; icon = 'alertTriangle';
  } else if (days <= 3) {
    bg = 'rgba(234,88,12,.08)'; color = '#EA580C'; icon = 'alertTriangle';
  } else if (days <= 10) {
    bg = 'rgba(202,138,4,.08)'; color = '#CA8A04'; icon = 'clock';
  } else {
    bg = 'rgba(21,128,61,.08)'; color = '#157F3D'; icon = 'clock';
  }

  const label = days < 0
    ? `Prazo vencido há ${Math.abs(days)} dia${Math.abs(days) !== 1 ? 's' : ''}`
    : days === 0
    ? 'Prazo vence hoje'
    : `Prazo em ${days} dia${days !== 1 ? 's' : ''}`;

  const sub = prazoDias
    ? `${prazoDias} dias ${prazoNatureza === 'uteis' ? 'úteis' : 'corridos'} · até ${fmtDate(dataLimite)}`
    : `Até ${fmtDate(dataLimite)}`;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 14px', borderRadius: 8,
      background: bg, border: `1px solid ${color}30`,
    }}>
      <Icon name={icon} size={16} style={{ color, flexShrink: 0 }} />
      <div>
        <div style={{ fontSize: 12.5, fontWeight: 700, color }}>{label}</div>
        <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 1 }}>{sub}</div>
      </div>
    </div>
  );
}

// ============================================================
// Import modal
// ============================================================

const ImportModal = ({ onClose, onImported }) => {
  const [file, setFile] = React.useState(null);
  const [dragging, setDragging] = React.useState(false);
  const [importing, setImporting] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  const fileRef = React.useRef(null);

  const handleFile = (f) => {
    if (!f) return;
    if (!f.name.match(/\.(xlsx|xls)$/i)) {
      setError('Apenas arquivos .xlsx são suportados.');
      return;
    }
    setFile(f);
    setError(null);
    setResult(null);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    const f = e.dataTransfer.files[0];
    handleFile(f);
  };

  const handleImport = async () => {
    if (!file) return;
    setImporting(true);
    setError(null);
    try {
      const data = await window.PACApi.publicacoes.importFile(file);
      setResult(data);
      onImported?.();
    } catch (e) {
      setError(e.message || 'Erro ao importar.');
    } finally {
      setImporting(false);
    }
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 520 }}>
        <div className="modal-head">
          <h3>Importar Publicações</h3>
          <button className="btn ghost sm icon" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body" style={{ display: 'grid', gap: 16 }}>
          {!result && (
            <>
              {/* Drop zone */}
              <div
                onDragOver={e => { e.preventDefault(); setDragging(true); }}
                onDragLeave={() => setDragging(false)}
                onDrop={handleDrop}
                onClick={() => fileRef.current?.click()}
                style={{
                  border: `2px dashed ${dragging ? 'var(--pac-navy)' : '#d1d5db'}`,
                  borderRadius: 10,
                  padding: '32px 24px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  background: dragging ? 'rgba(13,13,107,.04)' : 'transparent',
                  transition: 'all .15s',
                }}
              >
                <Icon name="upload" size={28} style={{ color: 'var(--fg-muted)', marginBottom: 10, display: 'block', margin: '0 auto 10px' }} />
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg)' }}>
                  {file ? file.name : 'Arraste o arquivo .xlsx aqui'}
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>
                  {file
                    ? `${(file.size / 1024).toFixed(0)} KB`
                    : 'ou clique para selecionar'}
                </div>
                <input
                  ref={fileRef}
                  type="file"
                  accept=".xlsx,.xls"
                  style={{ display: 'none' }}
                  onChange={e => handleFile(e.target.files[0])}
                />
              </div>

              {file && (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 14px', borderRadius: 8,
                  background: 'rgba(13,13,107,.05)',
                  border: '1px solid rgba(13,13,107,.12)',
                }}>
                  <Icon name="fileText" size={16} style={{ color: 'var(--pac-navy)' }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600 }}>{file.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>Pronto para importar</div>
                  </div>
                  <button
                    className="btn ghost sm icon"
                    onClick={e => { e.stopPropagation(); setFile(null); }}
                  >
                    <Icon name="x" size={12} />
                  </button>
                </div>
              )}

              {error && (
                <div style={{
                  padding: '10px 14px', borderRadius: 6, fontSize: 12.5,
                  background: 'rgba(220,38,38,.07)', border: '1px solid rgba(220,38,38,.2)',
                  color: '#DC2626',
                }}>
                  {error}
                </div>
              )}
            </>
          )}

          {result && (
            <div style={{ display: 'grid', gap: 12 }}>
              <div style={{
                padding: '14px 16px', borderRadius: 8,
                background: 'rgba(21,128,61,.07)', border: '1px solid rgba(21,128,61,.2)',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <Icon name="check" size={18} style={{ color: '#157F3D' }} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#157F3D' }}>Importação concluída</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>
                    {result.total_registros} publicações processadas
                  </div>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                <div style={{ padding: '12px', borderRadius: 8, background: 'var(--bg-secondary)', textAlign: 'center' }}>
                  <div style={{ fontSize: 22, fontWeight: 700, color: '#157F3D' }}>{result.total_vinculados}</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>Vinculadas</div>
                </div>
                <div style={{ padding: '12px', borderRadius: 8, background: 'var(--bg-secondary)', textAlign: 'center' }}>
                  <div style={{ fontSize: 22, fontWeight: 700, color: '#EA580C' }}>{result.total_nao_identificados}</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>Não identificadas</div>
                </div>
                <div style={{ padding: '12px', borderRadius: 8, background: 'var(--bg-secondary)', textAlign: 'center' }}>
                  <div style={{ fontSize: 22, fontWeight: 700, color: '#6B7280' }}>{result.total_duplicados}</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>Duplicadas ignoradas</div>
                </div>
              </div>
            </div>
          )}
        </div>
        <div className="modal-foot">
          {result ? (
            <button className="btn" onClick={onClose}>Fechar</button>
          ) : (
            <>
              <button className="btn ghost" onClick={onClose}>Cancelar</button>
              <button
                className="btn"
                onClick={handleImport}
                disabled={!file || importing}
                style={{ display: 'flex', alignItems: 'center', gap: 8 }}
              >
                {importing
                  ? <><span className="spinner" style={{ width: 13, height: 13, borderColor: 'rgba(255,255,255,.2)', borderTopColor: '#fff' }} /> Importando…</>
                  : <><Icon name="upload" size={13} /> Confirmar importação</>
                }
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Vincular a caso modal
// ============================================================

const VincularCasoModal = ({ pub, onClose, onVinculado }) => {
  const [mode, setMode] = React.useState('buscar'); // 'buscar' | 'novo'
  const [casos, setCasos] = React.useState([]);
  const [clientes, setClientes] = React.useState([]);
  const [search, setSearch] = React.useState('');
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  // Novo cliente+caso — form
  const isInpi = pub.tipo_publicacao === 'inpi';
  // Limpar nome do titular: remover sufixos como "[BR/SP] Data de dep..." que o INPI inclui
  const cleanTitular = (s) => (s || '').replace(/\s*\[.*/, '').replace(/\s*Data de.*/, '').trim();
  const [novoForm, setNovoForm] = React.useState({
    // cliente
    clienteNome: cleanTitular(pub.titular || pub.nome_pesquisado || ''),
    clienteExistente: '',       // id de cliente existente (opcional)
    // caso
    casoTitulo: isInpi
      ? (pub.tipo_despacho || 'Marca') + (pub.nome_pesquisado ? ` – ${pub.nome_pesquisado}` : '')
      : pub.nome_pesquisado || '',
    casoArea: isInpi ? 'Propriedade Intelectual' : 'Contencioso',
    casoStatus: 'Em análise',
    numerProcesso: pub.numero_processo || '',
  });

  React.useEffect(() => {
    Promise.all([
      window.PACApi.cases.list({}),
      window.PACApi.clients.list({}),
    ]).then(([cs, cl]) => {
      setCasos(cs || []);
      setClientes(cl || []);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const filtered = casos.filter(c => {
    const q = search.toLowerCase();
    return !q ||
      (c.title || '').toLowerCase().includes(q) ||
      (c.number || '').toLowerCase().includes(q) ||
      (c.numero_processo || '').includes(q);
  });

  const handleSelect = async (caso) => {
    setSaving(true);
    setError('');
    try {
      await window.PACApi.publicacoes.update(pub.id, {
        caso_id: caso.id,
        cliente_id: caso.cliente_id || null,
        status: 'lida',
      });
      onVinculado?.();
      onClose();
    } catch (e) {
      setError('Erro ao vincular: ' + e.message);
    } finally {
      setSaving(false);
    }
  };

  const handleCriarNovo = async () => {
    if (!novoForm.casoTitulo.trim()) { setError('Informe o título do caso.'); return; }
    if (!novoForm.clienteNome.trim() && !novoForm.clienteExistente) { setError('Informe o nome do cliente ou selecione um existente.'); return; }
    setSaving(true);
    setError('');
    try {
      let cliente_id = novoForm.clienteExistente || null;

      // Criar cliente novo se não selecionou existente
      if (!cliente_id && novoForm.clienteNome.trim()) {
        const nome = novoForm.clienteNome.trim();
        // short_name: primeiras letras de cada palavra, máx 10 chars
        const short_name = nome
          .split(/\s+/)
          .map(w => w[0])
          .join('')
          .toUpperCase()
          .slice(0, 10) || nome.slice(0, 10).toUpperCase();
        const novoCliente = await window.PACApi.clients.create({
          name: nome,
          short_name,
          tier: 'Padrão',
        });
        cliente_id = novoCliente.id;
      }

      // Criar caso
      const novoCaso = await window.PACApi.cases.create({
        title: novoForm.casoTitulo.trim(),
        area: novoForm.casoArea,
        status: novoForm.casoStatus,
        client_id: cliente_id,
        numero_processo: novoForm.numerProcesso.trim() || undefined,
      });

      // Vincular publicação ao novo caso
      await window.PACApi.publicacoes.update(pub.id, {
        caso_id: novoCaso.id,
        cliente_id,
        status: 'lida',
      });

      onVinculado?.();
      onClose();
    } catch (e) {
      setError('Erro ao criar: ' + e.message);
    } finally {
      setSaving(false);
    }
  };

  const inp = (style = {}) => ({
    width: '100%', boxSizing: 'border-box',
    padding: '9px 12px',
    border: '1.5px solid var(--border)',
    borderRadius: 6,
    fontSize: 13,
    outline: 'none',
    background: '#fff',
    ...style,
  });

  const modalContent = (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(26,10,46,.45)',
        zIndex: 600,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
        animation: 'fade 150ms',
      }}
    >
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 580, zIndex: 601, position: 'relative' }}>
        <div className="modal-head">
          <h3>Vincular publicação a caso</h3>
          <button className="btn ghost sm icon" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', padding: '0 20px' }}>
          {[['buscar', 'Caso existente'], ['novo', 'Criar cliente + caso']].map(([k, lbl]) => (
            <button key={k} onClick={() => { setMode(k); setError(''); }} style={{
              padding: '10px 16px', fontSize: 13, fontWeight: mode === k ? 700 : 400,
              color: mode === k ? 'var(--pac-navy)' : 'var(--fg-muted)',
              borderBottom: mode === k ? '2px solid var(--pac-navy)' : '2px solid transparent',
              background: 'none', border: 'none', borderRadius: 0, cursor: 'pointer',
              marginBottom: -1,
            }}>{lbl}</button>
          ))}
        </div>

        <div className="modal-body" style={{ display: 'grid', gap: 14 }}>
          {/* Info da publicação */}
          <div style={{ fontSize: 12, color: 'var(--fg-muted)', background: 'var(--surface)', borderRadius: 6, padding: '8px 12px' }}>
            Processo: <b style={{ color: 'var(--fg)' }}>{pub.numero_processo}</b>
            {pub.nome_pesquisado ? <> · <b style={{ color: 'var(--fg)' }}>{pub.nome_pesquisado}</b></> : null}
          </div>

          {/* ── MODO: BUSCAR CASO EXISTENTE ── */}
          {mode === 'buscar' && (
            <>
              <div className="crm-list-search" style={{ margin: 0 }}>
                <Icon name="search" size={13} />
                <input
                  placeholder="Buscar caso por título ou número…"
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                  autoFocus
                />
              </div>
              <div style={{ maxHeight: 300, overflowY: 'auto', display: 'grid', gap: 2 }}>
                {loading && <div style={{ padding: 16, color: 'var(--fg-muted)', fontSize: 13 }}>Carregando casos…</div>}
                {!loading && filtered.length === 0 && (
                  <div style={{ padding: 16, color: 'var(--fg-muted)', fontSize: 13, textAlign: 'center' }}>
                    Nenhum caso encontrado.{' '}
                    <button className="btn ghost sm" style={{ fontSize: 12 }} onClick={() => setMode('novo')}>Criar novo →</button>
                  </div>
                )}
                {filtered.map(c => (
                  <div key={c.id} className="list-row" style={{ cursor: saving ? 'not-allowed' : 'pointer', borderRadius: 6, opacity: saving ? 0.5 : 1 }}
                    onClick={() => !saving && handleSelect(c)}>
                    <Icon name="briefcase" size={14} style={{ color: 'var(--pac-navy)', flexShrink: 0 }} />
                    <div className="grow">
                      <div className="ttl">{c.title}</div>
                      <div className="meta">{c.number}{c.numero_processo ? ` · ${c.numero_processo}` : ''}</div>
                    </div>
                    <Icon name="chevronRight" size={14} />
                  </div>
                ))}
              </div>
            </>
          )}

          {/* ── MODO: CRIAR NOVO ── */}
          {mode === 'novo' && (
            <div style={{ display: 'grid', gap: 12 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '.06em' }}>Cliente</div>

              {/* Selecionar cliente existente */}
              <div>
                <label style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'block', marginBottom: 4 }}>Selecionar cliente já cadastrado (opcional)</label>
                <select style={inp()} value={novoForm.clienteExistente}
                  onChange={e => setNovoForm(f => ({ ...f, clienteExistente: e.target.value, clienteNome: e.target.value ? '' : f.clienteNome }))}>
                  <option value="">— Criar cliente novo —</option>
                  {clientes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>

              {/* Nome novo cliente (só aparece se não selecionou existente) */}
              {!novoForm.clienteExistente && (
                <div>
                  <label style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'block', marginBottom: 4 }}>Nome do novo cliente *</label>
                  <input style={inp()} placeholder="Ex: Empresa XYZ Ltda"
                    value={novoForm.clienteNome}
                    onChange={e => setNovoForm(f => ({ ...f, clienteNome: e.target.value }))} />
                </div>
              )}

              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '.06em', marginTop: 4 }}>Caso</div>

              <div>
                <label style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'block', marginBottom: 4 }}>Título do caso *</label>
                <input style={inp()} placeholder="Ex: Ação de cobrança – Empresa XYZ"
                  value={novoForm.casoTitulo}
                  onChange={e => setNovoForm(f => ({ ...f, casoTitulo: e.target.value }))} />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <div>
                  <label style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'block', marginBottom: 4 }}>Área</label>
                  <select style={inp()} value={novoForm.casoArea}
                    onChange={e => setNovoForm(f => ({ ...f, casoArea: e.target.value }))}>
                    {['M&A','Franchising','Societário','Contratos','Venture Capital','Propriedade Intelectual','Contencioso','Tributário','Trabalhista','Outros'].map(a => (
                      <option key={a} value={a}>{a}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'block', marginBottom: 4 }}>Número do processo</label>
                  <input style={inp()} placeholder={pub.numero_processo}
                    value={novoForm.numerProcesso}
                    onChange={e => setNovoForm(f => ({ ...f, numerProcesso: e.target.value }))} />
                </div>
              </div>
            </div>
          )}

          {error && (
            <div style={{ fontSize: 12.5, color: '#C2253E', background: 'rgba(194,37,62,.06)', border: '1px solid rgba(194,37,62,.2)', borderRadius: 5, padding: '8px 12px' }}>
              {error}
            </div>
          )}
        </div>

        <div className="modal-foot">
          <button className="btn ghost" onClick={onClose}>Cancelar</button>
          {mode === 'novo' && (
            <button className="btn" onClick={handleCriarNovo} disabled={saving} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              {saving ? <><span className="spinner" style={{ width: 12, height: 12 }} /> Criando…</> : <><Icon name="plus" size={13} /> Criar e vincular</>}
            </button>
          )}
        </div>
      </div>
    </div>
  );
  return ReactDOM.createPortal(modalContent, document.body);
};

// ============================================================
// Detail drawer
// ============================================================

const PublicacaoDetail = ({ pub, onClose, onUpdated }) => {
  const [anotacao, setAnotacao] = React.useState(pub.anotacao_interna || '');
  const [savingAnotacao, setSavingAnotacao] = React.useState(false);
  const [savingStatus, setSavingStatus] = React.useState(false);
  const [showVincular, setShowVincular] = React.useState(false);
  const [showCriarTarefa, setShowCriarTarefa] = React.useState(false);
  const [tarefaForm, setTarefaForm] = React.useState({ title: '', description: '', priority: 'media', due_date: '' });
  const [tratando, setTratando] = React.useState(false);
  const [tratadoMsg, setTratadoMsg] = React.useState('');

  React.useEffect(() => {
    setAnotacao(pub.anotacao_interna || '');
  }, [pub.id]);

  const handleSaveAnotacao = async () => {
    if (anotacao === (pub.anotacao_interna || '')) return;
    setSavingAnotacao(true);
    try {
      await window.PACApi.publicacoes.update(pub.id, { anotacao_interna: anotacao });
      onUpdated?.();
    } catch (e) {
      alert('Erro ao salvar anotação: ' + e.message);
    } finally {
      setSavingAnotacao(false);
    }
  };

  const handleMarcarLida = async () => {
    if (pub.status === 'lida') return;
    setSavingStatus(true);
    try {
      await window.PACApi.publicacoes.update(pub.id, { status: 'lida' });
      onUpdated?.();
    } catch (e) {
      alert('Erro: ' + e.message);
    } finally {
      setSavingStatus(false);
    }
  };

  const addToTimeline = async (title, body) => {
    if (!pub.caso_id && !pub.casos?.id) return;
    const caseId = pub.caso_id || pub.casos?.id;
    try {
      await window.PACApi.cases.addTimeline(caseId, { type: 'publicacao', title, body });
    } catch (e) {
      console.warn('Erro ao registrar na timeline:', e.message);
    }
  };

  const handleDescartar = async () => {
    if (tratando) return;
    if (!window.confirm('Descartar esta publicação? Ela será marcada como lida e registrada na timeline do caso.')) return;
    setTratando(true);
    try {
      await window.PACApi.publicacoes.update(pub.id, { status: 'lida', anotacao_interna: (anotacao ? anotacao + '\n' : '') + '[Descartada]' });
      await addToTimeline(
        `Publicação descartada — ${pub.numero_processo}`,
        `Processo: ${pub.numero_processo}${pub.tipo_comunicacao ? ' · ' + pub.tipo_comunicacao : ''}. Descartada sem ação necessária.`
      );
      setTratadoMsg('Publicação descartada e registrada na timeline.');
      onUpdated?.();
    } catch (e) {
      alert('Erro ao descartar: ' + e.message);
    } finally {
      setTratando(false);
    }
  };

  const handleSalvarTimeline = async () => {
    if (tratando) return;
    setTratando(true);
    try {
      await window.PACApi.publicacoes.update(pub.id, { status: 'lida' });
      await addToTimeline(
        `Publicação registrada — ${pub.numero_processo}`,
        [
          pub.tipo_comunicacao ? `Tipo: ${pub.tipo_comunicacao}` : null,
          pub.data_publicacao ? `Data: ${fmtDate(pub.data_publicacao)}` : null,
          pub.data_limite_prazo ? `Prazo: ${fmtDate(pub.data_limite_prazo)}` : null,
          anotacao ? `Anotação: ${anotacao}` : null,
        ].filter(Boolean).join(' · ')
      );
      setTratadoMsg('Publicação salva na timeline do caso.');
      onUpdated?.();
    } catch (e) {
      alert('Erro: ' + e.message);
    } finally {
      setTratando(false);
    }
  };

  const handleCriarTarefa = async () => {
    if (!tarefaForm.title.trim()) { alert('Informe o título da tarefa.'); return; }
    if (tratando) return;
    setTratando(true);
    try {
      const caseId = pub.caso_id || pub.casos?.id;
      const task = await window.PACApi.tasks.create({
        title: tarefaForm.title.trim(),
        description: tarefaForm.description || '',
        priority: tarefaForm.priority,
        due_date: tarefaForm.due_date || null,
        case_id: caseId || null,
        kanban_column: 'backlog',
      });
      await window.PACApi.publicacoes.update(pub.id, { status: 'lida' });
      await addToTimeline(
        `Tarefa criada a partir de publicação — ${pub.numero_processo}`,
        `Tarefa: "${task.title}"${tarefaForm.due_date ? ' · Prazo: ' + tarefaForm.due_date : ''}. Originada de publicação ${pub.tipo_comunicacao || pub.tipo_publicacao || ''}.`
      );
      setShowCriarTarefa(false);
      setTarefaForm({ title: '', description: '', priority: 'media', due_date: '' });
      setTratadoMsg(`Tarefa "${task.title}" criada e registrada na timeline.`);
      onUpdated?.();
    } catch (e) {
      alert('Erro ao criar tarefa: ' + e.message);
    } finally {
      setTratando(false);
    }
  };

  const tipoComunicacao = pub.tipo_comunicacao || pub.tipo_despacho || null;
  const tipoCor = tipoComunicacao ? TIPO_COMUNICACAO_COLOR[tipoComunicacao] : null;
  const statusColor = STATUS_COLOR[pub.status] || '#6B7280';

  const casoVinculado = pub.casos;
  const clienteVinculado = pub.clientes;

  const partes = Array.isArray(pub.partes) ? pub.partes : [];
  const advogados = Array.isArray(pub.advogados) ? pub.advogados : [];

  return (
    <>
      {showVincular && (
        <VincularCasoModal
          pub={pub}
          onClose={() => setShowVincular(false)}
          onVinculado={() => { setShowVincular(false); onUpdated?.(); }}
        />
      )}
      <div
        style={{
          position: 'fixed', inset: 0,
          background: 'rgba(26,10,46,.35)',
          zIndex: 299,
          animation: 'fade 180ms',
        }}
        onClick={onClose}
      />
      <div
        style={{
          position: 'fixed', top: 0, right: 0, bottom: 0,
          width: 'min(540px, 100vw)',
          background: 'var(--bg)',
          zIndex: 300,
          display: 'flex', flexDirection: 'column',
          boxShadow: '-4px 0 24px rgba(0,0,0,.12)',
          animation: 'slideIn 200ms ease',
        }}
      >
        {/* Header */}
        <div style={{
          padding: '16px 20px',
          borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'flex-start', gap: 12,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 6 }}>
              <span style={{
                fontSize: 10.5, fontWeight: 700, padding: '2px 7px', borderRadius: 4,
                background: pub.tipo_publicacao === 'inpi' ? 'rgba(109,40,217,.1)' : 'rgba(13,13,107,.1)',
                color: pub.tipo_publicacao === 'inpi' ? '#6D28D9' : 'var(--pac-navy)',
                letterSpacing: '.03em',
              }}>
                {TIPO_LABEL[pub.tipo_publicacao]}
              </span>
              {tipoComunicacao && tipoCor && (
                <span style={{
                  fontSize: 10.5, fontWeight: 700, padding: '2px 7px', borderRadius: 4,
                  background: tipoCor.bg, color: tipoCor.color,
                }}>
                  {tipoComunicacao}
                </span>
              )}
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--fg-muted)' }}>
                <span style={{
                  width: 7, height: 7, borderRadius: '50%',
                  background: statusColor, display: 'inline-block',
                }} />
                {STATUS_LABEL[pub.status]}
              </span>
            </div>
            <div style={{ fontSize: 14, fontWeight: 700, fontFamily: 'monospace', letterSpacing: '.02em' }}>
              {pub.numero_processo}
            </div>
            {pub.data_publicacao && (
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 3 }}>
                Publicado em {fmtDate(pub.data_publicacao)}
              </div>
            )}
          </div>
          <button className="btn ghost sm icon" onClick={onClose}>
            <Icon name="x" size={14} />
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px', display: 'grid', gap: 16 }}>
          {/* Prazo */}
          {pub.data_limite_prazo && (
            <PrazoAlert
              dataLimite={pub.data_limite_prazo}
              prazoDias={pub.prazo_dias}
              prazoNatureza={pub.prazo_natureza}
            />
          )}

          {/* Dados da publicação */}
          <div className="panel">
            <div className="panel-head"><h3>Dados da publicação</h3></div>
            <div className="panel-body">
              <div className="crm-grid">
                {pub.data_publicacao && (
                  <div className="crm-field">
                    <span className="lbl">Data de publicação</span>
                    <span className="val">{fmtDate(pub.data_publicacao)}</span>
                  </div>
                )}
                {pub.data_divulgacao && (
                  <div className="crm-field">
                    <span className="lbl">Data de divulgação</span>
                    <span className="val">{fmtDate(pub.data_divulgacao)}</span>
                  </div>
                )}
                {pub.diario && (
                  <div className="crm-field" style={{ gridColumn: '1/-1' }}>
                    <span className="lbl">Diário</span>
                    <span className="val">{pub.diario}</span>
                  </div>
                )}
                {pub.vara && (
                  <div className="crm-field">
                    <span className="lbl">Vara</span>
                    <span className="val">{pub.vara}</span>
                  </div>
                )}
                {pub.comarca && (
                  <div className="crm-field">
                    <span className="lbl">Comarca</span>
                    <span className="val">{pub.comarca}</span>
                  </div>
                )}
                {pub.orgao && (
                  <div className="crm-field">
                    <span className="lbl">Órgão</span>
                    <span className="val">{pub.orgao}</span>
                  </div>
                )}
                {pub.estado && (
                  <div className="crm-field">
                    <span className="lbl">Estado</span>
                    <span className="val">{pub.estado}</span>
                  </div>
                )}
                {pub.responsavel && (
                  <div className="crm-field">
                    <span className="lbl">Responsável</span>
                    <span className="val">{pub.responsavel}</span>
                  </div>
                )}
                {pub.nome_pesquisado && (
                  <div className="crm-field">
                    <span className="lbl">Nome pesquisado</span>
                    <span className="val">{pub.nome_pesquisado}</span>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* INPI fields */}
          {pub.tipo_publicacao === 'inpi' && (pub.titular || pub.especificacao || pub.classe_ncl) && (
            <div className="panel">
              <div className="panel-head"><h3>Dados INPI</h3></div>
              <div className="panel-body">
                <div className="crm-grid">
                  {pub.titular && (
                    <div className="crm-field" style={{ gridColumn: '1/-1' }}>
                      <span className="lbl">Titular</span>
                      <span className="val">{pub.titular}</span>
                    </div>
                  )}
                  {pub.especificacao && (
                    <div className="crm-field" style={{ gridColumn: '1/-1' }}>
                      <span className="lbl">Especificação</span>
                      <span className="val">{pub.especificacao}</span>
                    </div>
                  )}
                  {pub.classe_ncl && (
                    <div className="crm-field">
                      <span className="lbl">Classe NCL</span>
                      <span className="val">{pub.classe_ncl}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Partes & Advogados */}
          {pub.tipo_publicacao === 'judicial' && (partes.length > 0 || advogados.length > 0) && (
            <div className="panel">
              <div className="panel-head"><h3>Partes e advogados</h3></div>
              <div className="panel-body" style={{ display: 'grid', gap: 12 }}>
                {partes.length > 0 && (
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 6 }}>Partes</div>
                    <div style={{ display: 'grid', gap: 4 }}>
                      {partes.map((p, i) => (
                        <div key={i} style={{ fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Icon name="user" size={12} style={{ color: 'var(--fg-muted)' }} />
                          {p}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {advogados.length > 0 && (
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 6 }}>Advogados</div>
                    <div style={{ display: 'grid', gap: 4 }}>
                      {advogados.map((a, i) => (
                        <div key={i} style={{ fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Icon name="briefcase" size={12} style={{ color: 'var(--fg-muted)' }} />
                          {a}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {pub.classe_processual && (
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 4 }}>Classe processual</div>
                    <div style={{ fontSize: 12.5 }}>{pub.classe_processual}</div>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Caso vinculado */}
          <div className="panel">
            <div className="panel-head">
              <h3>Caso vinculado</h3>
              {!casoVinculado && (
                <div className="right">
                  <button className="btn ghost sm" onClick={() => setShowVincular(true)}>
                    <Icon name="link" size={11} /> Vincular
                  </button>
                </div>
              )}
            </div>
            <div className="panel-body">
              {casoVinculado ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Icon name="briefcase" size={14} style={{ color: 'var(--pac-navy)' }} />
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{casoVinculado.title}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>
                      {casoVinculado.number}
                      {clienteVinculado ? ` · ${clienteVinculado.name}` : ''}
                    </div>
                  </div>
                </div>
              ) : (
                <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>
                  Nenhum caso vinculado.{' '}
                  <button
                    onClick={() => setShowVincular(true)}
                    style={{ background: 'none', border: 'none', color: 'var(--pac-navy)', fontWeight: 600, cursor: 'pointer', fontSize: 12.5, padding: 0 }}
                  >
                    Vincular agora →
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Inteiro teor */}
          {pub.link_inteiro_teor && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="externalLink" size={13} style={{ color: 'var(--pac-navy)' }} />
              <a
                href={pub.link_inteiro_teor}
                target="_blank"
                rel="noopener noreferrer"
                style={{ fontSize: 12.5, color: 'var(--pac-navy)', fontWeight: 600 }}
              >
                Ver inteiro teor
              </a>
            </div>
          )}

          {/* Conteúdo completo */}
          {pub.conteudo_completo && (
            <div className="panel">
              <div className="panel-head"><h3>Conteúdo completo</h3></div>
              <div style={{
                padding: '12px 16px',
                fontSize: 12, lineHeight: 1.6,
                whiteSpace: 'pre-wrap', fontFamily: 'monospace',
                color: 'var(--fg)',
                maxHeight: 240, overflowY: 'auto',
                background: 'var(--bg-secondary)',
                borderRadius: '0 0 8px 8px',
              }}>
                {pub.conteudo_completo}
              </div>
            </div>
          )}

          {/* Tratamento da publicação */}
          <div className="panel">
            <div className="panel-head"><h3>Tratamento</h3></div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {tratadoMsg ? (
                <div style={{
                  padding: '10px 12px', borderRadius: 7, fontSize: 12.5,
                  background: 'rgba(21,128,61,.08)', border: '1px solid rgba(21,128,61,.25)',
                  color: '#157F3D', display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <Icon name="check" size={14} /> {tratadoMsg}
                </div>
              ) : (
                <>
                  {!(pub.caso_id || pub.casos) && (
                    <div style={{ fontSize: 12, color: '#EA580C', background: 'rgba(234,88,12,.07)', border: '1px solid rgba(234,88,12,.2)', borderRadius: 6, padding: '8px 10px' }}>
                      Vincule esta publicação a um caso antes de tratar.
                    </div>
                  )}
                  <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
                    <button
                      onClick={handleDescartar}
                      disabled={tratando || !(pub.caso_id || pub.casos)}
                      style={{
                        padding: '6px 13px', borderRadius: 7, fontSize: 12.5, fontWeight: 600,
                        border: '1.5px solid #DC2626', background: 'transparent', color: '#DC2626',
                        cursor: (tratando || !(pub.caso_id || pub.casos)) ? 'not-allowed' : 'pointer',
                        opacity: (pub.caso_id || pub.casos) ? 1 : 0.4,
                        display: 'flex', alignItems: 'center', gap: 5,
                        transition: 'background .15s, color .15s',
                      }}
                      onMouseEnter={e => { if (!tratando && (pub.caso_id || pub.casos)) { e.currentTarget.style.background = '#DC2626'; e.currentTarget.style.color = '#fff'; }}}
                      onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = '#DC2626'; }}
                    >
                      <Icon name="trash" size={13} /> Descartar
                    </button>
                    <button
                      onClick={handleSalvarTimeline}
                      disabled={tratando || !(pub.caso_id || pub.casos)}
                      style={{
                        padding: '6px 13px', borderRadius: 7, fontSize: 12.5, fontWeight: 600,
                        border: '1.5px solid var(--pac-navy)', background: 'transparent', color: 'var(--pac-navy)',
                        cursor: (tratando || !(pub.caso_id || pub.casos)) ? 'not-allowed' : 'pointer',
                        opacity: (pub.caso_id || pub.casos) ? 1 : 0.4,
                        display: 'flex', alignItems: 'center', gap: 5,
                        transition: 'background .15s, color .15s',
                      }}
                      onMouseEnter={e => { if (!tratando && (pub.caso_id || pub.casos)) { e.currentTarget.style.background = 'var(--pac-navy)'; e.currentTarget.style.color = '#fff'; }}}
                      onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--pac-navy)'; }}
                    >
                      <Icon name="git" size={13} /> Salvar na timeline
                    </button>
                    <button
                      onClick={() => setShowCriarTarefa(v => !v)}
                      disabled={tratando || !(pub.caso_id || pub.casos)}
                      style={{
                        padding: '6px 13px', borderRadius: 7, fontSize: 12.5, fontWeight: 600,
                        border: 'none', background: 'var(--pac-navy)', color: '#fff',
                        cursor: (tratando || !(pub.caso_id || pub.casos)) ? 'not-allowed' : 'pointer',
                        opacity: (pub.caso_id || pub.casos) ? 1 : 0.4,
                        display: 'flex', alignItems: 'center', gap: 5,
                      }}
                    >
                      <Icon name="plus" size={13} /> Criar tarefa
                    </button>
                  </div>

                  {showCriarTarefa && (
                    <div style={{
                      background: 'var(--bg-secondary)', borderRadius: 8, padding: '14px',
                      border: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 10,
                    }}>
                      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--pac-navy)', textTransform: 'uppercase', letterSpacing: '.05em' }}>Nova tarefa</div>
                      <div className="field-group" style={{ margin: 0 }}>
                        <label style={{ fontSize: 11.5 }}>Título *</label>
                        <input
                          value={tarefaForm.title}
                          onChange={e => setTarefaForm(f => ({...f, title: e.target.value}))}
                          placeholder={`Tratar ${pub.tipo_comunicacao || 'publicação'} — ${pub.numero_processo}`}
                          autoFocus
                        />
                      </div>
                      <div className="field-group" style={{ margin: 0 }}>
                        <label style={{ fontSize: 11.5 }}>Descrição</label>
                        <textarea
                          value={tarefaForm.description}
                          onChange={e => setTarefaForm(f => ({...f, description: e.target.value}))}
                          rows={2}
                          placeholder="Detalhes da tarefa…"
                          style={{ width: '100%', boxSizing: 'border-box', resize: 'vertical', fontSize: 12.5, border: '1.5px solid var(--border)', borderRadius: 6, padding: '7px 10px', fontFamily: 'inherit', background: '#fff' }}
                        />
                      </div>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                        <div className="field-group" style={{ margin: 0 }}>
                          <label style={{ fontSize: 11.5 }}>Prioridade</label>
                          <select value={tarefaForm.priority} onChange={e => setTarefaForm(f => ({...f, priority: e.target.value}))}>
                            <option value="urgente">Urgente</option>
                            <option value="alta">Alta</option>
                            <option value="media">Média</option>
                            <option value="baixa">Baixa</option>
                          </select>
                        </div>
                        <div className="field-group" style={{ margin: 0 }}>
                          <label style={{ fontSize: 11.5 }}>Prazo</label>
                          <input
                            type="date"
                            value={tarefaForm.due_date}
                            onChange={e => setTarefaForm(f => ({...f, due_date: e.target.value}))}
                            defaultValue={pub.data_limite_prazo || ''}
                          />
                        </div>
                      </div>
                      <div style={{ display: 'flex', gap: 7, justifyContent: 'flex-end' }}>
                        <button className="btn ghost sm" onClick={() => setShowCriarTarefa(false)}>Cancelar</button>
                        <button className="btn sm" onClick={handleCriarTarefa} disabled={tratando} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          {tratando ? <><span className="spinner" style={{ width: 11, height: 11 }} /> Criando…</> : <><Icon name="check" size={12} /> Criar tarefa</>}
                        </button>
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>
          </div>

          {/* Anotação interna */}
          <div className="panel">
            <div className="panel-head">
              <h3>Anotação interna</h3>
              {savingAnotacao && (
                <div className="right">
                  <span className="spinner" style={{ width: 12, height: 12 }} />
                </div>
              )}
            </div>
            <div className="panel-body">
              <textarea
                value={anotacao}
                onChange={e => setAnotacao(e.target.value)}
                onBlur={handleSaveAnotacao}
                placeholder="Adicione uma anotação interna…"
                rows={3}
                style={{
                  width: '100%', boxSizing: 'border-box',
                  resize: 'vertical', fontSize: 12.5, lineHeight: 1.5,
                  border: '1px solid var(--border)', borderRadius: 6,
                  padding: '8px 10px', fontFamily: 'inherit',
                  background: 'var(--bg)', color: 'var(--fg)',
                }}
              />
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding: '12px 20px',
          borderTop: '1px solid var(--border)',
          display: 'flex', gap: 8, justifyContent: 'flex-end',
        }}>
          {pub.status !== 'lida' && (
            <button
              className="btn ghost sm"
              onClick={handleMarcarLida}
              disabled={savingStatus}
              style={{ display: 'flex', alignItems: 'center', gap: 6 }}
            >
              {savingStatus
                ? <span className="spinner" style={{ width: 12, height: 12 }} />
                : <Icon name="check" size={13} />
              }
              Marcar como lida
            </button>
          )}
          {pub.status === 'sem_vinculo' && (
            <button className="btn sm" onClick={() => setShowVincular(true)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="link" size={13} /> Vincular a caso
            </button>
          )}
        </div>
      </div>
    </>
  );
};

// ============================================================
// Main component
// ============================================================

const Publicacoes = () => {
  const [publicacoes, setPublicacoes] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [stats, setStats] = React.useState({ nova: 0, sem_vinculo: 0 });
  const [filterStatus, setFilterStatus] = React.useState('');
  const [filterTipo, setFilterTipo] = React.useState('');
  const [search, setSearch] = React.useState('');
  const [total, setTotal] = React.useState(0);
  const [showImport, setShowImport] = React.useState(false);
  const [selected, setSelected] = React.useState(null);

  const loadData = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = {};
      if (filterStatus) params.status = filterStatus;
      if (filterTipo) params.tipo = filterTipo;
      if (search) params.search = search;

      const [result, statsData] = await Promise.all([
        window.PACApi.publicacoes.list(params),
        window.PACApi.publicacoes.stats(),
      ]);

      setPublicacoes(result.publicacoes || []);
      setTotal(result.total || 0);
      setStats(statsData);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, [filterStatus, filterTipo, search]);

  React.useEffect(() => {
    loadData();
  }, [loadData]);

  // Debounced search
  const [searchInput, setSearchInput] = React.useState('');
  React.useEffect(() => {
    const t = setTimeout(() => setSearch(searchInput), 350);
    return () => clearTimeout(t);
  }, [searchInput]);

  // If selected pub changes, keep it in sync with list
  const selectedPub = selected
    ? (publicacoes.find(p => p.id === selected.id) || selected)
    : null;

  const handleUpdated = () => {
    loadData();
    if (selected) {
      // refresh the selected item too
      setSelected(prev => publicacoes.find(p => p.id === prev?.id) || prev);
    }
  };

  // After import, reload
  const handleImported = () => {
    loadData();
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      {/* Page header */}
      <div style={{
        padding: '20px 24px 0',
        borderBottom: '1px solid var(--border)',
        background: 'var(--bg)',
        flexShrink: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800 }}>Publicações</h1>
            <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 3 }}>
              {stats.nova > 0 && (
                <span style={{ color: 'var(--pac-navy)', fontWeight: 600 }}>
                  {stats.nova} nova{stats.nova !== 1 ? 's' : ''}
                </span>
              )}
              {stats.nova > 0 && stats.sem_vinculo > 0 && ' · '}
              {stats.sem_vinculo > 0 && (
                <span style={{ color: '#EA580C', fontWeight: 600 }}>
                  {stats.sem_vinculo} sem vínculo
                </span>
              )}
              {stats.nova === 0 && stats.sem_vinculo === 0 && 'Tudo em dia'}
            </div>
          </div>
          <button
            className="btn"
            onClick={() => setShowImport(true)}
            style={{ display: 'flex', alignItems: 'center', gap: 7 }}
          >
            <Icon name="upload" size={13} />
            Importar Publicações
          </button>
        </div>

        {/* Filter bar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingBottom: 12, flexWrap: 'wrap' }}>
          {/* Search */}
          <div className="crm-list-search" style={{ margin: 0, minWidth: 220, flex: '1 1 220px', maxWidth: 340 }}>
            <Icon name="search" size={13} />
            <input
              placeholder="Buscar processo, conteúdo…"
              value={searchInput}
              onChange={e => setSearchInput(e.target.value)}
            />
          </div>

          <div style={{ display: 'flex', gap: 4 }}>
            {[
              ['', 'Todas'],
              ['nova', 'Novas'],
              ['lida', 'Lidas'],
              ['sem_vinculo', 'Sem vínculo'],
            ].map(([val, lbl]) => (
              <button
                key={val}
                className={`btn ghost sm ${filterStatus === val ? '' : ''}`}
                onClick={() => setFilterStatus(val)}
                style={{
                  fontWeight: filterStatus === val ? 700 : 400,
                  background: filterStatus === val ? 'var(--pac-navy)' : undefined,
                  color: filterStatus === val ? '#fff' : undefined,
                  borderColor: filterStatus === val ? 'var(--pac-navy)' : undefined,
                }}
              >
                {lbl}
                {val === 'nova' && stats.nova > 0 && (
                  <span style={{
                    marginLeft: 4, fontSize: 10, fontWeight: 700,
                    background: filterStatus === 'nova' ? 'rgba(255,255,255,.25)' : 'var(--pac-navy)',
                    color: filterStatus === 'nova' ? '#fff' : '#fff',
                    borderRadius: 10, padding: '0 5px',
                  }}>{stats.nova}</span>
                )}
              </button>
            ))}
          </div>

          <div style={{ display: 'flex', gap: 4 }}>
            {[
              ['', 'Todos'],
              ['judicial', 'Judicial'],
              ['inpi', 'INPI'],
            ].map(([val, lbl]) => (
              <button
                key={val}
                className="btn ghost sm"
                onClick={() => setFilterTipo(val)}
                style={{
                  fontWeight: filterTipo === val ? 700 : 400,
                  background: filterTipo === val ? '#6D28D9' : undefined,
                  color: filterTipo === val ? '#fff' : undefined,
                  borderColor: filterTipo === val ? '#6D28D9' : undefined,
                }}
              >
                {lbl}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Table */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 24px 24px' }}>
        {loading && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: 48, color: 'var(--fg-muted)' }}>
            <div className="spinner" /> Carregando publicações…
          </div>
        )}

        {error && (
          <div style={{ padding: '24px 0', color: '#DC2626', fontSize: 13 }}>Erro: {error}</div>
        )}

        {!loading && !error && publicacoes.length === 0 && (
          <div style={{ textAlign: 'center', padding: 64, color: 'var(--fg-muted)' }}>
            <Icon name="fileText" size={40} style={{ opacity: .25, marginBottom: 14, display: 'block', margin: '0 auto 14px' }} />
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Nenhuma publicação encontrada</div>
            <div style={{ fontSize: 12.5, marginBottom: 20 }}>
              {search || filterStatus || filterTipo
                ? 'Tente remover os filtros.'
                : 'Importe uma planilha .xlsx para começar.'}
            </div>
            {!search && !filterStatus && !filterTipo && (
              <button className="btn" onClick={() => setShowImport(true)}>
                <Icon name="upload" size={13} /> Importar Publicações
              </button>
            )}
          </div>
        )}

        {!loading && !error && publicacoes.length > 0 && (
          <div style={{ paddingTop: 12 }}>
            {/* Table header */}
            <div style={{
              display: 'grid',
              gridTemplateColumns: '100px 180px 80px 140px 140px 130px 120px 80px',
              gap: '0 12px',
              padding: '6px 12px',
              fontSize: 11, fontWeight: 700,
              color: 'var(--fg-muted)',
              textTransform: 'uppercase',
              letterSpacing: '.05em',
              borderBottom: '1px solid var(--border)',
              marginBottom: 4,
            }}>
              <div>Data</div>
              <div>Processo</div>
              <div>Tipo</div>
              <div>Comunicação</div>
              <div>Cliente</div>
              <div>Caso</div>
              <div>Responsável</div>
              <div>Status</div>
            </div>

            {/* Rows */}
            {publicacoes.map(pub => {
              const tipoComunicacao = pub.tipo_comunicacao || pub.tipo_despacho || null;
              const tipoCor = tipoComunicacao ? TIPO_COMUNICACAO_COLOR[tipoComunicacao] : null;
              const isSelected = selectedPub?.id === pub.id;

              return (
                <div
                  key={pub.id}
                  onClick={() => setSelected(pub)}
                  style={{
                    display: 'grid',
                    gridTemplateColumns: '100px 180px 80px 140px 140px 130px 120px 80px',
                    gap: '0 12px',
                    padding: '9px 12px',
                    borderRadius: 7,
                    cursor: 'pointer',
                    background: isSelected ? 'rgba(13,13,107,.05)' : 'transparent',
                    borderLeft: isSelected ? '3px solid var(--pac-navy)' : '3px solid transparent',
                    marginBottom: 1,
                    alignItems: 'center',
                    transition: 'background .1s',
                  }}
                  onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = 'var(--bg-secondary)'; }}
                  onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = 'transparent'; }}
                >
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>
                    {fmtDate(pub.data_publicacao)}
                  </div>
                  <div style={{
                    fontSize: 12, fontFamily: 'monospace',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    fontWeight: pub.status === 'nova' ? 700 : 400,
                  }}>
                    {pub.numero_processo}
                  </div>
                  <div>
                    <span style={{
                      fontSize: 10.5, fontWeight: 700, padding: '2px 6px', borderRadius: 4,
                      background: pub.tipo_publicacao === 'inpi' ? 'rgba(109,40,217,.1)' : 'rgba(13,13,107,.08)',
                      color: pub.tipo_publicacao === 'inpi' ? '#6D28D9' : 'var(--pac-navy)',
                    }}>
                      {TIPO_LABEL[pub.tipo_publicacao]}
                    </span>
                  </div>
                  <div>
                    {tipoComunicacao && tipoCor ? (
                      <span style={{
                        fontSize: 10.5, fontWeight: 700, padding: '2px 6px', borderRadius: 4,
                        background: tipoCor.bg, color: tipoCor.color,
                        whiteSpace: 'nowrap',
                      }}>
                        {tipoComunicacao}
                      </span>
                    ) : <span style={{ color: 'var(--fg-muted)', fontSize: 12 }}>—</span>}
                  </div>
                  <div style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {pub.clientes?.name || <span style={{ color: 'var(--fg-muted)' }}>—</span>}
                  </div>
                  <div style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {pub.casos?.title || <span style={{ color: 'var(--fg-muted)' }}>—</span>}
                  </div>
                  <div style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--fg-muted)' }}>
                    {pub.responsavel || '—'}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                    <span style={{
                      width: 7, height: 7, borderRadius: '50%',
                      background: STATUS_COLOR[pub.status] || '#6B7280',
                      display: 'inline-block', flexShrink: 0,
                    }} />
                    <span style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>
                      {STATUS_LABEL[pub.status]}
                    </span>
                  </div>
                </div>
              );
            })}

            {total > publicacoes.length && (
              <div style={{ padding: '16px 12px', fontSize: 12.5, color: 'var(--fg-muted)', textAlign: 'center' }}>
                Exibindo {publicacoes.length} de {total} publicações.
              </div>
            )}
          </div>
        )}
      </div>

      {/* Modals */}
      {showImport && (
        <ImportModal
          onClose={() => setShowImport(false)}
          onImported={handleImported}
        />
      )}

      {/* Detail drawer */}
      {selectedPub && (
        <PublicacaoDetail
          pub={selectedPub}
          onClose={() => setSelected(null)}
          onUpdated={() => {
            loadData();
          }}
        />
      )}
    </div>
  );
};

window.Publicacoes = Publicacoes;
