// Desktop Acervo IA — fully interactive filters with hierarchical tribunal tree
// Tap any chip/checkbox/tree node to filter results live.

const TRIBUNAIS_TREE = [
  { id: 'sup', l: 'Tribunais Superiores', children: [
    { id: 'STF', l: 'STF · Supremo Tribunal Federal' },
    { id: 'STJ', l: 'STJ · Superior Tribunal de Justiça', children: [
      { id: 'STJ-CE', l: 'Corte Especial' },
      { id: 'STJ-1S', l: '1ª Seção · Direito Público' },
      { id: 'STJ-2S', l: '2ª Seção · Direito Privado' },
      { id: 'STJ-3S', l: '3ª Seção · Penal' },
      { id: 'STJ-1T', l: '1ª Turma' },
      { id: 'STJ-2T', l: '2ª Turma' },
      { id: 'STJ-3T', l: '3ª Turma' },
      { id: 'STJ-4T', l: '4ª Turma' },
      { id: 'STJ-5T', l: '5ª Turma' },
      { id: 'STJ-6T', l: '6ª Turma' },
    ]},
    { id: 'TST', l: 'TST · Superior do Trabalho' },
    { id: 'TSE', l: 'TSE · Superior Eleitoral' },
    { id: 'STM', l: 'STM · Superior Militar' },
  ]},
  { id: 'fed', l: 'Justiça Federal', children: [
    { id: 'TRF1', l: 'TRF1 · 1ª Região (DF, MG, BA…)' },
    { id: 'TRF2', l: 'TRF2 · 2ª Região (RJ, ES)' },
    { id: 'TRF3', l: 'TRF3 · 3ª Região (SP, MS)', children: [
      { id: 'TRF3-1T', l: '1ª Turma' },
      { id: 'TRF3-2T', l: '2ª Turma' },
      { id: 'TRF3-3T', l: '3ª Turma' },
      { id: 'TRF3-4T', l: '4ª Turma' },
      { id: 'TRF3-5T', l: '5ª Turma' },
      { id: 'TRF3-6T', l: '6ª Turma' },
    ]},
    { id: 'TRF4', l: 'TRF4 · 4ª Região (RS, SC, PR)' },
    { id: 'TRF5', l: 'TRF5 · 5ª Região (PE, CE…)' },
    { id: 'TRF6', l: 'TRF6 · 6ª Região (MG)' },
  ]},
  { id: 'est', l: 'Justiça Estadual', children: [
    { id: 'TJSP', l: 'TJSP · São Paulo', children: [
      { id: 'TJSP-priv', l: 'Direito Privado' },
      { id: 'TJSP-pub',  l: 'Direito Público' },
      { id: 'TJSP-crim', l: 'Seção Criminal' },
      { id: 'TJSP-emp',  l: 'Câmaras Empresariais' },
    ]},
    { id: 'TJRJ',  l: 'TJRJ · Rio de Janeiro' },
    { id: 'TJMG',  l: 'TJMG · Minas Gerais' },
    { id: 'TJRS',  l: 'TJRS · Rio Grande do Sul' },
    { id: 'TJPR',  l: 'TJPR · Paraná' },
    { id: 'TJSC',  l: 'TJSC · Santa Catarina' },
    { id: 'TJBA',  l: 'TJBA · Bahia' },
    { id: 'TJGO',  l: 'TJGO · Goiás' },
    { id: 'TJDFT', l: 'TJDFT · Distrito Federal' },
    { id: 'TJPE',  l: 'TJPE · Pernambuco' },
    { id: 'TJCE',  l: 'TJCE · Ceará' },
  ]},
  { id: 'trab', l: 'Justiça do Trabalho', children: [
    { id: 'TRT2',  l: 'TRT2 · São Paulo' },
    { id: 'TRT15', l: 'TRT15 · Campinas' },
    { id: 'TRT4',  l: 'TRT4 · Rio Grande do Sul' },
    { id: 'TRT1',  l: 'TRT1 · Rio de Janeiro' },
    { id: 'TRT3',  l: 'TRT3 · Minas Gerais' },
  ]},
];

