// ═══════════════════════════════════════════════════════
// BAUKO CRM — Prospecção (v1)
// Tela de prospecção de empresas: filtros + lista paginada
// + exportar CSV + drawer (Modal wide) de detalhes.
//
// Hoje usa mock data. Quando a CNPJ_API_URL estiver no ar,
// trocar a função `fetchProspeccao` por chamada real
// (ver TODO marcado abaixo).
//
// v1.1 — features adicionais:
//   • CNAE hierárquico com drill-down (popup)
//   • Município via IBGE (autocomplete + cache por UF)
//   • Persistência da última busca em sessionStorage
//   • Seleção múltipla + barra flutuante → onAddProspects
// ═══════════════════════════════════════════════════════
/* global React, CRM_DATA, Panel, Modal, Badge, fR, DadosPublicosTab */

const {
  useState:  useProspState,
  useEffect: useProspEffect,
  useMemo:   useProspMemo,
  useRef:    useProspRef,
} = React;

// ── Constantes ────────────────────────────────────────
const UF_LIST = [
  'AC','AL','AM','AP','BA','CE','DF','ES','GO','MA','MG','MS','MT','PA','PB',
  'PE','PI','PR','RJ','RN','RO','RR','RS','SC','SE','SP','TO',
];

// Códigos reais da Receita Federal — '02' e '04' não existem na base.
// '01' cobre MEI + ME; '05' cobre EPP Demais, médio e grande porte.
const PORTE_OPCOES = [
  { codigo: '01', label: 'ME / MEI' },
  { codigo: '03', label: 'EPP' },
  { codigo: '05', label: 'Demais' },
];
const PORTE_MAP = PORTE_OPCOES.reduce(function(a, p) { a[p.codigo] = p.label; return a; }, {});

const SITUACAO_OPCOES = [
  { codigo: '02', label: 'Ativa' },
  { codigo: '03', label: 'Suspensa' },
  { codigo: '04', label: 'Inapta' },
  { codigo: '08', label: 'Baixada' },
];
const SITUACAO_MAP = SITUACAO_OPCOES.reduce(function(a, s) { a[s.codigo] = s.label; return a; }, {});

