// Consulta Processual — DataJud (CNJ). Ferramenta interna.
// ⚠️ A API pública do DataJud NÃO retorna partes nem valor da causa.
// Suporta busca por NÚMERO CNJ e busca AVANÇADA por filtros + timeline de movimentos.

const Processos = ({ onOpenCase } = {}) => {
  const [modo, setModo] = React.useState('numero'); // 'numero' | 'avancada'
  const [tribunais, setTribunais] = React.useState([]); // catálogo {sigla,nome,grupo}
  const [loadingTrib, setLoadingTrib] = React.useState(true);

  // busca por número
  const [numero, setNumero] = React.useState('');
  const [tribunalNum, setTribunalNum] = React.useState('tjsp');

  // busca avançada
  const [sel, setSel] = React.useState(() => new Set()); // siglas selecionadas
  const [filtros, setFiltros] = React.useState({ classe: '', assunto: '', orgaoJulgador: '', grau: '', dataInicio: '', dataFim: '' });
  const [filtrosOpen, setFiltrosOpen] = React.useState(false);

  // resultado
  const [buscando, setBuscando] = React.useState(false);
  const [resultados, setResultados] = React.useState(null); // [{tribunal,total,processos,erro}]
  const [totalGeral, setTotalGeral] = React.useState(0);
  const [erro, setErro] = React.useState('');
  const [detalhe, setDetalhe] = React.useState(null); // processo aberto no modal

  // histórico
  const [showHist, setShowHist] = React.useState(false);
  const [historico, setHistorico] = React.useState([]);
  const [histLoading, setHistLoading] = React.useState(false);
  const [salvando, setSalvando] = React.useState(false);

  // cadastrar processo como Caso do escritório
  const [cadastro, setCadastro] = React.useState(null); // form aberto (ou null)
  const [clientesLista, setClientesLista] = React.useState([]);
  const [clientesLoad, setClientesLoad] = React.useState(false);
  const [criandoCaso, setCriandoCaso] = React.useState(false);

  React.useEffect(() => {
    window.PACApi.datajud.tribunais()
      .then(setTribunais)
      .catch(() => setTribunais([]))
      .finally(() => setLoadingTrib(false));
  }, []);

  const grupos = React.useMemo(() => {
    const ordem = ['Superiores', 'TRF', 'TRT', 'TJ', 'TJM'];
    const map = {};
    for (const t of tribunais) (map[t.grupo] = map[t.grupo] || []).push(t);
    return ordem.filter(g => map[g]).map(g => [g, map[g]]);
  }, [tribunais]);

  const siglaNome = React.useMemo(() => Object.fromEntries(tribunais.map(t => [t.sigla, t.nome])), [tribunais]);

  const toggleTrib = (sigla) => setSel(prev => {
    const n = new Set(prev);
    n.has(sigla) ? n.delete(sigla) : n.add(sigla);
    return n;
  });
  const setAtalho = (siglas) => setSel(new Set(siglas));

  // ── formatação ──────────────────────────────────────────────
  const fmtData = (s) => {
    if (!s) return '—';
    const d = String(s).replace(/\D/g, '');
    if (d.length >= 8) return `${d.slice(6, 8)}/${d.slice(4, 6)}/${d.slice(0, 4)}`;
    return s;
  };
  const fmtDataHora = (iso) => {
    try { return new Date(iso).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' }); }
    catch { return iso || '—'; }
  };
  const ultimoMov = (p) => {
    const m = (p.movimentos || []).slice().sort((a, b) => new Date(b.dataHora) - new Date(a.dataHora))[0];
    return m ? `${m.nome} · ${fmtDataHora(m.dataHora)}` : 'Sem movimentações';
  };

  // ── ações ───────────────────────────────────────────────────
  const buscar = async () => {
    setErro(''); setResultados(null); setTotalGeral(0); setBuscando(true);
    try {
      if (modo === 'numero') {
        if (!numero.trim()) { setErro('Informe o número do processo.'); return; }
        const r = await window.PACApi.datajud.buscarPorNumero(numero, tribunalNum);
        setResultados([r]); setTotalGeral(r.total);
      } else {
        if (sel.size === 0) { setErro('Selecione ao menos um tribunal.'); return; }
        const payload = { tribunais: [...sel] };
        if (filtros.classe) payload.classe = Number(filtros.classe) || filtros.classe;
        if (filtros.assunto) payload.assunto = Number(filtros.assunto) || filtros.assunto;
        if (filtros.orgaoJulgador) payload.orgaoJulgador = filtros.orgaoJulgador;
        if (filtros.grau) payload.grau = filtros.grau;
        if (filtros.dataInicio) payload.dataInicio = filtros.dataInicio;
        if (filtros.dataFim) payload.dataFim = filtros.dataFim;
        const { resultados, totalGeral } = await window.PACApi.datajud.buscarAvancado(payload);
        setResultados(resultados); setTotalGeral(totalGeral);
      }
    } catch (e) {
      setErro(e.message || 'Erro na consulta.');
    } finally {
      setBuscando(false);
    }
  };

  const salvarConsulta = async () => {
    if (!resultados) return;
    setSalvando(true);
    try {
      const tribs = resultados.map(r => r.tribunal);
      const resumo = resultados.flatMap(r => r.processos.slice(0, 5).map(p => ({
        numeroProcesso: p.numeroProcesso, tribunal: p.tribunal, classe: p.classe?.nome,
      })));
      await window.PACApi.datajud.salvarConsulta({
        tipo_consulta: modo === 'numero' ? 'numero' : 'avancada',
        parametros: modo === 'numero' ? { numero, tribunal: tribunalNum } : { tribunais: tribs, ...filtros },
        resultado_resumo: resumo,
        total_processos_encontrados: totalGeral,
        tribunais_consultados: tribs,
      });
      alert('Consulta salva no histórico.');
    } catch (e) {
      alert('Erro ao salvar: ' + e.message);
    } finally {
      setSalvando(false);
    }
  };

  const abrirHistorico = async () => {
    setShowHist(true); setHistLoading(true);
    try { setHistorico(await window.PACApi.datajud.historico()); }
    catch { setHistorico([]); }
    finally { setHistLoading(false); }
  };

  const repetir = (h) => {
    setShowHist(false);
    if (h.tipo_consulta === 'numero') {
      setModo('numero');
      setNumero(h.parametros?.numero || '');
      setTribunalNum(h.parametros?.tribunal || 'tjsp');
    } else {
      setModo('avancada');
      setSel(new Set(h.parametros?.tribunais || h.tribunais_consultados || []));
      setFiltros({
        classe: h.parametros?.classe || '', assunto: h.parametros?.assunto || '',
        orgaoJulgador: h.parametros?.orgaoJulgador || '', grau: h.parametros?.grau || '',
        dataInicio: h.parametros?.dataInicio || '', dataFim: h.parametros?.dataFim || '',
      });
      setFiltrosOpen(true);
    }
  };

  // ── cadastrar processo como Caso ────────────────────────────
  const genShort = (nome) => {
    const w = (nome || '').trim().split(/\s+/).filter(Boolean);
    const sig = w.length > 1 ? w.map(x => x[0]).join('') : (w[0] || '');
    return sig.toUpperCase().slice(0, 10);
  };

  const abrirCadastro = (p) => {
    setCadastro({
      processo: p,
      clientMode: 'existente',
      client_id: '',
      novoNome: '', novoShort: '', novoTipo: 'PJ',
      title: `${p.classe?.nome || 'Processo'} — ${p.numeroProcesso}`,
      area: 'Contencioso', status: 'Em análise', priority: 'Média',
    });
    setClientesLoad(true);
    window.PACApi.clients.list()
      .then(setClientesLista).catch(() => setClientesLista([]))
      .finally(() => setClientesLoad(false));
  };
  const upC = (k, v) => setCadastro(c => ({ ...c, [k]: v }));

  const criarCaso = async () => {
    const c = cadastro;
    if (c.clientMode === 'existente' && !c.client_id) { alert('Selecione um cliente.'); return; }
    if (c.clientMode === 'novo' && !c.novoNome.trim()) { alert('Informe o nome do cliente.'); return; }
    if (!c.title.trim()) { alert('Informe o título do caso.'); return; }
    setCriandoCaso(true);
    try {
      let clientId = c.client_id;
      if (c.clientMode === 'novo') {
        const short = (c.novoShort.trim() || genShort(c.novoNome)).slice(0, 10) || 'CLI';
        const novo = await window.PACApi.clients.create({
          name: c.novoNome.trim(), short_name: short, person_type: c.novoTipo,
        });
        clientId = novo.id;
      }
      const caso = await window.PACApi.cases.create({
        title: c.title.trim(),
        client_id: clientId,
        area: c.area,
        status: c.status,
        priority: c.priority,
        numero_processo: c.processo.numeroProcesso,
        stage: (c.processo.orgaoJulgador?.nome || '').slice(0, 120) || undefined,
      });
      setCadastro(null); setDetalhe(null);
      if (onOpenCase && confirm(`Caso ${caso.number} criado e vinculado ao cliente. Abrir o caso agora?`)) {
        onOpenCase(caso.id);
      } else {
        alert(`Caso ${caso.number} criado e vinculado ao cliente.`);
      }
    } catch (e) {
      alert('Erro ao criar caso: ' + e.message);
    } finally {
      setCriandoCaso(false);
    }
  };

  const inputStyle = { width: '100%', boxSizing: 'border-box', padding: '8px 11px', borderRadius: 6, border: '1.5px solid #dde', fontSize: 13, background: '#fff', outline: 'none', fontFamily: 'inherit' };
  const todosProcessos = resultados ? resultados.flatMap(r => r.processos.map(p => ({ ...p, _trib: r.tribunal }))) : [];

  return (
    <div style={{ padding: '20px 24px', maxWidth: 1100, margin: '0 auto' }}>
      {/* Cabeçalho */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
        <h1 style={{ fontSize: 22, fontWeight: 800, color: 'var(--pac-navy)', margin: 0 }}>Consulta Processual</h1>
        <button className="btn ghost sm" onClick={abrirHistorico}><Icon name="search" size={13} /> Histórico</button>
      </div>
      <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', margin: '0 0 18px' }}>
        Dados públicos do DataJud (CNJ). Não inclui partes nem valor da causa, e tem defasagem de horas/dias — não usar para prazos fatais.
      </p>

      {/* Alternador de modo */}
      <div style={{ display: 'flex', gap: 0, border: '1.5px solid #dde', borderRadius: 8, overflow: 'hidden', width: 'fit-content', marginBottom: 16 }}>
        {[['numero', 'Por número'], ['avancada', 'Avançada (filtros)']].map(([v, l]) => (
          <button key={v} type="button" onClick={() => { setModo(v); setResultados(null); setErro(''); }}
            style={{ padding: '8px 18px', fontSize: 13, fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              background: modo === v ? 'var(--pac-navy)' : '#fff', color: modo === v ? '#fff' : 'var(--fg-muted)' }}>{l}</button>
        ))}
      </div>

      {/* Formulário */}
      <div className="panel" style={{ marginBottom: 20 }}>
        <div className="panel-body" style={{ padding: 16 }}>
          {modo === 'numero' ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 220px auto', gap: 12, alignItems: 'end' }}>
              <div className="field-group">
                <label>Número do processo (CNJ)</label>
                <input style={inputStyle} value={numero} onChange={e => setNumero(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && buscar()} placeholder="0000000-00.0000.0.00.0000" />
              </div>
              <div className="field-group">
                <label>Tribunal</label>
                <select style={inputStyle} value={tribunalNum} onChange={e => setTribunalNum(e.target.value)} disabled={loadingTrib}>
                  {grupos.map(([g, ts]) => (
                    <optgroup key={g} label={g}>
                      {ts.map(t => <option key={t.sigla} value={t.sigla}>{t.nome}</option>)}
                    </optgroup>
                  ))}
                </select>
              </div>
              <button className="btn" onClick={buscar} disabled={buscando} style={{ height: 38 }}>
                {buscando ? <><span className="spinner" style={{ width: 12, height: 12 }} /> Buscando…</> : <><Icon name="search" size={13} /> Buscar</>}
              </button>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {/* Atalhos + seleção de tribunais */}
              <div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <label style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: .4, color: 'var(--fg-muted)' }}>
                    Tribunais ({sel.size} selecionados)
                  </label>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button className="btn ghost sm" onClick={() => setAtalho(tribunais.map(t => t.sigla))}>Todos</button>
                    <button className="btn ghost sm" onClick={() => setAtalho(['tjsp', 'trf3', 'trt2'])}>Apenas SP</button>
                    <button className="btn ghost sm" onClick={() => setSel(new Set())}>Limpar</button>
                  </div>
                </div>
                <div style={{ maxHeight: 200, overflow: 'auto', border: '1px solid var(--border)', borderRadius: 8, padding: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {loadingTrib ? <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>Carregando tribunais…</span> : grupos.map(([g, ts]) => (
                    <div key={g}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--pac-navy)', marginBottom: 4 }}>{g}</div>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {ts.map(t => (
                          <span key={t.sigla} onClick={() => toggleTrib(t.sigla)}
                            className={`chip soft ${sel.has(t.sigla) ? 'active' : ''}`}
                            title={t.nome}
                            style={{ cursor: 'pointer', textTransform: 'uppercase', fontSize: 10.5 }}>
                            {t.sigla}
                          </span>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Filtros avançados */}
              <button className="btn ghost sm" style={{ alignSelf: 'flex-start' }} onClick={() => setFiltrosOpen(o => !o)}>
                <Icon name="search" size={11} /> Filtros avançados {filtrosOpen ? '▲' : '▼'}
              </button>
              {filtrosOpen && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                  <div className="field-group"><label>Código da classe</label><input style={inputStyle} value={filtros.classe} onChange={e => setFiltros(f => ({ ...f, classe: e.target.value }))} placeholder="Ex: 261" /></div>
                  <div className="field-group"><label>Código do assunto</label><input style={inputStyle} value={filtros.assunto} onChange={e => setFiltros(f => ({ ...f, assunto: e.target.value }))} placeholder="Ex: 1127" /></div>
                  <div className="field-group"><label>Grau</label>
                    <select style={inputStyle} value={filtros.grau} onChange={e => setFiltros(f => ({ ...f, grau: e.target.value }))}>
                      <option value="">Todos</option><option value="G1">G1 (1º grau)</option><option value="G2">G2 (2º grau)</option><option value="JE">JE (Juizado)</option>
                    </select>
                  </div>
                  <div className="field-group" style={{ gridColumn: '1/-1' }}><label>Órgão julgador (texto)</label><input style={inputStyle} value={filtros.orgaoJulgador} onChange={e => setFiltros(f => ({ ...f, orgaoJulgador: e.target.value }))} placeholder="Ex: Vara Cível de Caconde" /></div>
                  <div className="field-group"><label>Ajuizado de</label><input type="date" style={inputStyle} value={filtros.dataInicio} onChange={e => setFiltros(f => ({ ...f, dataInicio: e.target.value }))} /></div>
                  <div className="field-group"><label>Ajuizado até</label><input type="date" style={inputStyle} value={filtros.dataFim} onChange={e => setFiltros(f => ({ ...f, dataFim: e.target.value }))} /></div>
                </div>
              )}

              <button className="btn" onClick={buscar} disabled={buscando} style={{ alignSelf: 'flex-start', minWidth: 140 }}>
                {buscando ? <><span className="spinner" style={{ width: 12, height: 12 }} /> Buscando {sel.size} tribunais…</> : <><Icon name="search" size={13} /> Buscar</>}
              </button>
            </div>
          )}
        </div>
      </div>

      {erro && <div style={{ padding: '10px 14px', borderRadius: 8, background: 'rgba(194,37,62,.07)', border: '1px solid rgba(194,37,62,.2)', color: '#C2253E', fontSize: 13, marginBottom: 16 }}>{erro}</div>}

      {/* Resultados */}
      {resultados && (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>
              {totalGeral.toLocaleString('pt-BR')} processo(s) em {resultados.length} tribunal(is)
              <span style={{ fontWeight: 400, color: 'var(--fg-muted)' }}> · exibindo {todosProcessos.length}</span>
            </div>
            <button className="btn ghost sm" onClick={salvarConsulta} disabled={salvando}>
              {salvando ? 'Salvando…' : <><Icon name="folder" size={12} /> Salvar consulta</>}
            </button>
          </div>

          {/* Status por tribunal (quais retornaram / falharam) */}
          {resultados.length > 1 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
              {resultados.map(r => (
                <span key={r.tribunal} className="chip soft" style={{ fontSize: 10.5, textTransform: 'uppercase', color: r.erro ? '#C2253E' : undefined, borderColor: r.erro ? 'rgba(194,37,62,.3)' : undefined }} title={r.erro || `${r.total} encontrados`}>
                  {r.tribunal} · {r.erro ? 'falhou' : r.total}
                </span>
              ))}
            </div>
          )}

          {todosProcessos.length === 0 ? (
            <div className="panel" style={{ padding: 28, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>
              Nenhum processo encontrado com esses critérios. Lembre: processos sigilosos não são retornados pela API.
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {todosProcessos.map((p, i) => (
                <div key={p.numeroProcesso + i} className="panel" style={{ padding: 14, cursor: 'pointer' }} onClick={() => setDetalhe(p)}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--pac-navy)' }}>{p.numeroProcesso}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg)', marginTop: 2 }}>{p.classe?.nome || '—'}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 4 }}>{p.orgaoJulgador?.nome || '—'}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 6 }}>
                        <Icon name="search" size={10} /> {ultimoMov(p)}
                      </div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, flexShrink: 0 }}>
                      <span className="chip soft" style={{ textTransform: 'uppercase', fontSize: 10.5 }}>{(p.tribunal || p._trib)} · {p.grau}</span>
                      <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Ajuizado {fmtData(p.dataAjuizamento)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Modal detalhe */}
      {detalhe && (() => {
        const movs = (detalhe.movimentos || []).slice().sort((a, b) => new Date(b.dataHora) - new Date(a.dataHora));
        return (
          <div className="modal-overlay" onClick={() => setDetalhe(null)}>
            <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 640 }}>
              <div className="modal-head">
                <h3>{detalhe.numeroProcesso}</h3>
                <button className="btn ghost sm icon" onClick={() => setDetalhe(null)}><Icon name="x" size={14} /></button>
              </div>
              <div className="modal-body" style={{ maxHeight: '72vh', overflow: 'auto' }}>
                {/* Capa */}
                <div className="crm-grid" style={{ marginBottom: 18 }}>
                  <div className="crm-field"><span className="lbl">Tribunal</span><span className="val">{(detalhe.tribunal || detalhe._trib || '').toUpperCase()} · {detalhe.grau}</span></div>
                  <div className="crm-field"><span className="lbl">Classe</span><span className="val">{detalhe.classe?.nome || '—'}</span></div>
                  <div className="crm-field"><span className="lbl">Ajuizamento</span><span className="val">{fmtData(detalhe.dataAjuizamento)}</span></div>
                  <div className="crm-field"><span className="lbl">Última atualização</span><span className="val">{detalhe.dataHoraUltimaAtualizacao ? fmtDataHora(detalhe.dataHoraUltimaAtualizacao) : '—'}</span></div>
                  <div className="crm-field" style={{ gridColumn: '1/-1' }}><span className="lbl">Órgão julgador</span><span className="val">{detalhe.orgaoJulgador?.nome || '—'}</span></div>
                  {detalhe.assuntos?.length > 0 && (
                    <div className="crm-field" style={{ gridColumn: '1/-1' }}><span className="lbl">Assuntos</span>
                      <span className="val">{detalhe.assuntos.map(a => a.nome).join(' · ')}</span></div>
                  )}
                </div>

                {/* Timeline de movimentos */}
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: .4, color: 'var(--fg-muted)', marginBottom: 10 }}>
                  Movimentações ({movs.length})
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0, borderLeft: '2px solid var(--border)', paddingLeft: 14 }}>
                  {movs.length === 0 && <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>Sem movimentações registradas.</span>}
                  {movs.map((m, i) => (
                    <div key={i} style={{ position: 'relative', paddingBottom: 14 }}>
                      <div style={{ position: 'absolute', left: -19, top: 3, width: 8, height: 8, borderRadius: '50%', background: 'var(--pac-navy)' }} />
                      <div style={{ fontSize: 12.5, fontWeight: 600 }}>{m.nome}</div>
                      <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{fmtDataHora(m.dataHora)}</div>
                      {m.complementosTabelados?.length > 0 && (
                        <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>
                          {m.complementosTabelados.map(c => c.nome).join(' · ')}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
              <div className="modal-foot">
                <button className="btn ghost" onClick={() => setDetalhe(null)}>Fechar</button>
                <button className="btn" onClick={() => abrirCadastro(detalhe)}>
                  <Icon name="briefcase" size={13} /> Cadastrar como caso
                </button>
              </div>
            </div>
          </div>
        );
      })()}

      {/* Modal cadastrar como Caso */}
      {cadastro && (() => {
        const c = cadastro;
        return (
          <div className="modal-overlay" onClick={() => setCadastro(null)}>
            <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 560 }}>
              <div className="modal-head">
                <h3>Cadastrar como caso</h3>
                <button className="btn ghost sm icon" onClick={() => setCadastro(null)}><Icon name="x" size={14} /></button>
              </div>
              <div className="modal-body" style={{ display: 'grid', gap: 14, maxHeight: '72vh', overflow: 'auto' }}>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)', background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, padding: '8px 10px' }}>
                  Processo <b>{c.processo.numeroProcesso}</b> · {(c.processo.tribunal || '').toUpperCase()} · {c.processo.classe?.nome || '—'}
                </div>

                {/* Cliente */}
                <div>
                  <label style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: .4, color: 'var(--fg-muted)' }}>Cliente</label>
                  <div style={{ display: 'flex', gap: 0, border: '1.5px solid #dde', borderRadius: 8, overflow: 'hidden', width: 'fit-content', margin: '6px 0 10px' }}>
                    {[['existente', 'Cliente existente'], ['novo', 'Novo cliente']].map(([v, l]) => (
                      <button key={v} type="button" onClick={() => upC('clientMode', v)}
                        style={{ padding: '6px 14px', fontSize: 12.5, fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                          background: c.clientMode === v ? 'var(--pac-navy)' : '#fff', color: c.clientMode === v ? '#fff' : 'var(--fg-muted)' }}>{l}</button>
                    ))}
                  </div>
                  {c.clientMode === 'existente' ? (
                    <SearchableSelect style={inputStyle} value={c.client_id} onChange={e => upC('client_id', e.target.value)} disabled={clientesLoad}>
                      <option value="">{clientesLoad ? 'Carregando…' : 'Selecione um cliente'}</option>
                      {clientesLista.map(cl => <option key={cl.id} value={cl.id}>{cl.name}</option>)}
                    </SearchableSelect>
                  ) : (
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 120px 110px', gap: 10 }}>
                      <div className="field-group"><label>Nome / Razão social</label>
                        <input style={inputStyle} value={c.novoNome} autoFocus
                          onChange={e => upC('novoNome', e.target.value)}
                          onBlur={e => { if (!c.novoShort) upC('novoShort', genShort(e.target.value)); }}
                          placeholder="Nome do cliente" /></div>
                      <div className="field-group"><label>Nome curto</label>
                        <input style={inputStyle} value={c.novoShort} maxLength={10} onChange={e => upC('novoShort', e.target.value)} placeholder="Auto" /></div>
                      <div className="field-group"><label>Tipo</label>
                        <select style={inputStyle} value={c.novoTipo} onChange={e => upC('novoTipo', e.target.value)}>
                          <option value="PJ">PJ</option><option value="PF">PF</option>
                        </select></div>
                    </div>
                  )}
                </div>

                {/* Dados do caso */}
                <div className="field-group">
                  <label>Título do caso</label>
                  <input style={inputStyle} value={c.title} onChange={e => upC('title', e.target.value)} />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                  <div className="field-group"><label>Área</label>
                    <select style={inputStyle} value={c.area} onChange={e => upC('area', e.target.value)}>
                      {['Contencioso', 'M&A', 'Franchising', 'Societário', 'Contratos', 'Venture Capital', 'Propriedade Intelectual', 'Tributário', 'Trabalhista', 'Outros'].map(a => <option key={a}>{a}</option>)}
                    </select></div>
                  <div className="field-group"><label>Status</label>
                    <select style={inputStyle} value={c.status} onChange={e => upC('status', e.target.value)}>
                      {['Em análise', 'Em diligência', 'Em negociação', 'Em redação', 'Em revisão', 'Aguardando cliente', 'Aguardando externos', 'Suspenso'].map(s => <option key={s}>{s}</option>)}
                    </select></div>
                  <div className="field-group"><label>Prioridade</label>
                    <select style={inputStyle} value={c.priority} onChange={e => upC('priority', e.target.value)}>
                      {['Alta', 'Média', 'Baixa'].map(p => <option key={p}>{p}</option>)}
                    </select></div>
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>
                  O número CNJ <b>{c.processo.numeroProcesso}</b> será vinculado ao caso (campo nº do processo).
                </div>
              </div>
              <div className="modal-foot">
                <button className="btn ghost" onClick={() => setCadastro(null)}>Cancelar</button>
                <button className="btn" onClick={criarCaso} disabled={criandoCaso}>
                  {criandoCaso ? 'Criando…' : 'Criar caso'}
                </button>
              </div>
            </div>
          </div>
        );
      })()}

      {/* Modal histórico */}
      {showHist && (
        <div className="modal-overlay" onClick={() => setShowHist(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 560 }}>
            <div className="modal-head">
              <h3>Histórico de consultas</h3>
              <button className="btn ghost sm icon" onClick={() => setShowHist(false)}><Icon name="x" size={14} /></button>
            </div>
            <div className="modal-body" style={{ maxHeight: '70vh', overflow: 'auto' }}>
              {histLoading ? (
                <div style={{ padding: 16, color: 'var(--fg-muted)', fontSize: 13 }}><span className="spinner" style={{ width: 12, height: 12 }} /> Carregando…</div>
              ) : historico.length === 0 ? (
                <div style={{ padding: 16, color: 'var(--fg-muted)', fontSize: 13 }}>Nenhuma consulta salva ainda.</div>
              ) : historico.map(h => (
                <div className="list-row" key={h.id}>
                  <Icon name="search" size={14} style={{ color: 'var(--pac-navy)', flexShrink: 0 }} />
                  <div className="grow" style={{ minWidth: 0 }}>
                    <div className="ttl">
                      {h.tipo_consulta === 'numero' ? `Nº ${h.parametros?.numero || ''}` : `Avançada · ${(h.tribunais_consultados || []).length} tribunais`}
                    </div>
                    <div className="meta">{h.total_processos_encontrados} processo(s) · {fmtDataHora(h.criado_em)}</div>
                  </div>
                  <button className="btn ghost sm" onClick={() => repetir(h)}>Repetir</button>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