// Sample result corpus — much larger than what gets rendered, used for filtering
const ACERVO_RESULTS = [
  { id: 'REsp 1.987.443/SP', tipo: 'jurisprudencia', tribunal: 'STJ', sub: 'STJ-3T', area: ['civil', 'empresarial'], ano: 2024, rel: 92, tone: 'positive',
    tr: 'STJ · 3ª Turma · Min. Nancy Andrighi · 14.11.2024',
    em: 'O inadimplemento substancial enseja a rescisão imediata do contrato quando comprometida a finalidade econômica…',
    tags: ['Cível', 'Contratos', 'Inadimplemento'] },
  { id: 'REsp 1.755.911/RS', tipo: 'jurisprudencia', tribunal: 'STJ', sub: 'STJ-3T', area: ['civil'], ano: 2024, rel: 84, tone: 'accent',
    tr: 'STJ · 3ª Turma · Min. Paulo de Tarso · 02.2024',
    em: 'A Teoria do Adimplemento Substancial impede a resolução quando o descumprimento for de pequena monta…',
    tags: ['Cível', 'Teoria do adimplemento'] },
  { id: 'AgInt no REsp 1.876.231/SP', tipo: 'jurisprudencia', tribunal: 'STJ', sub: 'STJ-4T', area: ['civil'], ano: 2024, rel: 71, tone: 'warn',
    tr: 'STJ · 4ª Turma · Min. Luis Felipe Salomão · 06.2024',
    em: 'Mora simples não se confunde com inadimplemento essencial, exigindo prova de prejuízo significativo…',
    tags: ['Cível', 'Mora'] },
  { id: 'REsp 2.001.214/MG', tipo: 'jurisprudencia', tribunal: 'STJ', sub: 'STJ-3T', area: ['empresarial'], ano: 2025, rel: 67, tone: 'warn',
    tr: 'STJ · 3ª Turma · Min. Marco Aurélio Bellizze · 03.2025',
    em: 'Em contratos empresariais complexos, a análise do impacto sobre a finalidade econômica é critério central…',
    tags: ['Empresarial', 'M&A'] },
  { id: 'RE 1.043.215/DF', tipo: 'jurisprudencia', tribunal: 'STF', sub: 'STF', area: ['constitucional', 'tributario'], ano: 2024, rel: 78, tone: 'accent',
    tr: 'STF · Pleno · Min. Luís Roberto Barroso · 09.2024',
    em: 'Princípio da segurança jurídica nas relações contratuais privadas tem assento constitucional…',
    tags: ['Constitucional', 'Contratos'] },
  { id: 'Ap. Cível 1234567-89.2024.8.26.0100', tipo: 'jurisprudencia', tribunal: 'TJSP', sub: 'TJSP-priv', area: ['civil', 'empresarial'], ano: 2025, rel: 72, tone: 'accent',
    tr: 'TJSP · 1ª Câm. Direito Privado · Des. Rui Cascaldi · 01.2025',
    em: 'Reforma de sentença que reconheceu adimplemento substancial diante de descumprimento de prazo essencial…',
    tags: ['Cível', 'Contratos'] },
  { id: 'Ap. Cível 2098765-12.2024.8.26.0001', tipo: 'jurisprudencia', tribunal: 'TJSP', sub: 'TJSP-emp', area: ['empresarial'], ano: 2024, rel: 65, tone: 'neutral',
    tr: 'TJSP · 2ª Câm. Reservada de Direito Empresarial · 11.2024',
    em: 'Sociedade limitada — exclusão de sócio por falta grave deve observar a finalidade econômica do contrato social…',
    tags: ['Empresarial', 'Societário'] },
  { id: 'Ap. Cível 0234-56.2024.8.19.0001', tipo: 'jurisprudencia', tribunal: 'TJRJ', sub: 'TJRJ', area: ['civil'], ano: 2024, rel: 58, tone: 'neutral',
    tr: 'TJRJ · 5ª Câm. Cível · Des. Cláudio Brandão · 08.2024',
    em: 'Aplicação da teoria da imprevisão em contratos de longa duração diante de alteração econômica imprevisível…',
    tags: ['Cível', 'Teoria da imprevisão'] },
  { id: 'Ap. 1238765-45.2024.4.03.6100', tipo: 'jurisprudencia', tribunal: 'TRF3', sub: 'TRF3-3T', area: ['tributario'], ano: 2024, rel: 81, tone: 'positive',
    tr: 'TRF3 · 3ª Turma · 10.2024',
    em: 'Reforma tributária — incidência de IBS sobre operações de M&A pré-existentes carece de previsão expressa…',
    tags: ['Tributário', 'Reforma'] },
  { id: 'Ap. 0091-23.2024.4.04.7100', tipo: 'jurisprudencia', tribunal: 'TRF4', sub: 'TRF4', area: ['tributario'], ano: 2024, rel: 62, tone: 'neutral',
    tr: 'TRF4 · 1ª Turma · 07.2024',
    em: 'Crédito presumido de ICMS — incidência na base de cálculo do IRPJ violando o pacto federativo…',
    tags: ['Tributário', 'ICMS'] },
  { id: 'Lei nº 14.451/2022 · art. 1.078', tipo: 'lei', tribunal: '—', sub: '—', area: ['empresarial'], ano: 2022, rel: 95, tone: 'positive',
    tr: 'Lei 14.451/22 · Sociedades Limitadas',
    em: 'Quóruns de deliberação social e exclusão de sócio — redação atualizada vigente desde 2024…',
    tags: ['Empresarial', 'Lei'] },
  { id: 'Código Civil · arts. 475–477', tipo: 'lei', tribunal: '—', sub: '—', area: ['civil'], ano: 2002, rel: 99, tone: 'positive',
    tr: 'Lei 10.406/02 · Código Civil',
    em: 'Da resolução por inexecução voluntária — fundamento legal da rescisão por inadimplemento…',
    tags: ['Civil', 'Código'] },
  { id: 'CPC · art. 1.009', tipo: 'lei', tribunal: '—', sub: '—', area: ['processual'], ano: 2015, rel: 90, tone: 'positive',
    tr: 'Lei 13.105/15 · Código de Processo Civil',
    em: 'Apelação — requisitos e prazos para interposição em processos cíveis…',
    tags: ['Processo Civil', 'Recursos'] },
  { id: 'Pontes de Miranda · Tratado XXI', tipo: 'doutrina', tribunal: '—', sub: '—', area: ['civil'], ano: 1972, rel: 88, tone: 'accent',
    tr: 'Tratado de Direito Privado · Tomo XXI',
    em: 'Resolução por inexecução — distinção dogmática entre resolução, resilição e rescisão…',
    tags: ['Doutrina', 'Civil'] },
  { id: 'Comparato · Poder de Controle na S/A', tipo: 'doutrina', tribunal: '—', sub: '—', area: ['empresarial'], ano: 1976, rel: 86, tone: 'accent',
    tr: 'O Poder de Controle na Sociedade Anônima',
    em: 'Análise estrutural do poder de controle e suas implicações em operações de M&A…',
    tags: ['Doutrina', 'Societário'] },
  { id: 'Súmula 308/STJ', tipo: 'sumula', tribunal: 'STJ', sub: 'STJ-CE', area: ['civil', 'imobiliario'], ano: 2005, rel: 76, tone: 'accent',
    tr: 'STJ · Súmula 308',
    em: 'A hipoteca firmada entre a construtora e o agente financeiro, anterior à promessa de compra e venda…',
    tags: ['Súmula', 'Civil'] },
];