// ── CNAE_HIERARQUIA — estrutura drill-down ─────────────
// Seção (letra) → Divisão (2d) → Grupo (3d) → Classe (4d) → Subclasse (7d / "XXXX-X/XX")
// Cobre os 10 CNAEs usados em MOCK_EMPRESAS + algumas opções extras para
// validar o drill-down de A (Agricultura), B (Mineração) e F (Construção).
//
// TODO: substituir mock por fetch real (GET CNPJ_API_URL/cnaes?q=)
// Quando a API local estiver no ar:
//   const base = window.BAUKO_AUTH && window.BAUKO_AUTH.CNPJ_API_URL;
//   const resp = await fetch(base + '/cnaes' + (q ? '?q=' + encodeURIComponent(q) : ''));
//   if (!resp.ok) throw new Error('HTTP ' + resp.status);
//   return await resp.json(); // mesmo formato que CNAE_HIERARQUIA abaixo
const CNAE_HIERARQUIA = [
  {
    codigo: 'A',
    nome: 'Agricultura, pecuária, produção florestal, pesca e aquicultura',
    divisoes: [
      {
        codigo: '01', nome: 'Agricultura, pecuária e serviços relacionados',
        grupos: [
          {
            codigo: '015', nome: 'Pecuária',
            classes: [
              {
                codigo: '0151', nome: 'Criação de bovinos',
                subclasses: [
                  { codigo: '0151201', codigoFmt: '0151-2/01', desc: 'Criação de bovinos para corte' },
                  { codigo: '0151202', codigoFmt: '0151-2/02', desc: 'Criação de bovinos para leite' },
                ],
              },
              {
                codigo: '0155', nome: 'Criação de suínos',
                subclasses: [
                  { codigo: '0155501', codigoFmt: '0155-5/01', desc: 'Criação de suínos' },
                ],
              },
            ],
          },
          {
            codigo: '011', nome: 'Produção de lavouras temporárias',
            classes: [
              {
                codigo: '0111', nome: 'Cultivo de cereais',
                subclasses: [
                  { codigo: '0111301', codigoFmt: '0111-3/01', desc: 'Cultivo de arroz' },
                  { codigo: '0111302', codigoFmt: '0111-3/02', desc: 'Cultivo de milho' },
                ],
              },
            ],
          },
        ],
      },
      {
        codigo: '02', nome: 'Produção florestal',
        grupos: [
          {
            codigo: '021', nome: 'Produção florestal — florestas plantadas',
            classes: [
              {
                codigo: '0210', nome: 'Produção florestal — florestas plantadas',
                subclasses: [
                  { codigo: '0210107', codigoFmt: '0210-1/07', desc: 'Extração de madeira em florestas plantadas' },
                  { codigo: '0210101', codigoFmt: '0210-1/01', desc: 'Cultivo de eucalipto' },
                ],
              },
            ],
          },
          {
            codigo: '022', nome: 'Produção florestal — florestas nativas',
            classes: [
              {
                codigo: '0220', nome: 'Produção florestal — florestas nativas',
                subclasses: [
                  { codigo: '0220906', codigoFmt: '0220-9/06', desc: 'Conservação de florestas nativas' },
                  { codigo: '0220901', codigoFmt: '0220-9/01', desc: 'Extração de madeira em florestas nativas' },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
  {
    codigo: 'B',
    nome: 'Indústrias extrativas',
    divisoes: [
      {
        codigo: '07', nome: 'Extração de minerais metálicos',
        grupos: [
          {
            codigo: '072', nome: 'Extração de minerais metálicos não-ferrosos',
            classes: [
              {
                codigo: '0721', nome: 'Extração de minério de alumínio',
                subclasses: [
                  { codigo: '0721901', codigoFmt: '0721-9/01', desc: 'Extração de minério de alumínio' },
                ],
              },
              {
                codigo: '0729', nome: 'Extração de outros minerais metálicos não-ferrosos',
                subclasses: [
                  { codigo: '0729404', codigoFmt: '0729-4/04', desc: 'Extração de minerais metálicos não-ferrosos não especificados anteriormente' },
                  { codigo: '0729403', codigoFmt: '0729-4/03', desc: 'Extração de minério de tungstênio' },
                ],
              },
            ],
          },
          {
            codigo: '071', nome: 'Extração de minério de ferro',
            classes: [
              {
                codigo: '0710', nome: 'Extração de minério de ferro',
                subclasses: [
                  { codigo: '0710301', codigoFmt: '0710-3/01', desc: 'Extração de minério de ferro' },
                ],
              },
            ],
          },
        ],
      },
      {
        codigo: '08', nome: 'Extração de minerais não-metálicos',
        grupos: [
          {
            codigo: '081', nome: 'Extração de pedra, areia e argila',
            classes: [
              {
                codigo: '0810', nome: 'Extração de pedra, areia e argila',
                subclasses: [
                  { codigo: '0810099', codigoFmt: '0810-0/99', desc: 'Extração de outros minerais não-metálicos' },
                  { codigo: '0810001', codigoFmt: '0810-0/01', desc: 'Extração de ardósia e beneficiamento associado' },
                ],
              },
            ],
          },
          {
            codigo: '089', nome: 'Extração de minerais não-metálicos não especificados',
            classes: [
              {
                codigo: '0892', nome: 'Extração e refino de sal marinho e sal-gema',
                subclasses: [
                  { codigo: '0892401', codigoFmt: '0892-4/01', desc: 'Extração de sal marinho' },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
  {
    codigo: 'F',
    nome: 'Construção',
    divisoes: [
      {
        codigo: '42', nome: 'Obras de infraestrutura',
        grupos: [
          {
            codigo: '421', nome: 'Construção de rodovias, ferrovias, obras urbanas e obras de arte especiais',
            classes: [
              {
                codigo: '4211', nome: 'Construção de rodovias e ferrovias',
                subclasses: [
                  { codigo: '4211101', codigoFmt: '4211-1/01', desc: 'Construção de rodovias e ferrovias' },
                ],
              },
              {
                codigo: '4212', nome: 'Construção de obras de arte especiais',
                subclasses: [
                  { codigo: '4212000', codigoFmt: '4212-0/00', desc: 'Construção de obras de arte especiais' },
                ],
              },
              {
                codigo: '4213', nome: 'Obras de urbanização',
                subclasses: [
                  { codigo: '4213800', codigoFmt: '4213-8/00', desc: 'Obras de urbanização — ruas, praças e calçadas' },
                ],
              },
            ],
          },
          {
            codigo: '422', nome: 'Obras de infraestrutura para energia, telecom, água, esgoto e dutos',
            classes: [
              {
                codigo: '4221', nome: 'Obras para geração e distribuição de energia elétrica e telecom',
                subclasses: [
                  { codigo: '4221901', codigoFmt: '4221-9/01', desc: 'Construção de barragens e represas para geração de energia elétrica' },
                  { codigo: '4221902', codigoFmt: '4221-9/02', desc: 'Construção de estações e redes de distribuição de energia elétrica' },
                ],
              },
            ],
          },
        ],
      },
      {
        codigo: '43', nome: 'Serviços especializados para construção',
        grupos: [
          {
            codigo: '432', nome: 'Instalações elétricas, hidráulicas e outras',
            classes: [
              {
                codigo: '4321', nome: 'Instalação e manutenção elétrica',
                subclasses: [
                  { codigo: '4321500', codigoFmt: '4321-5/00', desc: 'Instalação e manutenção elétrica' },
                ],
              },
              {
                codigo: '4322', nome: 'Instalações hidráulicas, ventilação e refrigeração',
                subclasses: [
                  { codigo: '4322301', codigoFmt: '4322-3/01', desc: 'Instalações hidráulicas, sanitárias e de gás' },
                ],
              },
            ],
          },
          {
            codigo: '431', nome: 'Demolição e preparação do terreno',
            classes: [
              {
                codigo: '4311', nome: 'Demolição e preparação de terrenos',
                subclasses: [
                  { codigo: '4311801', codigoFmt: '4311-8/01', desc: 'Demolição de edifícios e outras estruturas' },
                  { codigo: '4311802', codigoFmt: '4311-8/02', desc: 'Preparação de canteiro e limpeza de terreno' },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
];

// Achata a hierarquia em lista de subclasses (com referência ao path).
// Útil para a busca textual e para resolver "código → descrição/codigoFmt".
function flattenCnaes(hierarquia) {
  var out = [];
  hierarquia.forEach(function(secao) {
    secao.divisoes.forEach(function(divisao) {
      divisao.grupos.forEach(function(grupo) {
        grupo.classes.forEach(function(classe) {
          classe.subclasses.forEach(function(sub) {
            out.push({
              codigo:    sub.codigo,
              codigoFmt: sub.codigoFmt,
              desc:      sub.desc,
              path:      { secao: secao, divisao: divisao, grupo: grupo, classe: classe },
              pathStr:   secao.codigo + ' › ' + divisao.codigo + ' › ' + grupo.codigo + ' › ' + classe.codigo,
            });
          });
        });
      });
    });
  });
  return out;
}
const CNAE_FLAT = flattenCnaes(CNAE_HIERARQUIA);
// Lookup por código (rápido)
const CNAE_BY_CODIGO = CNAE_FLAT.reduce(function(a, s) { a[s.codigo] = s; return a; }, {});

// ── Mock de empresas (20 entradas, 4 filiais) ─────────
// Filiais: índices 1, 3, 10, 14 (matriz_filial === '2').
const MOCK_EMPRESAS = [
  {
    cnpj_raw:'12345678000195', cnpj_formatado:'12.345.678/0001-95',
    razao_social:'CONSTRUTORA HORIZONTE SA', nome_fantasia:'Horizonte Engenharia',
    situacao_cadastral:'02', data_inicio_atividade:'20080315',
    porte:'04', capital_social:25000000,
    cnae_principal:'4212000', cnae_descricao:'Construção de obras de arte especiais',
    municipio_nome:'São Paulo', uf:'SP',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'12345678000276', cnpj_formatado:'12.345.678/0002-76',
    razao_social:'CONSTRUTORA HORIZONTE SA', nome_fantasia:'Horizonte Engenharia · Filial Campinas',
    situacao_cadastral:'02', data_inicio_atividade:'20120420',
    porte:'04', capital_social:25000000,
    cnae_principal:'4211101', cnae_descricao:'Construção de rodovias e ferrovias',
    municipio_nome:'Campinas', uf:'SP',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'2'
  },
  {
    cnpj_raw:'22333444000155', cnpj_formatado:'22.333.444/0001-55',
    razao_social:'MINERADORA SERRA AZUL LTDA', nome_fantasia:'Serra Azul Mineração',
    situacao_cadastral:'02', data_inicio_atividade:'19980512',
    porte:'04', capital_social:80000000,
    cnae_principal:'0721901', cnae_descricao:'Extração de minério de alumínio',
    municipio_nome:'Itabira', uf:'MG',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'22333444000236', cnpj_formatado:'22.333.444/0002-36',
    razao_social:'MINERADORA SERRA AZUL LTDA', nome_fantasia:'Serra Azul Mineração · Unidade Conceição',
    situacao_cadastral:'02', data_inicio_atividade:'20051120',
    porte:'04', capital_social:80000000,
    cnae_principal:'0729404', cnae_descricao:'Extração de minerais metálicos não-ferrosos',
    municipio_nome:'Conceição do Mato Dentro', uf:'MG',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'2'
  },
  {
    cnpj_raw:'44555666000177', cnpj_formatado:'44.555.666/0001-77',
    razao_social:'FLORESTAL VALE VERDE LTDA', nome_fantasia:'Vale Verde Reflorestamento',
    situacao_cadastral:'02', data_inicio_atividade:'20100208',
    porte:'03', capital_social:1500000,
    cnae_principal:'0210107', cnae_descricao:'Extração de madeira em florestas plantadas',
    municipio_nome:'Telêmaco Borba', uf:'PR',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'33444555000166', cnpj_formatado:'33.444.555/0001-66',
    razao_social:'AGRO PLANALTO PARTICIPACOES LTDA', nome_fantasia:'Agro Planalto',
    situacao_cadastral:'02', data_inicio_atividade:'19951005',
    porte:'04', capital_social:120000000,
    cnae_principal:'0151201', cnae_descricao:'Criação de bovinos para corte',
    municipio_nome:'Rio Verde', uf:'GO',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'55666777000188', cnpj_formatado:'55.666.777/0001-88',
    razao_social:'LOCADORA EQUIPAMENTOS BRASILIA LTDA', nome_fantasia:'LEB Locações',
    situacao_cadastral:'02', data_inicio_atividade:'20180712',
    porte:'03', capital_social:800000,
    cnae_principal:'4213800', cnae_descricao:'Obras de urbanização — ruas, praças e calçadas',
    municipio_nome:'Brasília', uf:'DF',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'66777888000199', cnpj_formatado:'66.777.888/0001-99',
    razao_social:'MINERACAO PEDRAS DO NORTE SA', nome_fantasia:'Pedras Norte',
    situacao_cadastral:'02', data_inicio_atividade:'20030225',
    porte:'04', capital_social:45000000,
    cnae_principal:'0810099', cnae_descricao:'Extração de outros minerais não-metálicos',
    municipio_nome:'Marabá', uf:'PA',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'77888999000110', cnpj_formatado:'77.888.999/0001-10',
    razao_social:'CONSTRUCAO SUL LTDA ME', nome_fantasia:'Construsul',
    situacao_cadastral:'02', data_inicio_atividade:'20150818',
    porte:'02', capital_social:350000,
    cnae_principal:'4213800', cnae_descricao:'Obras de urbanização — ruas, praças e calçadas',
    municipio_nome:'Porto Alegre', uf:'RS',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'88999000000121', cnpj_formatado:'88.999.000/0001-21',
    razao_social:'ENGENHARIA COSTA SA', nome_fantasia:'Costa Engenharia',
    situacao_cadastral:'02', data_inicio_atividade:'19920614',
    porte:'05', capital_social:8500000,
    cnae_principal:'4211101', cnae_descricao:'Construção de rodovias e ferrovias',
    municipio_nome:'Salvador', uf:'BA',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'88999000000202', cnpj_formatado:'88.999.000/0002-02',
    razao_social:'ENGENHARIA COSTA SA', nome_fantasia:'Costa Engenharia · Filial Aracaju',
    situacao_cadastral:'02', data_inicio_atividade:'20160304',
    porte:'05', capital_social:8500000,
    cnae_principal:'4212000', cnae_descricao:'Construção de obras de arte especiais',
    municipio_nome:'Aracaju', uf:'SE',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'2'
  },
  {
    cnpj_raw:'99000111000132', cnpj_formatado:'99.000.111/0001-32',
    razao_social:'PEDRAS DO CARIRI ME LTDA', nome_fantasia:'Pedras Cariri',
    situacao_cadastral:'02', data_inicio_atividade:'20171102',
    porte:'02', capital_social:280000,
    cnae_principal:'0810099', cnae_descricao:'Extração de outros minerais não-metálicos',
    municipio_nome:'Crato', uf:'CE',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'10111222000143', cnpj_formatado:'10.111.222/0001-43',
    razao_social:'FLORESTAL AMAZON SA', nome_fantasia:'Amazon Florestas',
    situacao_cadastral:'02', data_inicio_atividade:'20090625',
    porte:'03', capital_social:1200000,
    cnae_principal:'0220906', cnae_descricao:'Conservação de florestas nativas',
    municipio_nome:'Manaus', uf:'AM',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'11222333000154', cnpj_formatado:'11.222.333/0001-54',
    razao_social:'CONSTRUTORA PAMPA SA', nome_fantasia:'Pampa Construções',
    situacao_cadastral:'02', data_inicio_atividade:'20000917',
    porte:'05', capital_social:6500000,
    cnae_principal:'4211101', cnae_descricao:'Construção de rodovias e ferrovias',
    municipio_nome:'Caxias do Sul', uf:'RS',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'11222333000235', cnpj_formatado:'11.222.333/0002-35',
    razao_social:'CONSTRUTORA PAMPA SA', nome_fantasia:'Pampa Construções · Unidade Porto Alegre',
    situacao_cadastral:'02', data_inicio_atividade:'20140728',
    porte:'05', capital_social:6500000,
    cnae_principal:'4321500', cnae_descricao:'Instalação e manutenção elétrica em obras',
    municipio_nome:'Porto Alegre', uf:'RS',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'2'
  },
  {
    cnpj_raw:'12333444000165', cnpj_formatado:'12.333.444/0001-65',
    razao_social:'BOVINOS CENTRO OESTE LTDA', nome_fantasia:'Bovinos Centro',
    situacao_cadastral:'02', data_inicio_atividade:'20060409',
    porte:'04', capital_social:35000000,
    cnae_principal:'0151201', cnae_descricao:'Criação de bovinos para corte',
    municipio_nome:'Cuiabá', uf:'MT',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'13444555000176', cnpj_formatado:'13.444.555/0001-76',
    razao_social:'ESTRADAS DO LITORAL EPP LTDA', nome_fantasia:'Estradas Litoral',
    situacao_cadastral:'03', data_inicio_atividade:'20130222',
    porte:'03', capital_social:950000,
    cnae_principal:'4211101', cnae_descricao:'Construção de rodovias e ferrovias',
    municipio_nome:'Florianópolis', uf:'SC',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'14555666000187', cnpj_formatado:'14.555.666/0001-87',
    razao_social:'EXTRATIVA BAUXITA MINAS LTDA', nome_fantasia:'Extrativa Bauxita',
    situacao_cadastral:'04', data_inicio_atividade:'20040818',
    porte:'05', capital_social:4200000,
    cnae_principal:'0721901', cnae_descricao:'Extração de minério de alumínio',
    municipio_nome:'Belo Horizonte', uf:'MG',
    opcao_simples:'N', opcao_mei:'N', matriz_filial:'1'
  },
  {
    cnpj_raw:'15666777000198', cnpj_formatado:'15.666.777/0001-98',
    razao_social:'JOAQUIM SILVA PEDREIRO MEI', nome_fantasia:'Joaquim Pedreiro',
    situacao_cadastral:'02', data_inicio_atividade:'20210510',
    porte:'01', capital_social:1000,
    cnae_principal:'4213800', cnae_descricao:'Obras de urbanização — ruas, praças e calçadas',
    municipio_nome:'Recife', uf:'PE',
    opcao_simples:'S', opcao_mei:'S', matriz_filial:'1'
  },
  {
    cnpj_raw:'16777888000109', cnpj_formatado:'16.777.888/0001-09',
    razao_social:'REFLORESTAMENTO PINHAL EPP LTDA', nome_fantasia:'Reflorestamento Pinhal',
    situacao_cadastral:'08', data_inicio_atividade:'20111114',
    porte:'03', capital_social:1800000,
    cnae_principal:'0210107', cnae_descricao:'Extração de madeira em florestas plantadas',
    municipio_nome:'Itararé', uf:'SP',
    opcao_simples:'S', opcao_mei:'N', matriz_filial:'1'
  },
];

// ── fetchCnpjDireto — GET /empresa/{cnpj} — busca exata por CNPJ completo ──
async function fetchCnpjDireto(cnpj, signal) {
  var base = window.BAUKO_AUTH && window.BAUKO_AUTH.CNPJ_API_URL;
  if (!base || base.includes('SEU_IP')) return null;
  var digitos = cnpj.replace(/\D/g, '');
  var resp = await fetch(
    base.replace(/\/$/, '') + '/empresa/' + digitos,
    signal ? { signal: signal } : {}
  );
  if (resp.status === 404) return null;
  if (!resp.ok) throw new Error('HTTP ' + resp.status);
  return resp.json();
}

// ── fetchProspeccao — GET /prospeccao com filtros mapeados ────────────────
async function fetchProspeccao(filtros, limit, offset, signal) {
  var base = window.BAUKO_AUTH && window.BAUKO_AUTH.CNPJ_API_URL;
  if (!base || base.includes('SEU_IP')) {
    // Fallback: retorna mock enquanto API não estiver configurada
    var mock = MOCK_EMPRESAS;
    // Filtro mock de matriz/filial
    if (filtros.matrizFilial === '1') mock = mock.filter(function(e){ return e.matriz_filial === '1'; });
    else if (filtros.matrizFilial === '2') mock = mock.filter(function(e){ return e.matriz_filial === '2'; });
    // Filtro mock de texto
    if (filtros.q) {
      var ql = filtros.q.toLowerCase();
      mock = mock.filter(function(e){
        return (e.razao_social || '').toLowerCase().indexOf(ql) >= 0 ||
               (e.nome_fantasia || '').toLowerCase().indexOf(ql) >= 0;
      });
    }
    return mock.slice(offset || 0, (offset || 0) + (limit || 200));
  }
  var url = new URL(base.replace(/\/$/, '') + '/prospeccao');
  // Busca textual por nome/razao social
  if (filtros.q && filtros.q.trim().length >= 2) {
    url.searchParams.set('q', filtros.q.trim());
    if (filtros.modo_busca && filtros.modo_busca !== 'contem') {
      url.searchParams.set('modo_busca', filtros.modo_busca);
    }
  }
  // CNAEs (múltiplos)
  if (filtros.cnaes && filtros.cnaes.length) {
    filtros.cnaes.forEach(function(c) { url.searchParams.append('cnae', c); });
  }
  // UF
  if (filtros.uf) url.searchParams.set('uf', filtros.uf);
  // Município
  if (filtros.municipio && filtros.municipio.trim()) {
    url.searchParams.set('municipio', filtros.municipio.trim());
  }
  // Portes (múltiplos)
  if (filtros.portes && filtros.portes.length) {
    filtros.portes.forEach(function(p) { url.searchParams.append('porte', p); });
  }
  // Situações (múltiplas)
  if (filtros.situacoes && filtros.situacoes.length) {
    filtros.situacoes.forEach(function(s) { url.searchParams.append('situacao', s); });
  }
  // Matriz/Filial: '1'=só matrizes, '2'=só filiais, 'todos'=ambos
  if (filtros.matrizFilial === '1' || filtros.matrizFilial === '2') {
    url.searchParams.set('matriz_filial', filtros.matrizFilial);
  }
  // Simples Nacional
  if (filtros.simples === 'S' || filtros.simples === 'N') {
    url.searchParams.set('simples', filtros.simples);
  }
  // Paginação
  url.searchParams.set('limit',  String(limit  || 200));
  url.searchParams.set('offset', String(offset || 0));

  var resp = await fetch(url.toString(), signal ? { signal: signal } : {});
  if (!resp.ok) throw new Error('HTTP ' + resp.status);
  var lista = await resp.json();
  // Expõe total real (X-Total-Count) no array para uso opcional no componente
  lista._total = parseInt(resp.headers.get('X-Total-Count') || '0', 10);
  return lista;
}

// Busca empresas por nome de sócio via /socios/buscar
async function fetchSociosBuscar(nome, filtros, signal) {
  var base = window.BAUKO_AUTH && window.BAUKO_AUTH.CNPJ_API_URL;
  if (!base || base.includes('SEU_IP')) return [];
  var url = new URL(base.replace(/\/$/, '') + '/socios/buscar');
  url.searchParams.set('nome', nome);
  url.searchParams.set('limit', '50');
  // Aplica os mesmos filtros do /prospeccao para reduzir o volume retornado
  if (filtros) {
    if (filtros.uf) url.searchParams.set('uf', filtros.uf);
    if (filtros.municipio) url.searchParams.set('municipio', filtros.municipio);
    if (filtros.portes && filtros.portes.length)
      filtros.portes.forEach(function(p) { url.searchParams.append('porte', p); });
    if (filtros.cnaes && filtros.cnaes.length)
      filtros.cnaes.forEach(function(c) { url.searchParams.append('cnae', c); });
    if (filtros.situacoes && filtros.situacoes.length)
      filtros.situacoes.forEach(function(s) { url.searchParams.append('situacao', s); });
    if (filtros.simples === 'S' || filtros.simples === 'N')
      url.searchParams.set('simples', filtros.simples);
    if (filtros.matrizFilial === '1' || filtros.matrizFilial === '2')
      url.searchParams.set('matriz_filial', filtros.matrizFilial);
  }
  var resp = await fetch(url.toString(), signal ? { signal: signal } : {});
  if (!resp.ok) throw new Error('HTTP ' + resp.status);
  return await resp.json();
}

// Verifica se um CNPJ já foi prospectado/excluído do BDR (via localStorage)
function jaProspectado(cnpjRaw) {
  if (!cnpjRaw) return false;
  try {
    var cnpj = String(cnpjRaw).replace(/\D/g, '');
    var raw = localStorage.getItem('bdr_prospectados');
    var lista = raw ? JSON.parse(raw) : [];
    return lista.indexOf(cnpj) >= 0;
  } catch(e) { return false; }
}

// Adiciona/remove CNPJ da lista de prospectados no localStorage
function toggleProspectado(cnpjRaw) {
  if (!cnpjRaw) return;
  try {
    var cnpj = String(cnpjRaw).replace(/\D/g, '');
    var raw  = localStorage.getItem('bdr_prospectados');
    var lista = raw ? JSON.parse(raw) : [];
    var idx  = lista.indexOf(cnpj);
    if (idx >= 0) lista.splice(idx, 1); else lista.push(cnpj);
    localStorage.setItem('bdr_prospectados', JSON.stringify(lista));
  } catch(e) {}
}

// ── Helpers ───────────────────────────────────────────
function fmtDataReceita(d) {
  if (!d || d.length !== 8) return '—';
  return d.slice(6,8) + '/' + d.slice(4,6) + '/' + d.slice(0,4);
}
function clienteByCNPJ(cnpjRaw) {
  if (!cnpjRaw) return null;
  var alvo = String(cnpjRaw).replace(/\D/g, '');
  if (!alvo) return null;
  var lista = (window.CRM_DATA && window.CRM_DATA.clientes) || [];
  return lista.find(function(c) {
    return (c.cnpj || '').replace(/\D/g,'') === alvo;
  }) || null;
}
// Devolve string formatada para exibição "0151-2/01" se conhecido, senão o código bruto.
function cnaeLabel(codigo) {
  var s = CNAE_BY_CODIGO[codigo];
  return s ? s.codigoFmt : codigo;
}

function exportarCSV(resultados) {
  var headers = [
    'CNPJ','Razão Social','Nome Fantasia','Município','UF',
    'Porte','Tipo','CNAE','Capital Social','Data Abertura',
  ];
  function esc(v) {
    var s = v == null ? '' : String(v);
    if (s.indexOf('"') >= 0 || s.indexOf(';') >= 0 || s.indexOf('\n') >= 0) {
      s = '"' + s.replace(/"/g, '""') + '"';
    }
    return s;
  }
  var linhas = resultados.map(function(e) {
    return [
      e.cnpj_formatado, e.razao_social, e.nome_fantasia || '',
      e.municipio_nome, e.uf,
      PORTE_MAP[e.porte] || e.porte,
      e.matriz_filial === '1' ? 'Matriz' : 'Filial',
      (e.cnae_principal || '') + ' - ' + (e.cnae_descricao || ''),
      typeof e.capital_social === 'number' ? e.capital_social.toFixed(2).replace('.', ',') : '',
      fmtDataReceita(e.data_inicio_atividade),
    ].map(esc).join(';');
  });
  // BOM para Excel reconhecer UTF-8
  var csv = '﻿' + [headers.join(';')].concat(linhas).join('\r\n');
  var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  var url  = URL.createObjectURL(blob);
  var hoje = new Date();
  var yyyymmdd =
    hoje.getFullYear()
    + String(hoje.getMonth() + 1).padStart(2, '0')
    + String(hoje.getDate()).padStart(2, '0');
  var a = document.createElement('a');
  a.href = url;
  a.download = 'prospeccao_bauko_' + yyyymmdd + '.csv';
  document.body.appendChild(a); a.click();
  setTimeout(function() {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 100);
}

// ── Persistência sessionStorage ────────────────────────
var PROSP_STORAGE_KEY = 'prospeccao_last_search';
function lerSnapshot() {
  try {
    var raw = sessionStorage.getItem(PROSP_STORAGE_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch(e) { return null; }
}
function salvarSnapshot(snap) {
  try { sessionStorage.setItem(PROSP_STORAGE_KEY, JSON.stringify(snap)); } catch(e) { /* ignora quota/serializa */ }
}
function limparSnapshot() {
  try { sessionStorage.removeItem(PROSP_STORAGE_KEY); } catch(e) { /* ignora */ }
}

// ═══════════════════════════════════════════════════════
// COMPONENTE — Popup CNAE hierárquico
// ═══════════════════════════════════════════════════════
function CnaeHierarquicoPopup({ open, onClose, cnaesSel, onChange }) {
  const [path,  setPath]  = useProspState([]);  // array de crumbs: [{tipo, codigo, nome}]
  const [busca, setBusca] = useProspState('');

  // Reset ao abrir
  useProspEffect(function() {
    if (open) { setPath([]); setBusca(''); }
  }, [open]);

  // Recria ícones lucide a cada render (idêntico ao padrão CRM)
  useProspEffect(function() {
    try { if (window.lucide) window.lucide.createIcons({ attrs: { 'stroke-width': 1.75 } }); }
    catch(e) {}
  });

  var buscaTrim = (busca || '').trim().toLowerCase();
  var modoBusca = buscaTrim.length >= 2;

  // Resultados da busca via API (quando disponível) + fallback local
  var [cnaesAPI, setCnaesAPI] = useProspState([]);
  useProspEffect(function() {
    if (!modoBusca) { setCnaesAPI([]); return; }
    var base = window.BAUKO_AUTH && window.BAUKO_AUTH.CNPJ_API_URL;
    if (!base || base.includes('SEU_IP')) { setCnaesAPI([]); return; }
    var url = base.replace(/\/$/, '') + '/cnaes?q=' + encodeURIComponent(buscaTrim);
    fetch(url)
      .then(function(r) { return r.ok ? r.json() : []; })
      .then(function(data) {
        // API retorna [{ codigo, descricao }] — adapta para shape esperado pelo render
        setCnaesAPI((data || []).map(function(item) {
          return { codigo: item.codigo, codigoFmt: item.codigo, desc: item.descricao };
        }));
      })
      .catch(function() { setCnaesAPI([]); });
  }, [modoBusca, buscaTrim]);

  var resultadosBusca = useProspMemo(function() {
    if (!modoBusca) return [];
    // Usa resultados da API se disponíveis; caso contrário, filtra localmente
    if (cnaesAPI.length > 0) return cnaesAPI.slice(0, 40);
    var digitos = buscaTrim.replace(/\D/g, '');
    return CNAE_FLAT.filter(function(s) {
      if (digitos && (s.codigo.indexOf(digitos) >= 0 || s.codigoFmt.replace(/\D/g,'').indexOf(digitos) >= 0)) return true;
      if (s.desc.toLowerCase().includes(buscaTrim)) return true;
      if (s.path.classe.nome.toLowerCase().includes(buscaTrim)) return true;
      if (s.path.grupo.nome.toLowerCase().includes(buscaTrim)) return true;
      if (s.path.divisao.nome.toLowerCase().includes(buscaTrim)) return true;
      if (s.path.secao.nome.toLowerCase().includes(buscaTrim)) return true;
      return false;
    }).slice(0, 40);
  }, [buscaTrim, modoBusca, cnaesAPI]);

  // Determina o nível atual e os itens a exibir
  function viewAtual() {
    if (path.length === 0) return { tipo: 'secoes', items: CNAE_HIERARQUIA };
    var node = CNAE_HIERARQUIA.find(function(s) { return s.codigo === path[0].codigo; });
    if (!node) return { tipo: 'secoes', items: CNAE_HIERARQUIA };
    if (path.length === 1) return { tipo: 'divisoes', items: node.divisoes };
    node = node.divisoes.find(function(d) { return d.codigo === path[1].codigo; });
    if (!node) return { tipo: 'divisoes', items: [] };
    if (path.length === 2) return { tipo: 'grupos', items: node.grupos };
    node = node.grupos.find(function(g) { return g.codigo === path[2].codigo; });
    if (!node) return { tipo: 'grupos', items: [] };
    if (path.length === 3) return { tipo: 'classes', items: node.classes };
    node = node.classes.find(function(c) { return c.codigo === path[3].codigo; });
    if (!node) return { tipo: 'classes', items: [] };
    return { tipo: 'subclasses', items: node.subclasses };
  }

  function entrar(item) {
    setPath(function(prev) { return prev.concat([{ codigo: item.codigo, nome: item.nome }]); });
  }
  function voltar() {
    setPath(function(prev) { return prev.slice(0, -1); });
  }
  function irPara(idx) {
    setPath(function(prev) { return prev.slice(0, idx); });
  }
  function selecionarSubclasse(sub) {
    // Conforme spec: ao selecionar uma subclasse, fecha popup e adiciona chip.
    // Já presente? Não duplica — só adiciona se ainda não está.
    if (cnaesSel.indexOf(sub.codigo) < 0) {
      onChange(cnaesSel.concat([sub.codigo]));
    }
    onClose();
  }

  if (!open) return null;

  var view = viewAtual();

  var inputBuscaStyle = {
    width: '100%', padding: '10px 12px',
    border: '1px solid var(--border-2)',
    borderRadius: 'var(--r-sm)', background: 'var(--surface)',
    fontFamily: 'var(--ff-body)', fontSize: 13, color: 'var(--tx)',
    outline: 'none', boxSizing: 'border-box', marginBottom: 12,
  };
  var crumbBtnStyle = {
    background: 'none', border: 'none', cursor: 'pointer',
    padding: '2px 6px', borderRadius: 'var(--r-sm)',
    font: '500 12px/1.2 var(--ff-mono)', color: 'var(--tx-2)',
  };

  return (
    <Modal open={open} onClose={onClose} title="Selecionar CNAE" subtitle="Navegue pela hierarquia ou busque por código/descrição" wide>
      <div>
        {/* Busca por texto */}
        <input
          value={busca}
          onChange={function(e) { setBusca(e.target.value); }}
          placeholder="Buscar em qualquer nível — código ou descrição (mín. 2 caracteres)…"
          style={inputBuscaStyle}
          autoFocus />

        {/* Breadcrumb + botão voltar (oculto em modo busca) */}
        {!modoBusca && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap',
            padding: '8px 10px', background: 'var(--surface-2)',
            border: '1px solid var(--border)', borderRadius: 'var(--r-sm)',
            marginBottom: 10, minHeight: 36,
          }}>
            {path.length > 0 && (
              <button onClick={voltar} title="Voltar"
                style={Object.assign({}, crumbBtnStyle, {
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  marginRight: 6, color: 'var(--tx)',
                })}>
                <i data-lucide="chevron-left" style={{ width: 13, height: 13 }}></i>
                Voltar
              </button>
            )}
            <button onClick={function() { irPara(0); }} style={crumbBtnStyle}>
              Todas as seções
            </button>
            {path.map(function(crumb, idx) {
              var ehUltimo = idx === path.length - 1;
              return (
                <React.Fragment key={idx}>
                  <span style={{ color: 'var(--tx-3)', font: '500 12px/1 var(--ff-body)' }}>›</span>
                  <button onClick={function() { irPara(idx + 1); }}
                    disabled={ehUltimo}
                    style={Object.assign({}, crumbBtnStyle, ehUltimo ? {
                      color: 'var(--tx)', cursor: 'default', fontWeight: 600,
                    } : {})}>
                    {crumb.codigo}
                  </button>
                </React.Fragment>
              );
            })}
          </div>
        )}

        {/* Lista */}
        <div style={{
          maxHeight: 380, overflowY: 'auto',
          border: '1px solid var(--border)', borderRadius: 'var(--r-sm)',
          background: 'var(--surface)',
        }}>
          {/* Modo busca */}
          {modoBusca && resultadosBusca.length === 0 && (
            <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--tx-3)', font: '400 12px/1.5 var(--ff-body)' }}>
              Nenhum CNAE encontrado para "{busca}"
            </div>
          )}
          {modoBusca && resultadosBusca.map(function(sub) {
            var ja = cnaesSel.indexOf(sub.codigo) >= 0;
            return (
              <div key={sub.codigo}
                onClick={function() { selecionarSubclasse(sub); }}
                style={{
                  padding: '10px 14px', cursor: 'pointer',
                  borderBottom: '1px solid var(--border)',
                  background: ja ? 'var(--grn-050)' : 'transparent',
                }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ font: '600 12px/1 var(--ff-mono)', color: 'var(--tx)' }}>{sub.codigoFmt}</span>
                  {ja && <span style={{ fontSize: 10, color: 'var(--ok)', font: '600 10px/1 var(--ff-body)' }}>✓ JÁ SELECIONADO</span>}
                </div>
                <div style={{ font: '400 12px/1.4 var(--ff-body)', color: 'var(--tx)', marginTop: 3 }}>{sub.desc}</div>
                <div style={{ font: '400 10px/1.2 var(--ff-mono)', color: 'var(--tx-3)', marginTop: 3 }}>{sub.pathStr}</div>
              </div>
            );
          })}

          {/* Modo drill-down */}
          {!modoBusca && view.items.length === 0 && (
            <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--tx-3)', font: '400 12px/1.5 var(--ff-body)' }}>
              Nenhum item neste nível.
            </div>
          )}
          {!modoBusca && view.items.map(function(item) {
            var isSubclasse = view.tipo === 'subclasses';
            var ja = isSubclasse && cnaesSel.indexOf(item.codigo) >= 0;
            var displayCodigo = isSubclasse ? item.codigoFmt : item.codigo;
            var displayNome   = isSubclasse ? item.desc : item.nome;
            return (
              <div key={item.codigo}
                onClick={function() {
                  if (isSubclasse) selecionarSubclasse(item);
                  else entrar(item);
                }}
                style={{
                  padding: '10px 14px', cursor: 'pointer',
                  borderBottom: '1px solid var(--border)',
                  background: ja ? 'var(--grn-050)' : 'transparent',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                <div style={{ minWidth: 80, flexShrink: 0 }}>
                  <span style={{ font: '600 12px/1 var(--ff-mono)', color: 'var(--tx)' }}>{displayCodigo}</span>
                </div>
                <div style={{ flex: 1, font: '400 12px/1.4 var(--ff-body)', color: 'var(--tx)' }}>
                  {displayNome}
                  {ja && <span style={{ marginLeft: 8, fontSize: 10, color: 'var(--ok)', font: '600 10px/1 var(--ff-body)' }}>✓ SELECIONADO</span>}
                </div>
                {!isSubclasse && (
                  <i data-lucide="chevron-right" style={{ width: 14, height: 14, color: 'var(--tx-3)', flexShrink: 0 }}></i>
                )}
              </div>
            );
          })}
        </div>

        {/* Rodapé */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          marginTop: 14, gap: 8,
        }}>
          <div style={{ font: '400 12px/1.4 var(--ff-body)', color: 'var(--tx-2)' }}>
            {cnaesSel.length === 0
              ? 'Nenhum CNAE selecionado'
              : cnaesSel.length + ' CNAE(s) selecionado(s)'}
          </div>
          <button className="btn btn-primary" onClick={onClose}>Concluir</button>
        </div>
      </div>
    </Modal>
  );
}

// ═══════════════════════════════════════════════════════
// COMPONENTE — Município autocomplete (API IBGE)
// ═══════════════════════════════════════════════════════
function MunicipioAutocomplete({ uf, value, onChange, cacheRef, inputStyle }) {
  const [sugestoes,    setSugestoes]    = useProspState([]);
  const [carregando,   setCarregando]   = useProspState(false);
  const [showDropdown, setShowDropdown] = useProspState(false);
  const debounceRef = useProspRef(null);
  const abortRef    = useProspRef(null);

  // Debounce + busca
  useProspEffect(function() {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (!uf) { setSugestoes([]); setShowDropdown(false); return; }
    if (!value || value.trim().length < 2) { setSugestoes([]); setShowDropdown(false); return; }

    debounceRef.current = setTimeout(function() {
      var aplicar = function(municipios) {
        var q = value.trim().toLowerCase();
        var filt = municipios
          .filter(function(m) { return m.nome.toLowerCase().indexOf(q) >= 0; })
          .slice(0, 10);
        setSugestoes(filt);
        setShowDropdown(filt.length > 0);
        setCarregando(false);
      };
      if (cacheRef.current[uf]) {
        aplicar(cacheRef.current[uf]);
      } else {
        setCarregando(true);
        // Cancela request anterior se ainda pendente
        if (abortRef.current) { try { abortRef.current.abort(); } catch(e) {} }
        var ctrl = new AbortController();
        abortRef.current = ctrl;
        fetch('https://servicodados.ibge.gov.br/api/v1/localidades/estados/' + uf + '/municipios', { signal: ctrl.signal })
          .then(function(r) {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
          })
          .then(function(data) {
            var list = (data || []).map(function(m) { return { nome: m.nome }; });
            cacheRef.current[uf] = list;
            aplicar(list);
          })
          .catch(function(err) {
            if (err && err.name === 'AbortError') return;
            setCarregando(false); setSugestoes([]); setShowDropdown(false);
          });
      }
    }, 300);

    return function() {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [value, uf]);

  var disabled = !uf;
  var inputStyleFinal = Object.assign({}, inputStyle, disabled ? {
    opacity: 0.55, cursor: 'not-allowed', background: 'var(--surface-2)',
  } : {});

  return (
    <div style={{ position: 'relative' }}>
      <input
        value={value}
        disabled={disabled}
        onChange={function(e) { onChange(e.target.value); }}
        onFocus={function() { if (sugestoes.length) setShowDropdown(true); }}
        onBlur={function() { setTimeout(function() { setShowDropdown(false); }, 150); }}
        placeholder={disabled ? 'Selecione UF primeiro' : 'Digite 2+ caracteres…'}
        style={inputStyleFinal} />
      {carregando && (
        <div style={{
          position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
          font: '400 10px/1 var(--ff-body)', color: 'var(--tx-3)', pointerEvents: 'none',
        }}>Buscando…</div>
      )}
      {showDropdown && sugestoes.length > 0 && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0,
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow-3)',
          zIndex: 50, maxHeight: 220, overflowY: 'auto',
        }}>
          {sugestoes.map(function(m, idx) {
            return (
              <div key={idx}
                /* onMouseDown garante seleção antes do onBlur do input */
                onMouseDown={function(ev) {
                  ev.preventDefault();
                  onChange(m.nome);
                  setShowDropdown(false);
                }}
                style={{
                  padding: '8px 11px',
                  borderBottom: '1px solid var(--border)',
                  cursor: 'pointer',
                  font: '400 12px/1.3 var(--ff-body)', color: 'var(--tx)',
                }}>
                {m.nome}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// COMPONENTE PRINCIPAL
// ═══════════════════════════════════════════════════════
function Prospeccao({ onNav, onAddCliente, onAddOportunidade, onAddProspects, onSilentAddToBdr }) {
  // ── Restauração de última busca (sessionStorage) ───
  // Lê 1× no mount via useRef + guarda. `snap` referencia o objeto
  // restaurado (ou null se nada salvo / falha de parse).
  const snapshotInitRef = useProspRef(null);
  if (snapshotInitRef.current === null) {
    snapshotInitRef.current = lerSnapshot() || { _none: true };
  }
  const snap = snapshotInitRef.current._none ? null : snapshotInitRef.current;
  const sf = (snap && snap.filtros) || {};

  // ── Filtros (controlados) — inicializados a partir do snapshot ──
  const [cnaesSel,        setCnaesSel]        = useProspState(sf.cnaesSel || []);
  const [uf,              setUf]              = useProspState(sf.uf || '');
  const [municipio,       setMunicipio]       = useProspState(sf.municipio || '');
  const [portes,          setPortes]          = useProspState(sf.portes || ['01','03','05']);
  // situacoes hardcoded — prospecção busca sempre só empresas Ativas (código '02')
  const [somenteMatrizes, setSomenteMatrizes] = useProspState(sf.somenteMatrizes !== undefined ? sf.somenteMatrizes : true);
  const [simples,         setSimples]         = useProspState(sf.simples || 'Todos');
  // Novos filtros
  const [buscaTexto,   setBuscaTexto]   = useProspState(sf.buscaTexto || '');
  const [matrizFilial, setMatrizFilial] = useProspState(sf.matrizFilial || 'todos');
  const [modoSocio,    setModoSocio]    = useProspState(false);
  const [modoBusca,    setModoBusca]    = useProspState(sf.modoBusca || 'contem'); // contem | igual | exato
  const [sortCol,      setSortCol]      = useProspState(null);                    // coluna ativa de ordenação
  const [sortDir,      setSortDir]      = useProspState('asc');                   // 'asc' | 'desc'
  const [prospBump,    setProspBump]    = useProspState(0);                       // força re-render ao alterar prospectados
  // AbortController para cancelar busca em andamento
  const buscaAbortRef = useProspRef(null);

  // ── Popup CNAE ─────────────────────────────────────
  const [cnaePopupOpen, setCnaePopupOpen] = useProspState(false);

  // ── Cache IBGE por UF (sessão) ─────────────────────
  const municipiosCacheRef = useProspRef({});

  // ── Busca / resultados (inicializa restaurado se houver snapshot) ──
  const [busca, setBusca] = useProspState(snap ? {
    iniciada: true, loading: false, resultados: snap.resultados || [], erro: null,
  } : {
    iniciada: false, loading: false, resultados: [], erro: null,
  });
  const [pagina, setPagina]       = useProspState((snap && snap.pagina) || 1);
  const [drawerEmp, setDrawerEmp] = useProspState(null);
  const [drawerAba, setDrawerAba] = useProspState('resumo'); // 'resumo' | 'publicos'

  // ── Aviso "última busca restaurada" ────────────────
  const [showRestoredBanner, setShowRestoredBanner] = useProspState(!!snap);

  // ── Seleção múltipla (Set de cnpj_raw) ─────────────
  const [selecionados, setSelecionados] = useProspState(function() { return new Set(); });

  // ── Responsividade ─────────────────────────────────
  const [vw, setVw] = useProspState(
    typeof window !== 'undefined' ? window.innerWidth : 1200
  );
  useProspEffect(function() {
    function onResize() { setVw(window.innerWidth); }
    window.addEventListener('resize', onResize);
    return function() { window.removeEventListener('resize', onResize); };
  }, []);
  const isMobile = vw < 860;

  // Recria ícones lucide após cada render (padrão CRM — try/catch defensivo)
  useProspEffect(function() {
    try { if (window.lucide) window.lucide.createIcons({ attrs: { 'stroke-width': 1.75 } }); }
    catch(e) { /* ignora */ }
  });

  // ── Helpers de toggle ──────────────────────────────
  function removerCnae(codigo) {
    setCnaesSel(function(prev) { return prev.filter(function(c) { return c !== codigo; }); });
  }
  function togglePorte(codigo) {
    setPortes(function(prev) {
      return prev.indexOf(codigo) >= 0
        ? prev.filter(function(c) { return c !== codigo; })
        : prev.concat([codigo]);
    });
  }


  // ── UF muda → limpa município (e dropdown) ─────────
  function handleUfChange(novoUf) {
    if (novoUf !== uf) setMunicipio('');
    setUf(novoUf);
  }

  function pararBusca() {
    if (buscaAbortRef.current) { try { buscaAbortRef.current.abort(); } catch(e) {} }
    setBusca(function(prev) { return Object.assign({}, prev, { loading: false }); });
  }

  function buscar() {
    // Cancela busca anterior se houver
    if (buscaAbortRef.current) { try { buscaAbortRef.current.abort(); } catch(e) {} }
    var ctrl = new AbortController();
    buscaAbortRef.current = ctrl;

    setShowRestoredBanner(false);
    setBusca({ iniciada: true, loading: true, resultados: [], erro: null });
    setPagina(1);
    setSelecionados(new Set());

    var filtrosState = { cnaesSel, uf, municipio, portes, situacoes: ['02'], somenteMatrizes, simples, buscaTexto, matrizFilial, modoBusca };
    var filtrosAPI = {
      q:               buscaTexto && buscaTexto.trim().length >= 2 ? buscaTexto.trim() : null,
      modo_busca:      modoBusca || 'contem',
      cnaes:           cnaesSel,
      uf:              uf,
      municipio:       municipio,
      portes:          portes,
      situacoes:       ['02'],   // sempre Ativa — filtro removido da UI
      matrizFilial:    matrizFilial,
      simples:         simples === 'Sim' ? 'S' : (simples === 'Não' ? 'N' : null),
    };

    // Detecta CNPJ: 14 dígitos (com ou sem formatação XX.XXX.XXX/XXXX-XX)
    var cnpjDigitos = buscaTexto.replace(/\D/g, '');
    var modoCnpj = cnpjDigitos.length === 14;

    var promessa = modoCnpj
      ? fetchCnpjDireto(buscaTexto, ctrl.signal).then(function(emp) {
          if (!emp) return [];
          return [Object.assign({}, emp, { _origem: 'cnpj' })];
        })
      : modoSocio && filtrosAPI.q
        ? fetchSociosBuscar(filtrosAPI.q, filtrosAPI, ctrl.signal).then(function(rows) {
            // Converte resultado de sócios para o formato de empresa
            return rows.map(function(r) {
              return Object.assign({}, r, {
                cnpj_raw: (r.cnpj_raw || '').replace(/\D/g, ''),
                _origem: 'socio',
              });
            });
          })
        : fetchProspeccao(filtrosAPI, 200, 0, ctrl.signal);

    promessa.then(function(lista) {
      if (ctrl.signal.aborted) return;
      setBusca({ iniciada: true, loading: false, resultados: lista, erro: null });
      salvarSnapshot({ filtros: filtrosState, resultados: lista, pagina: 1 });
    }).catch(function(e) {
      if (e && e.name === 'AbortError') return; // busca cancelada pelo usuário
      setBusca({ iniciada: true, loading: false, resultados: [], erro: e.message });
    });
  }

  function limpar() {
    if (buscaAbortRef.current) { try { buscaAbortRef.current.abort(); } catch(e) {} }
    setCnaesSel([]);
    setUf(''); setMunicipio('');
    setPortes(['01','02','03','04','05']);
    setSomenteMatrizes(true);
    setSimples('Todos');
    setBuscaTexto('');
    setMatrizFilial('todos');
    setModoSocio(false);
    setBusca({ iniciada: false, loading: false, resultados: [], erro: null });
    setPagina(1);
    setSelecionados(new Set());
    setShowRestoredBanner(false);
    limparSnapshot();
  }

  // ── Paginação ──────────────────────────────────────
  const POR_PAGINA   = 50;
  // Ordenação — aplicada sobre todos os resultados antes de paginar
  const resultadosSorted = (sortCol && busca.resultados.length) ? [...busca.resultados].sort(function(a, b) {
    if (sortCol === 'capital_social') {
      var va = typeof a.capital_social === 'number' ? a.capital_social : 0;
      var vb = typeof b.capital_social === 'number' ? b.capital_social : 0;
      return sortDir === 'asc' ? va - vb : vb - va;
    }
    var sa = '', sb = '';
    if (sortCol === 'municipio') {
      sa = (a.municipio_nome || '') + ' ' + (a.uf || '');
      sb = (b.municipio_nome || '') + ' ' + (b.uf || '');
    } else {
      sa = String(a[sortCol] || '').toUpperCase();
      sb = String(b[sortCol] || '').toUpperCase();
    }
    if (sa < sb) return sortDir === 'asc' ? -1 : 1;
    if (sa > sb) return sortDir === 'asc' ? 1 : -1;
    return 0;
  }) : busca.resultados;
  const total        = resultadosSorted.length;
  const totalPaginas = Math.max(1, Math.ceil(total / POR_PAGINA));
  const inicio       = (pagina - 1) * POR_PAGINA;
  const visiveis     = resultadosSorted.slice(inicio, inicio + POR_PAGINA);

  // Persiste página no snapshot quando muda (sem reescrever resultados/filtros)
  function mudarPagina(novaPagina) {
    setPagina(novaPagina);
    try {
      var raw = sessionStorage.getItem(PROSP_STORAGE_KEY);
      if (raw) {
        var data = JSON.parse(raw);
        data.pagina = novaPagina;
        sessionStorage.setItem(PROSP_STORAGE_KEY, JSON.stringify(data));
      }
    } catch(e) {}
  }

  // ── Seleção múltipla ───────────────────────────────
  function toggleSel(cnpj) {
    setSelecionados(function(prev) {
      var next = new Set(prev);
      if (next.has(cnpj)) next.delete(cnpj);
      else next.add(cnpj);
      return next;
    });
  }
  function toggleAllPagina() {
    setSelecionados(function(prev) {
      var next = new Set(prev);
      var todasMarcadas = visiveis.length > 0 && visiveis.every(function(e) { return next.has(e.cnpj_raw); });
      if (todasMarcadas) {
        visiveis.forEach(function(e) { next.delete(e.cnpj_raw); });
      } else {
        visiveis.forEach(function(e) { next.add(e.cnpj_raw); });
      }
      return next;
    });
  }
  function limparSelecao() { setSelecionados(new Set()); }

  function handleAddProspects() {
    if (typeof onAddProspects !== 'function') return;
    var mapa = {};
    busca.resultados.forEach(function(e) { mapa[e.cnpj_raw] = e; });
    var empresas = Array.from(selecionados).map(function(cnpj) { return mapa[cnpj]; }).filter(Boolean);
    if (empresas.length) onAddProspects(empresas);
  }

  var allMarcadasPagina    = visiveis.length > 0 && visiveis.every(function(e) { return selecionados.has(e.cnpj_raw); });
  var algumaMarcadaPagina  = visiveis.some(function(e) { return selecionados.has(e.cnpj_raw); });

  // ── Ações por linha ────────────────────────────────
  function handleAddCliente(emp) {
    if (typeof onAddCliente === 'function') onAddCliente(emp);
  }
  function handleAddOportunidade(emp) {
    var existente = clienteByCNPJ(emp.cnpj_raw);
    if (typeof onAddOportunidade === 'function') onAddOportunidade(emp, existente);
  }

  // ── Estilos inline reutilizados ────────────────────
  var inputStyle = {
    width: '100%', padding: '9px 11px',
    border: '1px solid var(--border-2)',
    borderRadius: 'var(--r-sm)', background: 'var(--surface)',
    fontFamily: 'var(--ff-body)', fontSize: 13, color: 'var(--tx)',
    outline: 'none', boxSizing: 'border-box',
  };
  var checkLabelStyle = {
    display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
    font: '400 12px/1 var(--ff-body)', color: 'var(--tx-2)',
  };
  var checkBoxStyle = { width: 14, height: 14, accentColor: 'var(--ok)', cursor: 'pointer' };

  return (
    <div data-screen-label="11 Prospecção"
      style={{ paddingBottom: selecionados.size > 0 ? 72 : 0 }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '320px 1fr',
        gap: 16,
        alignItems: 'start',
      }}>
        {/* ═══════════ PAINEL DE FILTROS ═══════════ */}
        <Panel title="Filtros">
          {/* Busca por nome / razão social / CNPJ */}
          <div className="f" style={{ marginBottom: 12 }}>
            <label>Busca
              <span className="hint"> · nome, razão social ou CNPJ</span>
            </label>
            <div style={{ display: 'flex', gap: 6 }}>
              <input
                type="text"
                value={buscaTexto}
                onChange={function(e){ setBuscaTexto(e.target.value); }}
                onKeyDown={function(e){ if (e.key === 'Enter') buscar(); }}
                placeholder="Nome, razão social ou CNPJ (14 dígitos)..."
                style={Object.assign({}, inputStyle, { flex: 1 })}
              />
              <select
                value={modoBusca}
                onChange={function(e){ setModoBusca(e.target.value); }}
                disabled={modoSocio || buscaTexto.replace(/\D/g,'').length === 14}
                title="Tipo de correspondência na busca por nome"
                style={Object.assign({}, inputStyle, { width: 'auto', flex: 'none', fontSize: 12, cursor: 'pointer' })}>
                <option value="contem">Contém</option>
                <option value="igual">É igual a</option>
                <option value="exato">Exato</option>
              </select>
            </div>
            {(function() {
              var d = buscaTexto.replace(/\D/g, '');
              if (d.length >= 8 && d.length <= 13) {
                return (
                  <div style={{ marginTop: 6, padding: '6px 10px', background: 'var(--warn-050,#fffbeb)', border: '1px solid var(--warn,#f59e0b)', borderRadius: 'var(--r-sm)', font: '400 11px/1.4 var(--ff-body)', color: 'var(--tx-2)' }}>
                    <i data-lucide="alert-triangle" style={{ width: 11, height: 11, verticalAlign: '-1px', marginRight: 4 }}></i>
                    CNPJ incompleto ({d.length}/14 dígitos). Para busca por CNPJ, informe os 14 dígitos completos.
                  </div>
                );
              }
              if (d.length === 14) {
                return (
                  <div style={{ marginTop: 6, padding: '6px 10px', background: 'var(--success-050,#f0fdf4)', border: '1px solid var(--grn,#22c55e)', borderRadius: 'var(--r-sm)', font: '400 11px/1.4 var(--ff-body)', color: 'var(--tx-2)' }}>
                    <i data-lucide="search" style={{ width: 11, height: 11, verticalAlign: '-1px', marginRight: 4 }}></i>
                    Modo CNPJ — busca exata. Os outros filtros são ignorados.
                  </div>
                );
              }
              return null;
            })()}
            <label style={Object.assign({}, checkLabelStyle, { marginTop: 8 })}>
              <input type="checkbox" checked={modoSocio}
                onChange={function(e){ setModoSocio(e.target.checked); }}
                style={checkBoxStyle} />
              <span>Buscar por <strong>nome do sócio</strong></span>
            </label>
            {modoSocio && (
              <div style={{ marginTop: 6, padding: '6px 10px', background: 'var(--info-050)', border: '1px solid var(--info)', borderRadius: 'var(--r-sm)', font: '400 11px/1.4 var(--ff-body)', color: 'var(--tx-2)' }}>
                <i data-lucide="info" style={{ width: 11, height: 11, verticalAlign: '-1px', marginRight: 4 }}></i>
                Modo sócio: os demais filtros (UF, CNAE, porte…) são aplicados normalmente para restringir os resultados.
              </div>
            )}
          </div>

          {/* CNAE — botão abre popup hierárquico */}
          <div className="f" style={{ marginBottom: 12 }}>
            <label>CNAE <span className="hint">· hierárquico</span></label>
            <button
              type="button"
              onClick={function() { setCnaePopupOpen(true); }}
              style={Object.assign({}, inputStyle, {
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                cursor: 'pointer', textAlign: 'left', gap: 8,
              })}>
              <span style={{ color: cnaesSel.length ? 'var(--tx)' : 'var(--tx-3)', flex: 1, font: '400 12px/1.2 var(--ff-body)' }}>
                {cnaesSel.length
                  ? cnaesSel.length + ' CNAE(s) selecionado(s)'
                  : 'Selecionar CNAE…'}
              </span>
              <i data-lucide="chevron-down" style={{ width: 14, height: 14, color: 'var(--tx-3)' }}></i>
            </button>
            {/* Chips dos CNAEs selecionados */}
            {cnaesSel.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                {cnaesSel.map(function(codigo) {
                  return (
                    <span key={codigo} title={(CNAE_BY_CODIGO[codigo] && CNAE_BY_CODIGO[codigo].desc) || codigo}
                      style={{
                        display: 'inline-flex', alignItems: 'center', gap: 6,
                        padding: '4px 6px 4px 10px',
                        background: 'var(--grn-050)', border: '1px solid var(--grn-100)',
                        borderRadius: 99, font: '500 11px/1 var(--ff-mono)', color: 'var(--tx)',
                      }}>
                      {cnaeLabel(codigo)}
                      <button onClick={function() { removerCnae(codigo); }}
                        title="Remover CNAE"
                        style={{
                          background: 'none', border: 'none', cursor: 'pointer',
                          width: 16, height: 16, padding: 0,
                          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                          color: 'var(--tx-3)',
                        }}>
                        <i data-lucide="x" style={{ width: 12, height: 12 }}></i>
                      </button>
                    </span>
                  );
                })}
              </div>
            )}
          </div>

          {/* UF */}
          <div className="f" style={{ marginBottom: 12 }}>
            <label>UF</label>
            <select value={uf} onChange={function(e) { handleUfChange(e.target.value); }} style={inputStyle}>
              <option value="">Todas</option>
              {UF_LIST.map(function(u) { return <option key={u} value={u}>{u}</option>; })}
            </select>
          </div>

          {/* Município — autocomplete IBGE (só ativa após UF) */}
          <div className="f" style={{ marginBottom: 12 }}>
            <label>
              Município
              <span className="hint">{uf ? ' · via IBGE' : ' · selecione UF'}</span>
            </label>
            <MunicipioAutocomplete
              uf={uf}
              value={municipio}
              onChange={setMunicipio}
              cacheRef={municipiosCacheRef}
              inputStyle={inputStyle} />
          </div>

          {/* Porte */}
          <div className="f" style={{ marginBottom: 12 }}>
            <label>Porte</label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4 }}>
              {PORTE_OPCOES.map(function(p) {
                var ck = portes.indexOf(p.codigo) >= 0;
                return (
                  <label key={p.codigo} style={checkLabelStyle}>
                    <input type="checkbox" checked={ck}
                      onChange={function() { togglePorte(p.codigo); }}
                      style={checkBoxStyle} />
                    {p.label}
                  </label>
                );
              })}
            </div>
          </div>

          {/* Tipo: matriz / filial / todos */}
          <div className="f" style={{ marginBottom: 12 }}>
            <label>Tipo de estabelecimento</label>
            <div style={{ display: 'flex', gap: 16, marginTop: 4 }}>
              {[['1','Só matrizes'],['2','Só filiais'],['todos','Todos']].map(function(op) {
                return (
                  <label key={op[0]} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer', font: '400 12px/1 var(--ff-body)', color: 'var(--tx-2)' }}>
                    <input type="radio" name="prosp_matriz" checked={matrizFilial === op[0]}
                      onChange={function(){ setMatrizFilial(op[0]); }}
                      style={checkBoxStyle} />
                    {op[1]}
                  </label>
                );
              })}
            </div>
          </div>

          {/* Simples Nacional */}
          <div className="f" style={{ marginBottom: 16 }}>
            <label>Simples Nacional</label>
            <div style={{ display: 'flex', gap: 12, marginTop: 4 }}>
              {['Todos','Sim','Não'].map(function(v) {
                return (
                  <label key={v} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
                    font: '400 12px/1 var(--ff-body)', color: 'var(--tx-2)',
                  }}>
                    <input type="radio" name="prosp_simples" checked={simples === v}
                      onChange={function() { setSimples(v); }}
                      style={checkBoxStyle} />
                    {v}
                  </label>
                );
              })}
            </div>
          </div>

          {/* Botões */}
          <div style={{ display: 'flex', gap: 8 }}>
            {busca.loading ? (
              <button className="btn" onClick={pararBusca}
                style={{ flex: 1, background: 'var(--warn)', borderColor: 'var(--warn)', color: '#fff' }}>
                <i data-lucide="square" style={{ width: 13, height: 13 }}></i> Parar busca
              </button>
            ) : (
              <button className="btn btn-primary" onClick={buscar} style={{ flex: 1 }}>
                <i data-lucide="search"></i> Buscar
              </button>
            )}
            <button className="btn btn-ghost" onClick={limpar} title="Reseta filtros e limpa busca salva">
              <i data-lucide="rotate-ccw"></i> Limpar
            </button>
          </div>
        </Panel>

        {/* ═══════════ PAINEL DE RESULTADOS ═══════════ */}
        <Panel
          title="Resultados"
          meta={busca.iniciada && !busca.loading
            ? (total + ' empresa' + (total !== 1 ? 's' : '') + ' encontrada' + (total !== 1 ? 's' : ''))
            : ''}
          actions={
            busca.iniciada && !busca.loading && total > 0 ? (
              <button className="btn btn-secondary"
                onClick={function() { exportarCSV(busca.resultados); }}
                style={{ fontSize: 12, padding: '6px 10px' }}>
                <i data-lucide="download" style={{ width: 13, height: 13 }}></i>
                Exportar CSV
              </button>
            ) : null
          }
          noPad
        >
          {/* Banner de "última busca restaurada" */}
          {showRestoredBanner && busca.iniciada && !busca.loading && (
            <div style={{
              padding: '8px 16px', background: 'var(--grn-050)', borderBottom: '1px solid var(--grn-100)',
              display: 'flex', alignItems: 'center', gap: 8,
              font: '400 12px/1.4 var(--ff-body)', color: 'var(--tx-2)',
            }}>
              <i data-lucide="history" style={{ width: 13, height: 13, color: 'var(--ok)' }}></i>
              <span>Última busca restaurada · <strong style={{ color: 'var(--tx)' }}>{total}</strong> resultado(s)</span>
              <button onClick={limpar}
                title="Resetar filtros e limpar busca salva"
                style={{
                  marginLeft: 'auto', background: 'none', border: '1px solid var(--border)',
                  borderRadius: 'var(--r-sm)', padding: '3px 8px', cursor: 'pointer',
                  font: '500 11px/1 var(--ff-body)', color: 'var(--tx-2)',
                }}>
                Limpar
              </button>
              <button onClick={function() { setShowRestoredBanner(false); }}
                title="Esconder aviso"
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  width: 22, height: 22, padding: 0,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--tx-3)',
                }}>
                <i data-lucide="x" style={{ width: 13, height: 13 }}></i>
              </button>
            </div>
          )}

          {/* Estado inicial */}
          {!busca.iniciada && (
            <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--tx-3)' }}>
              <i data-lucide="search" style={{ width: 28, height: 28, display: 'block', margin: '0 auto 12px' }}></i>
              <div style={{ font: '500 14px/1 var(--ff-body)', color: 'var(--tx-2)', marginBottom: 6 }}>
                Configure os filtros e clique em Buscar
              </div>
              <div style={{ fontSize: 12 }}>
                Encontre empresas pelos critérios da sua estratégia comercial.
              </div>
            </div>
          )}

          {/* Loading — mensagem + skeleton */}
          {busca.loading && (
            <div style={{ padding: '16px 24px' }}>
              {/* Banner de status */}
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 14px', marginBottom: 14,
                background: 'var(--surface-2)', border: '1px solid var(--border)',
                borderRadius: 'var(--r-md)', font: '500 13px/1 var(--ff-body)', color: 'var(--tx-2)'
              }}>
                <span style={{
                  display: 'inline-block', width: 14, height: 14,
                  border: '2px solid var(--tx-3)', borderTopColor: 'var(--accent)',
                  borderRadius: '50%', flexShrink: 0,
                  animation: 'bdrSpin 0.75s linear infinite',
                }} />
                Consultando base da Receita Federal
                <span style={{ letterSpacing: 2, animation: 'bdrDots 1.2s steps(4, end) infinite' }}>...</span>
              </div>
              {/* Skeleton rows */}
              {[0,1,2,3,4].map(function(i) {
                return (
                  <div key={i} style={{
                    height: 48, background: 'var(--surface-2)',
                    border: '1px solid var(--border)', borderRadius: 'var(--r-sm)',
                    marginBottom: 6, overflow: 'hidden', position: 'relative',
                  }}>
                    <div style={{
                      position: 'absolute', inset: 0,
                      background: 'linear-gradient(90deg, transparent 0%, var(--surface) 50%, transparent 100%)',
                      animation: 'crmLoad 1.4s ease-in-out infinite',
                      animationDelay: (i * 0.15) + 's',
                    }} />
                  </div>
                );
              })}
            </div>
          )}

          {/* Erro */}
          {busca.erro && !busca.loading && (
            <div style={{ padding: 24, color: 'var(--danger)', font: '400 13px/1.6 var(--ff-body)' }}>
              Erro ao buscar empresas: {busca.erro}
            </div>
          )}

          {/* Sem resultados */}
          {busca.iniciada && !busca.loading && total === 0 && !busca.erro && (
            <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--tx-3)' }}>
              <i data-lucide="search-x" style={{ width: 28, height: 28, display: 'block', margin: '0 auto 12px' }}></i>
              <div style={{ font: '500 14px/1 var(--ff-body)', color: 'var(--tx-2)', marginBottom: 6 }}>
                Nenhuma empresa encontrada para os filtros selecionados.
              </div>
              <div style={{ fontSize: 12 }}>
                Tente afrouxar — remova CNAEs, mude UF ou desmarque "Somente matrizes".
              </div>
            </div>
          )}

          {/* Resultados — tabela (desktop) */}
          {busca.iniciada && !busca.loading && total > 0 && !isMobile && (
            <React.Fragment>
              <div className="dt-wrap">
                <table className="dt">
                  <thead>
                    <tr>
                      <th style={{ width: 34, padding: '8px 4px 8px 12px' }}>
                        <input type="checkbox"
                          checked={allMarcadasPagina}
                          ref={function(el) {
                            if (el) el.indeterminate = !allMarcadasPagina && algumaMarcadaPagina;
                          }}
                          onChange={toggleAllPagina}
                          title={allMarcadasPagina ? 'Desmarcar página' : 'Marcar página'}
                          style={checkBoxStyle} />
                      </th>
                      <th>CNPJ</th>
                      {[
                        { col: 'razao_social',          label: 'Razão Social' },
                        { col: 'nome_fantasia',         label: 'Nome Fantasia' },
                        { col: 'municipio',             label: 'Município/UF' },
                        { col: 'porte',                 label: 'Porte' },
                        { col: null,                    label: 'Tipo' },
                        { col: 'cnae_principal',        label: 'CNAE' },
                        { col: 'capital_social',        label: 'Capital', right: true },
                        { col: 'data_inicio_atividade', label: 'Abertura' },
                      ].map(function(h) {
                        var ativo = sortCol === h.col;
                        var seta = !h.col ? '' : ativo ? (sortDir === 'asc' ? ' ↑' : ' ↓') : ' ↕';
                        return (
                          <th key={h.label}
                              onClick={h.col ? function() {
                                if (sortCol === h.col) setSortDir(function(d){ return d === 'asc' ? 'desc' : 'asc'; });
                                else { setSortCol(h.col); setSortDir('asc'); }
                              } : null}
                              style={Object.assign({ whiteSpace: 'nowrap' },
                                h.col ? { cursor: 'pointer', userSelect: 'none' } : {},
                                h.right ? { textAlign: 'right' } : {},
                                ativo ? { color: 'var(--grn)' } : {})}>
                            {h.label}<span style={{ opacity: ativo ? 1 : 0.35, fontSize: 10 }}>{seta}</span>
                          </th>
                        );
                      })}
                      <th style={{ textAlign: 'right' }}>Ações</th>
                    </tr>
                  </thead>
                  <tbody>
                    {visiveis.map(function(e) {
                      var ehMatriz = e.matriz_filial === '1';
                      var marcada  = selecionados.has(e.cnpj_raw);
                      return (
                        <tr key={e.cnpj_raw}
                          style={marcada ? { background: 'var(--grn-050)' } : null}>
                          <td style={{ width: 34, padding: '8px 4px 8px 12px' }}>
                            <input type="checkbox"
                              checked={marcada}
                              onChange={function() { toggleSel(e.cnpj_raw); }}
                              style={checkBoxStyle} />
                          </td>
                          <td><div style={{ font: '500 12px/1 var(--ff-mono)', color: 'var(--tx)' }}>{e.cnpj_formatado}</div></td>
                          <td>
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 5, flexWrap: 'wrap' }}>
                              <span style={{ font: '500 13px/1.2 var(--ff-body)', color: 'var(--tx)' }}>{e.razao_social}</span>
                              {clienteByCNPJ(e.cnpj_raw) && (
                                <span title="Ja e cliente no CRM" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '2px 6px', background: 'var(--ok-050)', border: '1px solid var(--ok)', borderRadius: 99, font: '500 10px/1 var(--ff-mono)', color: 'var(--grn-600)', whiteSpace: 'nowrap', marginTop: 1 }}>
                                  <i data-lucide="check-circle" style={{ width: 9, height: 9 }}></i> cliente
                                </span>
                              )}
                              {!clienteByCNPJ(e.cnpj_raw) && jaProspectado(e.cnpj_raw) && (
                                <span title="Ja foi prospectado no BDR" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '2px 6px', background: '#fef9ec', border: '1px solid var(--warn)', borderRadius: 99, font: '500 10px/1 var(--ff-mono)', color: '#8a5a00', whiteSpace: 'nowrap', marginTop: 1 }}>
                                  <i data-lucide="clock" style={{ width: 9, height: 9 }}></i> prospectado
                                </span>
                              )}
                              {e._origem === 'socio' && e.nome_socio && (
                                <span title={"Socio: " + e.nome_socio} style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '2px 6px', background: 'var(--info-050)', border: '1px solid var(--info)', borderRadius: 99, font: '500 10px/1 var(--ff-mono)', color: 'var(--info)', whiteSpace: 'nowrap', marginTop: 1 }}>
                                  <i data-lucide="user" style={{ width: 9, height: 9 }}></i> {(e.nome_socio || '').split(' ').slice(0,2).join(' ')}
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="tx2" style={{ fontSize: 12 }}>{e.nome_fantasia || (e._origem === 'socio' ? e.cnae_descricao || '—' : '—')}</td>
                          <td className="tx2" style={{ fontSize: 12 }}>{e.municipio_nome} · {e.uf}</td>
                          <td className="tx2" style={{ fontSize: 12 }}>{PORTE_MAP[e.porte] || '—'}</td>
                          <td>
                            <span className={'b ' + (ehMatriz ? 'bi' : 'bx')}>
                              <span className="b-dot"></span>{ehMatriz ? 'Matriz' : 'Filial'}
                            </span>
                          </td>
                          <td className="tx2" style={{ fontSize: 11, fontFamily: 'var(--ff-mono)' }}>{e.cnae_principal}</td>
                          <td className="num">{typeof e.capital_social === 'number' ? fR(e.capital_social) : '—'}</td>
                          <td className="tx2" style={{ fontSize: 11, fontFamily: 'var(--ff-mono)' }}>{fmtDataReceita(e.data_inicio_atividade)}</td>
                          <td style={{ textAlign: 'right' }}>
                            <div style={{ display: 'inline-flex', gap: 4 }}>
                              <button className="btn btn-ghost" title="Ver detalhes"
                                onClick={function() { setDrawerAba('resumo'); setDrawerEmp(e); }}
                                style={{ padding: '4px 7px' }}>
                                <i data-lucide="eye" style={{ width: 13, height: 13 }}></i>
                              </button>
                              <button className="btn btn-ghost" title="Adicionar como cliente"
                                onClick={function() { handleAddCliente(e); }}
                                style={{ padding: '4px 7px' }}>
                                <i data-lucide="user-plus" style={{ width: 13, height: 13 }}></i>
                              </button>
                              <button className="btn btn-ghost" title="Adicionar oportunidade"
                                onClick={function() { handleAddOportunidade(e); }}
                                style={{ padding: '4px 7px' }}>
                                <i data-lucide="target" style={{ width: 13, height: 13 }}></i>
                              </button>
                              {!clienteByCNPJ(e.cnpj_raw) && (
                                <button className="btn btn-ghost"
                                  title={jaProspectado(e.cnpj_raw) ? 'Remover dos prospectados' : 'Enviar para o BDR'}
                                  onClick={(function(_e) { return function() {
                                    if (!jaProspectado(_e.cnpj_raw)) {
                                      // Primeiro clique → marca + envia ao BDR silenciosamente
                                      toggleProspectado(_e.cnpj_raw);
                                      if (typeof onSilentAddToBdr === 'function') {
                                        onSilentAddToBdr(_e);
                                        var nome = _e.razao_social ? _e.razao_social.split(' ').slice(0,3).join(' ') : _e.cnpj_raw;
                                        if (typeof window.showCrmToast === 'function') window.showCrmToast(nome + ' enviado ao BDR', 'ok');
                                      }
                                    } else {
                                      // Segundo clique → apenas desmarca (card permanece no BDR)
                                      toggleProspectado(_e.cnpj_raw);
                                    }
                                    setProspBump(function(b){ return b+1; });
                                  }; })(e)}
                                  style={{ padding: '4px 7px', color: jaProspectado(e.cnpj_raw) ? 'var(--warn)' : undefined }}>
                                  <i data-lucide="bookmark" style={{ width: 13, height: 13, fill: jaProspectado(e.cnpj_raw) ? 'var(--warn)' : 'none' }}></i>
                                </button>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              {/* Paginação */}
              {totalPaginas > 1 && (
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '12px 16px', borderTop: '1px solid var(--border)',
                  font: '500 12px/1 var(--ff-body)', color: 'var(--tx-2)',
                }}>
                  <div>Página {pagina} de {totalPaginas} · {total} resultado(s)</div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button className="btn btn-ghost"
                      disabled={pagina === 1}
                      onClick={function() { mudarPagina(Math.max(1, pagina - 1)); }}
                      style={{ padding: '4px 10px' }}>
                      <i data-lucide="chevron-left" style={{ width: 13, height: 13 }}></i> Anterior
                    </button>
                    <button className="btn btn-ghost"
                      disabled={pagina === totalPaginas}
                      onClick={function() { mudarPagina(Math.min(totalPaginas, pagina + 1)); }}
                      style={{ padding: '4px 10px' }}>
                      Próxima <i data-lucide="chevron-right" style={{ width: 13, height: 13 }}></i>
                    </button>
                  </div>
                </div>
              )}
            </React.Fragment>
          )}

          {/* Resultados — cards (mobile) */}
          {busca.iniciada && !busca.loading && total > 0 && isMobile && (
            <React.Fragment>
              {/* Header com "marcar todos da página" no mobile */}
              <div style={{
                display: 'flex', alignItems: 'center', gap: 8,
                padding: '10px 16px', borderBottom: '1px solid var(--border)',
                background: 'var(--surface-2)',
                font: '500 12px/1 var(--ff-body)', color: 'var(--tx-2)',
              }}>
                <input type="checkbox"
                  checked={allMarcadasPagina}
                  ref={function(el) {
                    if (el) el.indeterminate = !allMarcadasPagina && algumaMarcadaPagina;
                  }}
                  onChange={toggleAllPagina}
                  style={checkBoxStyle} />
                Marcar todos desta página
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: 16 }}>
                {visiveis.map(function(e) {
                  var ehMatriz = e.matriz_filial === '1';
                  var marcada  = selecionados.has(e.cnpj_raw);
                  return (
                    <div key={e.cnpj_raw} style={{
                      background: marcada ? 'var(--grn-050)' : 'var(--surface-2)',
                      border: '1px solid ' + (marcada ? 'var(--grn-100)' : 'var(--border)'),
                      borderRadius: 'var(--r-md)', padding: '12px 14px',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                        <input type="checkbox"
                          checked={marcada}
                          onChange={function() { toggleSel(e.cnpj_raw); }}
                          style={Object.assign({}, checkBoxStyle, { marginTop: 2 })} />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ font: '500 13px/1.3 var(--ff-body)', color: 'var(--tx)' }}>{e.razao_social}</div>
                              <div style={{ font: '400 11px/1 var(--ff-mono)', color: 'var(--tx-3)', marginTop: 3 }}>{e.cnpj_formatado}</div>
                            </div>
                            <span className={'b ' + (ehMatriz ? 'bi' : 'bx')} style={{ flexShrink: 0 }}>
                              <span className="b-dot"></span>{ehMatriz ? 'Matriz' : 'Filial'}
                            </span>
                          </div>
                          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 10, font: '400 11px/1.4 var(--ff-body)', color: 'var(--tx-2)' }}>
                            <div><strong style={{ color: 'var(--tx-3)' }}>Município:</strong> {e.municipio_nome} · {e.uf}</div>
                            <div><strong style={{ color: 'var(--tx-3)' }}>Porte:</strong> {PORTE_MAP[e.porte] || '—'}</div>
                            <div><strong style={{ color: 'var(--tx-3)' }}>CNAE:</strong> {e.cnae_principal}</div>
                            <div><strong style={{ color: 'var(--tx-3)' }}>Capital:</strong> {typeof e.capital_social === 'number' ? fR(e.capital_social) : '—'}</div>
                          </div>
                          <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
                            <button className="btn btn-ghost"
                              onClick={function() { setDrawerAba('resumo'); setDrawerEmp(e); }}
                              style={{ flex: 1, fontSize: 11, padding: '6px 8px' }}>
                              <i data-lucide="eye" style={{ width: 12, height: 12 }}></i> Detalhes
                            </button>
                            <button className="btn btn-ghost"
                              onClick={function() { handleAddCliente(e); }}
                              style={{ flex: 1, fontSize: 11, padding: '6px 8px' }}>
                              <i data-lucide="user-plus" style={{ width: 12, height: 12 }}></i> Cliente
                            </button>
                            <button className="btn btn-ghost"
                              onClick={function() { handleAddOportunidade(e); }}
                              style={{ flex: 1, fontSize: 11, padding: '6px 8px' }}>
                              <i data-lucide="target" style={{ width: 12, height: 12 }}></i> Oport.
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
              {totalPaginas > 1 && (
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '12px 16px', borderTop: '1px solid var(--border)',
                  font: '500 12px/1 var(--ff-body)', color: 'var(--tx-2)',
                }}>
                  <div>Pág. {pagina}/{totalPaginas}</div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button className="btn btn-ghost"
                      disabled={pagina === 1}
                      onClick={function() { mudarPagina(Math.max(1, pagina - 1)); }}
                      style={{ padding: '4px 8px' }}>
                      <i data-lucide="chevron-left" style={{ width: 12, height: 12 }}></i>
                    </button>
                    <button className="btn btn-ghost"
                      disabled={pagina === totalPaginas}
                      onClick={function() { mudarPagina(Math.min(totalPaginas, pagina + 1)); }}
                      style={{ padding: '4px 8px' }}>
                      <i data-lucide="chevron-right" style={{ width: 12, height: 12 }}></i>
                    </button>
                  </div>
                </div>
              )}
            </React.Fragment>
          )}
        </Panel>
      </div>

      {/* ═══════════ POPUP CNAE HIERÁRQUICO ═══════════ */}
      <CnaeHierarquicoPopup
        open={cnaePopupOpen}
        onClose={function() { setCnaePopupOpen(false); }}
        cnaesSel={cnaesSel}
        onChange={setCnaesSel} />

      {/* ═══════════ DRAWER DE DETALHES (Modal wide) ═══════════ */}
      <Modal
        open={!!drawerEmp}
        onClose={function() { setDrawerEmp(null); }}
        title={drawerEmp ? drawerEmp.razao_social : ''}
        subtitle={drawerEmp ? (drawerEmp.cnpj_formatado + ' · ' + drawerEmp.municipio_nome + '/' + drawerEmp.uf) : ''}
        wide
      >
        {drawerEmp && (
          <div>
            {/* Abas */}
            <div style={{ display: 'flex', gap: 2, marginBottom: 16, borderBottom: '1px solid var(--border)', paddingBottom: 0 }}>
              {[['resumo', 'Resumo'], ['publicos', 'Dados Públicos RF']].map(function(ab) {
                var ativo = drawerAba === ab[0];
                return (
                  <button key={ab[0]} onClick={function() { setDrawerAba(ab[0]); }}
                    style={{
                      all: 'unset', cursor: 'pointer', padding: '8px 14px',
                      font: '500 12px/1 var(--ff-body)',
                      color: ativo ? 'var(--accent)' : 'var(--tx-3)',
                      borderBottom: ativo ? '2px solid var(--accent)' : '2px solid transparent',
                      marginBottom: -1,
                    }}>
                    {ab[1]}
                  </button>
                );
              })}
            </div>

            {drawerAba === 'publicos' ? (
              <DadosPublicosTab cnpj={drawerEmp.cnpj_raw} onNav={onNav} />
            ) : (
              <div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
                  {[
                    ['Nome fantasia',      drawerEmp.nome_fantasia || '—'],
                    ['Tipo',               drawerEmp.matriz_filial === '1' ? 'Matriz' : 'Filial'],
                    ['Situação cadastral', SITUACAO_MAP[drawerEmp.situacao_cadastral] || '—'],
                    ['Data de abertura',   fmtDataReceita(drawerEmp.data_inicio_atividade)],
                    ['Porte',              PORTE_MAP[drawerEmp.porte] || '—'],
                    ['Capital social',     typeof drawerEmp.capital_social === 'number' ? fR(drawerEmp.capital_social) : '—'],
                    ['CNAE principal',     drawerEmp.cnae_principal],
                    ['CNAE — descrição',   drawerEmp.cnae_descricao],
                    ['Simples Nacional',   drawerEmp.opcao_simples === 'S' ? 'Sim' : 'Não'],
                    ['MEI',               drawerEmp.opcao_mei === 'S' ? 'Sim' : 'Não'],
                  ].map(function(par) {
                    return (
                      <div key={par[0]} style={{
                        background: 'var(--surface-2)', border: '1px solid var(--border)',
                        borderRadius: 'var(--r-md)', padding: '8px 12px',
                      }}>
                        <div style={{ font: '600 10px/1 var(--ff-body)', textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--tx-3)', marginBottom: 4 }}>
                          {par[0]}
                        </div>
                        <div style={{ font: '400 12px/1.3 var(--ff-mono)', color: 'var(--tx)' }}>
                          {par[1]}
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* Status: já é cliente? */}
                {(function() {
                  var existente = clienteByCNPJ(drawerEmp.cnpj_raw);
                  return existente ? (
                    <div style={{
                      padding: '10px 14px', background: 'var(--grn-050)', border: '1px solid var(--grn-100)',
                      borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center', gap: 8,
                      marginBottom: 14, font: '500 12px/1.4 var(--ff-body)', color: 'var(--tx-2)',
                    }}>
                      <i data-lucide="check-circle" style={{ width: 14, height: 14, color: 'var(--ok)' }}></i>
                      Empresa já cadastrada como cliente: <strong style={{ color: 'var(--tx)' }}>{existente.razao}</strong>
                    </div>
                  ) : (
                    <div style={{
                      padding: '10px 14px', background: 'var(--surface-2)', border: '1px solid var(--border)',
                      borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center', gap: 8,
                      marginBottom: 14, font: '400 12px/1.4 var(--ff-body)', color: 'var(--tx-3)',
                    }}>
                      <i data-lucide="info" style={{ width: 14, height: 14 }}></i>
                      Empresa ainda não cadastrada no CRM. Use "Add cliente" para criar.
                    </div>
                  );
                })()}

                {/* Ações */}
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                  <button className="btn btn-ghost" onClick={function() { setDrawerEmp(null); }}>Fechar</button>
                  <button className="btn btn-secondary"
                    onClick={function() { var e = drawerEmp; setDrawerEmp(null); handleAddCliente(e); }}>
                    <i data-lucide="user-plus"></i> Add cliente
                  </button>
                  <button className="btn btn-primary"
                    onClick={function() { var e = drawerEmp; setDrawerEmp(null); handleAddOportunidade(e); }}>
                    <i data-lucide="target"></i> Add oportunidade
                  </button>
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* ═══════════ BARRA FLUTUANTE — SELEÇÃO MÚLTIPLA ═══════════ */}
      {selecionados.size > 0 && (
        <div style={{
          position: 'fixed', bottom: 0, left: 0, right: 0,
          background: 'var(--surface)',
          borderTop: '1px solid var(--border)',
          boxShadow: '0 -4px 12px rgba(0,0,0,.08)',
          padding: isMobile ? '10px 14px' : '12px 24px',
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          alignItems: isMobile ? 'stretch' : 'center',
          justifyContent: 'space-between',
          gap: isMobile ? 8 : 12,
          zIndex: 100,
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            font: '500 13px/1.4 var(--ff-body)', color: 'var(--tx)',
          }}>
            <i data-lucide="check-square" style={{ width: 15, height: 15, color: 'var(--ok)' }}></i>
            <span>{selecionados.size} empresa{selecionados.size !== 1 ? 's' : ''} selecionada{selecionados.size !== 1 ? 's' : ''}</span>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: isMobile ? 'space-between' : 'flex-end' }}>
            <button className="btn btn-ghost" onClick={limparSelecao}
              style={isMobile ? { flex: 1, justifyContent: 'center' } : null}>
              <i data-lucide="x" style={{ width: 13, height: 13 }}></i>
              Limpar seleção
            </button>
            {selecionados.size < total && total > 0 && (
              <button className="btn btn-secondary"
                onClick={function() {
                  var todos = new Set(busca.resultados.map(function(e){ return e.cnpj_raw; }));
                  setSelecionados(todos);
                }}
                style={isMobile ? { flex: 1, justifyContent: 'center' } : null}>
                <i data-lucide="check-square" style={{ width: 13, height: 13 }}></i>
                Todos ({total})
              </button>
            )}
            <button className="btn btn-primary" onClick={handleAddProspects}
              style={isMobile ? { flex: 2, justifyContent: 'center' } : null}>
              <i data-lucide="user-plus" style={{ width: 13, height: 13 }}></i>
              Adicionar como prospects no BDR
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

window.Prospeccao = Prospeccao;