const TIPOS = [
  { id: 'jurisprudencia', l: 'Jurisprudência' },
  { id: 'lei', l: 'Lei' },
  { id: 'doutrina', l: 'Doutrina' },
  { id: 'sumula', l: 'Súmula' },
];

const PERIODOS = [
  { id: '12m', l: 'Últimos 12 meses', max: 1 },
  { id: '24m', l: '24 meses', max: 2 },
  { id: '5a',  l: '5 anos', max: 5 },
  { id: 'todos', l: 'Sem filtro', max: 99 },
];

const AREAS = [
  { id: 'civil', l: 'Civil' },
  { id: 'empresarial', l: 'Empresarial' },
  { id: 'tributario', l: 'Tributário' },
  { id: 'constitucional', l: 'Constitucional' },
  { id: 'trabalhista', l: 'Trabalhista' },
  { id: 'processual', l: 'Processo Civil' },
  { id: 'imobiliario', l: 'Imobiliário' },
];

// Collect all descendant leaf IDs of a tree node
function descendantIds(node) {
  if (!node.children) return [node.id];
  return node.children.flatMap(descendantIds);
}
// Find a tree node by id
function findNode(id, tree = TRIBUNAIS_TREE) {
  for (const n of tree) {
    if (n.id === id) return n;
    if (n.children) {
      const f = findNode(id, n.children);
      if (f) return f;
    }
  }
  return null;
}

function toggleSetItem(set, id) {
  const next = new Set(set);
  if (next.has(id)) next.delete(id); else next.add(id);
  return next;
}

function DAcervo() {
  const t = useTheme();

  // Filter state
  const [tipos, setTipos] = React.useState(() => new Set(['jurisprudencia']));
  const [tribunais, setTribunais] = React.useState(() => new Set([
    ...descendantIds(findNode('STJ')),
    ...descendantIds(findNode('TJSP')),
  ]));
  const [periodo, setPeriodo] = React.useState('12m');
  const [areas, setAreas] = React.useState(() => new Set(['civil', 'empresarial']));
  const [expanded, setExpanded] = React.useState(() => new Set(['sup', 'STJ']));

  // Helpers
  const toggleTipo = id => setTipos(s => toggleSetItem(s, id));
  const toggleArea = id => setAreas(s => toggleSetItem(s, id));
  const toggleExp  = id => setExpanded(s => toggleSetItem(s, id));
  const toggleTribunal = (id) => {
    const node = findNode(id);
    if (!node) return;
    const leaves = descendantIds(node);
    setTribunais(s => {
      const next = new Set(s);
      const allOn = leaves.every(l => next.has(l));
      if (allOn) leaves.forEach(l => next.delete(l));
      else       leaves.forEach(l => next.add(l));
      return next;
    });
  };
  const isFullyOn = (node) => {
    const leaves = descendantIds(node);
    return leaves.every(l => tribunais.has(l));
  };
  const isPartlyOn = (node) => {
    const leaves = descendantIds(node);
    return !isFullyOn(node) && leaves.some(l => tribunais.has(l));
  };

  // Filter results
  const filtered = React.useMemo(() => {
    const yearMax = PERIODOS.find(p => p.id === periodo)?.max ?? 99;
    const cutoff = 2026 - yearMax;
    return ACERVO_RESULTS.filter(r => {
      if (tipos.size && !tipos.has(r.tipo)) return false;
      if (r.tipo === 'jurisprudencia' && tribunais.size) {
        if (!tribunais.has(r.tribunal) && !tribunais.has(r.sub)) return false;
      }
      if (areas.size && !r.area.some(a => areas.has(a))) return false;
      if (r.tipo === 'jurisprudencia' && r.ano < cutoff) return false;
      return true;
    });
  }, [tipos, tribunais, periodo, areas]);

  // Collapse tribunal leaves into the highest fully-on ancestor for chip display.
  const tribChips = React.useMemo(() => {
    const out = [];
    const seen = new Set();
    const walk = (nodes) => {
      for (const n of nodes) {
        if (seen.has(n.id)) continue;
        if (isFullyOn(n)) {
          out.push({ id: n.id, l: n.l.split('·')[0].trim() });
          descendantIds(n).forEach(d => seen.add(d));
          seen.add(n.id);
        } else if (n.children) {
          walk(n.children);
        }
      }
    };
    walk(TRIBUNAIS_TREE);
    return out;
  }, [tribunais]);

  const activeChips = [
    ...Array.from(tipos).map(id => ({ kind: 'tipo', id, l: TIPOS.find(x => x.id === id)?.l })),
    ...tribChips.map(c => ({ kind: 'trib', id: c.id, l: c.l })),
    { kind: 'per', id: periodo, l: PERIODOS.find(p => p.id === periodo)?.l },
    ...Array.from(areas).map(id => ({ kind: 'area', id, l: AREAS.find(x => x.id === id)?.l })),
  ].filter(c => c.l);

  const removeChip = (c) => {
    if (c.kind === 'tipo') setTipos(s => toggleSetItem(s, c.id));
    else if (c.kind === 'trib') {
      const node = findNode(c.id);
      const leaves = node ? descendantIds(node) : [c.id];
      setTribunais(s => {
        const n = new Set(s);
        leaves.forEach(l => n.delete(l));
        n.delete(c.id);
        return n;
      });
    }
    else if (c.kind === 'area') setAreas(s => toggleSetItem(s, c.id));
    else if (c.kind === 'per') setPeriodo('todos');
  };
  const clearAll = () => {
    setTipos(new Set(['jurisprudencia']));
    setTribunais(new Set());
    setAreas(new Set());
    setPeriodo('todos');
  };

  return <DesktopShell active="acv">
    <div style={{ padding: 22, height: '100%', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, color: t.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Acervo · busca conversacional</div>
        <h1 style={{ fontFamily: '"Playfair Display", serif', fontSize: 28, fontWeight: 600, margin: '4px 0 0', color: t.text }}>Pesquisa em jurisprudência</h1>
      </div>

      {/* IA search bar */}
      <Card pad={14} style={{ background: t.raised, marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: t.accent, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="spark" size={18}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 2 }}>Pergunte como um colega</div>
            <div style={{ fontSize: 14, color: t.text, fontStyle: 'italic' }}>"Tese mais recente do STJ sobre rescisão por inadimplemento essencial em M&A?"</div>
          </div>
          <Btn size="md" variant="primary" icon="search">Buscar</Btn>
        </div>
        {/* Active filter chips */}
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6, marginTop: 10 }}>
          <span style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>Filtros ativos:</span>
          {activeChips.length === 0 && <span style={{ fontSize: 11, color: t.subtext, fontStyle: 'italic' }}>nenhum</span>}
          {activeChips.map((c, i) => <button key={c.kind + c.id + i} onClick={() => removeChip(c)} style={{
            fontSize: 10.5, padding: '4px 9px 4px 11px', borderRadius: 999,
            background: t.elevated, color: t.text, border: `1px solid ${t.border}`,
            fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 5,
            fontFamily: 'inherit',
          }}>
            {c.l}
            <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 13, height: 13, borderRadius: '50%', background: t.borderSoft, color: t.subtext, fontSize: 11, lineHeight: 1 }}>×</span>
          </button>)}
          {activeChips.length > 0 && <button onClick={clearAll} style={{ marginLeft: 4, background: 'transparent', border: 'none', color: t.accent, fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>limpar tudo</button>}
        </div>
      </Card>

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '260px 1fr 320px', gap: 14, minHeight: 0 }}>
        {/* Filters sidebar */}
        <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, padding: 14, overflow: 'auto' }}>
          {/* Tipo */}
          <FilterGroup t={t} label="Tipo">
            {TIPOS.map(opt => {
              const count = ACERVO_RESULTS.filter(r => r.tipo === opt.id).length;
              return <FilterRow key={opt.id} t={t} on={tipos.has(opt.id)} onClick={() => toggleTipo(opt.id)} label={opt.l} count={count}/>;
            })}
          </FilterGroup>

          {/* Tribunais — hierarchical */}
          <FilterGroup t={t} label="Tribunais">
            <TribunalTree t={t} nodes={TRIBUNAIS_TREE} expanded={expanded} toggleExp={toggleExp}
              isFullyOn={isFullyOn} isPartlyOn={isPartlyOn} toggleTribunal={toggleTribunal}/>
          </FilterGroup>

          {/* Período */}
          <FilterGroup t={t} label="Período">
            {PERIODOS.map(opt => <FilterRow key={opt.id} t={t} on={periodo === opt.id} radio onClick={() => setPeriodo(opt.id)} label={opt.l}/>)}
          </FilterGroup>

          {/* Área */}
          <FilterGroup t={t} label="Área">
            {AREAS.map(opt => {
              const count = ACERVO_RESULTS.filter(r => r.area.includes(opt.id)).length;
              return <FilterRow key={opt.id} t={t} on={areas.has(opt.id)} onClick={() => toggleArea(opt.id)} label={opt.l} count={count}/>;
            })}
          </FilterGroup>
        </div>

        {/* Results */}
        <div style={{ overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ fontSize: 11, color: t.subtext, fontWeight: 600, padding: '0 2px 2px' }}>
            <b style={{ color: t.text, fontFamily: '"Playfair Display"', fontSize: 14 }}>{filtered.length}</b> resultado{filtered.length === 1 ? '' : 's'} para os filtros atuais
          </div>
          {filtered.length === 0 && <Card pad={20} style={{ textAlign: 'center', color: t.subtext }}>
            <Icon name="search" size={26} color={t.muted}/>
            <div style={{ marginTop: 10, fontSize: 13, color: t.text, fontWeight: 600 }}>Nenhum resultado</div>
            <div style={{ marginTop: 4, fontSize: 11.5 }}>Remova um filtro ou amplie o período.</div>
          </Card>}
          {filtered.map(r => <Card key={r.id} pad={14}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
              <div>
                <div style={{ fontFamily: '"Playfair Display"', fontSize: 15, fontWeight: 700, color: t.text }}>{r.id}</div>
                <div style={{ fontSize: 10.5, color: t.subtext, marginTop: 2 }}>{r.tr}</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 10, color: t.muted, fontWeight: 600 }}>Relevância</span>
                <Pill tone={r.tone}>{r.rel}%</Pill>
              </div>
            </div>
            <div style={{
              padding: '8px 11px', background: t.elevated, borderRadius: 8,
              borderLeft: `3px solid ${t.accent}`,
              fontSize: 12, color: t.textDim, lineHeight: 1.55, marginTop: 6,
              fontFamily: 'Georgia, serif', fontStyle: 'italic',
            }}>"{r.em}"</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
              <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                {r.tags.map(tag => <Pill key={tag} tone="neutral">{tag}</Pill>)}
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <Btn size="sm" variant="soft" icon="pin">Salvar</Btn>
                <Btn size="sm" variant="ghost">Inserir</Btn>
              </div>
            </div>
          </Card>)}
        </div>

        {/* IA sidebar */}
        <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, padding: 14, overflow: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 9 }}>
            <Icon name="spark" size={13} color={t.accent}/>
            <span style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Síntese do copiloto</span>
          </div>
          <div style={{ fontSize: 12.5, color: t.text, lineHeight: 1.55, marginBottom: 12 }}>
            O STJ tem firmado posição de que o <b>inadimplemento substancial</b> em M&A exige análise sobre a <b>finalidade econômica</b> do contrato, não bastando a simples mora.
          </div>

          <div style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 7 }}>Próximos passos sugeridos</div>
          {[
            { i: 'feather', t: `Inserir ${Math.min(3, filtered.length)} acórdãos no Recurso` },
            { i: 'doc',     t: 'Gerar memorando de tese · 2 pgs' },
            { i: 'pin',     t: 'Salvar coleção desta busca' },
          ].map((a, i) => <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 9px', background: t.elevated, borderRadius: 8, marginBottom: 6, cursor: 'pointer' }}>
            <Icon name={a.i} size={13} color={t.accent}/>
            <span style={{ fontSize: 11.5, color: t.text }}>{a.t}</span>
          </div>)}

          <div style={{ fontSize: 10, color: t.muted, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginTop: 14, marginBottom: 7 }}>Autores referenciados</div>
          {['Pontes de Miranda', 'Fábio Konder Comparato', 'Caio Mário'].map(a => <div key={a} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '5px 0', fontSize: 11.5, color: t.textDim }}>
            <Icon name="book" size={11} color={t.muted}/>
            <span>{a}</span>
          </div>)}
        </div>
      </div>
    </div>
  </DesktopShell>;
}

function FilterGroup({ t, label, children }) {
  return <div style={{ marginBottom: 16 }}>
    <div style={{ fontSize: 11, fontWeight: 700, color: t.text, marginBottom: 6, letterSpacing: 0.2 }}>{label}</div>
    {children}
  </div>;
}

function FilterRow({ t, on, onClick, label, count, radio, indent = 0 }) {
  const box = radio ? {
    borderRadius: '50%', border: `1.5px solid ${on ? t.accent : t.border}`, background: 'transparent',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  } : {
    borderRadius: 3, border: `1.5px solid ${on ? t.accent : t.border}`, background: on ? t.accent : 'transparent',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
  return <div onClick={onClick} style={{
    display: 'flex', alignItems: 'center', gap: 7,
    padding: '4px 0 4px ' + (indent * 14) + 'px',
    fontSize: 11.5, color: on ? t.text : t.subtext, cursor: 'pointer',
  }}>
    <span style={{ width: 13, height: 13, flexShrink: 0, ...box }}>
      {on && (radio
        ? <span style={{ width: 7, height: 7, borderRadius: '50%', background: t.accent }}/>
        : <Icon name="check" size={9} color="#fff" stroke={3}/>)}
    </span>
    <span style={{ flex: 1, fontWeight: on ? 600 : 500, lineHeight: 1.3 }}>{label}</span>
    {count > 0 && <span style={{ fontSize: 10, color: t.muted, fontWeight: 600 }}>{count}</span>}
  </div>;
}

function TribunalTree({ t, nodes, expanded, toggleExp, isFullyOn, isPartlyOn, toggleTribunal, depth = 0 }) {
  return <div>
    {nodes.map(node => {
      const hasChildren = !!node.children;
      const isExp = expanded.has(node.id);
      const full = isFullyOn(node);
      const partial = !full && isPartlyOn(node);
      return <div key={node.id}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '4px 0 4px ' + (depth * 12) + 'px',
          fontSize: 11.5, color: full ? t.text : t.subtext, cursor: 'pointer',
        }}>
          {hasChildren ? (
            <button onClick={() => toggleExp(node.id)} style={{
              width: 14, height: 14, padding: 0, background: 'transparent', border: 'none',
              color: t.subtext, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              transform: isExp ? 'rotate(90deg)' : 'none', transition: 'transform 0.15s', flexShrink: 0,
            }}>
              <Icon name="chevron" size={10}/>
            </button>
          ) : <span style={{ width: 14, flexShrink: 0 }}/>}

          {/* Checkbox */}
          <span onClick={() => toggleTribunal(node.id)} style={{
            width: 13, height: 13, flexShrink: 0, borderRadius: 3,
            border: `1.5px solid ${full || partial ? t.accent : t.border}`,
            background: full ? t.accent : (partial ? t.chipBg : 'transparent'),
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {full && <Icon name="check" size={9} color="#fff" stroke={3}/>}
            {partial && <span style={{ width: 6, height: 2, background: t.accent, borderRadius: 1 }}/>}
          </span>
          <span onClick={() => toggleTribunal(node.id)} style={{ flex: 1, fontWeight: full ? 600 : 500, lineHeight: 1.3 }}>{node.l}</span>
        </div>
        {hasChildren && isExp && <TribunalTree t={t} nodes={node.children} depth={depth + 1}
          expanded={expanded} toggleExp={toggleExp}
          isFullyOn={isFullyOn} isPartlyOn={isPartlyOn} toggleTribunal={toggleTribunal}/>}
      </div>;
    })}
  </div>;
}

Object.assign(window, { DAcervo });
