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

// ── Group modal ─────────────────────────────────────────────────────────────
const GRUPO_PER_PAGE = 7;

function EmpGrupoModal({ grupo, onClose, onUpdate, onDelete, onAddAllToExclusao }) {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const btnPrimary = window.btnPrimary, btnDanger = window.btnDanger, btnSoft = window.btnSoft;
  const [empresas, setEmpresas] = useState(grupo.empresas ? [...grupo.empresas] : []);
  const [busca, setBusca] = useState('');
  const [page, setPage] = useState(1);

  useEffect(() => { setPage(1); }, [busca]);

  const remove = (idx) => {
    const next = empresas.filter((_, i) => i !== idx);
    setEmpresas(next);
    onUpdate({ ...grupo, empresas: next });
  };

  const filtradas = busca.trim()
    ? empresas.filter(e => e.nome.toLowerCase().includes(busca.toLowerCase()) || String(e.id).includes(busca))
    : empresas;

  const totalPages = Math.max(1, Math.ceil(filtradas.length / GRUPO_PER_PAGE));
  const pg = Math.min(page, totalPages);
  const paginadas = filtradas.slice((pg - 1) * GRUPO_PER_PAGE, pg * GRUPO_PER_PAGE);

  const navBtn = (disabled) => ({
    background: 'transparent', border: `1px solid ${MX.border}`, borderRadius: 7,
    padding: '3px 10px', cursor: disabled ? 'default' : 'pointer',
    color: disabled ? MX.dim : MX.text, fontSize: 15, opacity: disabled ? 0.35 : 1, lineHeight: 1.6,
  });

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 8500, background: 'rgba(20,20,30,0.42)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ ...card, width: 500, maxWidth: '93vw', maxHeight: '82vh', display: 'flex', flexDirection: 'column', overflow: 'hidden', animation: 'modalIn 0.22s ease', boxShadow: '0 32px 80px rgba(20,20,30,0.20)' }}>

        {/* Header fixo */}
        <div style={{ padding: '24px 28px 16px', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
            <div>
              <div style={{ fontSize: 17, fontWeight: 700, color: MX.text, letterSpacing: '-0.01em' }}>Gerenciar grupo</div>
              <div style={{ fontSize: 13, color: MX.muted, marginTop: 3 }}>
                {grupo.nomeGrupo}
                <span style={{ marginLeft: 8, background: MX.surface3, color: MX.dim, borderRadius: 20, padding: '1px 8px', fontSize: 11.5, fontWeight: 600 }}>
                  {empresas.length} empresa{empresas.length !== 1 ? 's' : ''}
                </span>
              </div>
            </div>
            <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.dim, fontSize: 22, lineHeight: 1 }}>✕</button>
          </div>
          <input
            className="mx-input"
            placeholder="Buscar por nome ou ID…"
            value={busca}
            onChange={e => setBusca(e.target.value)}
            style={{ width: '100%', padding: '9px 14px', borderRadius: 9, border: `1px solid ${MX.border}`, background: MX.surface, fontSize: 13, color: MX.text, outline: 'none', boxSizing: 'border-box' }}
          />
        </div>

        {/* Lista fixa — sem scroll, altura exata de GRUPO_PER_PAGE linhas */}
        <div style={{ flex: 1, minHeight: 0, padding: '0 28px', overflowY: 'auto' }}>
          {empresas.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '32px 0', color: MX.dim, fontSize: 13.5 }}>Grupo vazio.</div>
          ) : filtradas.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '32px 0', color: MX.dim, fontSize: 13.5 }}>Nenhum resultado para "{busca}".</div>
          ) : (
            <div style={{ border: `1px solid ${MX.border}`, borderRadius: 12, overflow: 'hidden' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
                <thead><tr><th style={thStyle}>Empresa</th><th style={{ ...thStyle, width: 50, textAlign: 'center' }}></th></tr></thead>
                <tbody>
                  {paginadas.map((emp, pos) => {
                    const origIdx = empresas.indexOf(emp);
                    return (
                      <tr key={emp.id} style={{ borderBottom: pos === paginadas.length - 1 ? 'none' : `1px solid ${MX.border}` }}>
                        <td style={{ padding: '10px 22px' }}>
                          <div style={{ fontWeight: 500, color: MX.text }}>{emp.nome}</div>
                          <div style={{ fontSize: 11.5, color: MX.dim, marginTop: 2 }} className="mono">ID: {emp.id}</div>
                        </td>
                        <td style={{ padding: '10px 22px', textAlign: 'center' }}>
                          <button onClick={() => remove(origIdx)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.red, fontSize: 16, lineHeight: 1 }}>✕</button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}

          {/* Paginação */}
          {totalPages > 1 && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 2px 4px' }}>
              <span style={{ fontSize: 12, color: MX.dim }}>
                {(pg - 1) * GRUPO_PER_PAGE + 1}–{Math.min(pg * GRUPO_PER_PAGE, filtradas.length)} de {filtradas.length}
              </span>
              <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={pg === 1} style={navBtn(pg === 1)}>‹</button>
                <span style={{ fontSize: 12, color: MX.muted, minWidth: 64, textAlign: 'center' }}>pág. {pg} / {totalPages}</span>
                <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={pg === totalPages} style={navBtn(pg === totalPages)}>›</button>
              </div>
            </div>
          )}
        </div>

        {/* Footer fixo */}
        <div style={{ padding: '16px 28px 24px', flexShrink: 0, borderTop: `1px solid ${MX.border}`, display: 'flex', gap: 10, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
          {onAddAllToExclusao && (
            <button onClick={onAddAllToExclusao} style={{ ...btnSoft, fontSize: 13 }}>Adicionar à exclusão</button>
          )}
          <button onClick={onDelete} style={{ ...btnDanger, fontSize: 13 }}>Excluir grupo</button>
          <button onClick={onClose} style={btnPrimary}>Fechar</button>
        </div>
      </div>
    </div>
  );
}

// ── Exclusion modal ─────────────────────────────────────────────────────────
const EXCL_PER_PAGE = 7;

function EmpExclusaoModal({ exclusoes, busca, onBuscaChange, onAdd, onRemove, onClearAll, onClose }) {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const styleInput = window.styleInput, btnSoft = window.btnSoft, btnDanger = window.btnDanger, btnPrimary = window.btnPrimary;
  const [page, setPage] = useState(1);

  useEffect(() => { setPage(1); }, [exclusoes.length]);

  const totalPages = Math.max(1, Math.ceil(exclusoes.length / EXCL_PER_PAGE));
  const pg = Math.min(page, totalPages);
  const paginados = exclusoes.slice((pg - 1) * EXCL_PER_PAGE, pg * EXCL_PER_PAGE);

  const navBtn = (disabled) => ({
    background: 'transparent', border: `1px solid ${MX.border}`, borderRadius: 7,
    padding: '3px 10px', cursor: disabled ? 'default' : 'pointer',
    color: disabled ? MX.dim : MX.text, fontSize: 15, opacity: disabled ? 0.35 : 1, lineHeight: 1.6,
  });

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 8500, background: 'rgba(20,20,30,0.42)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ ...card, width: 540, maxWidth: '93vw', maxHeight: '82vh', display: 'flex', flexDirection: 'column', overflow: 'hidden', animation: 'modalIn 0.22s ease', boxShadow: '0 32px 80px rgba(20,20,30,0.20)' }}>

        {/* Header fixo */}
        <div style={{ padding: '24px 28px 16px', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
            <div>
              <div style={{ fontSize: 17, fontWeight: 700, color: MX.text, letterSpacing: '-0.01em' }}>Lista de exclusão</div>
              <div style={{ fontSize: 13, color: MX.muted, marginTop: 3 }}>
                Empresas ignoradas pelos filtros
                {exclusoes.length > 0 && (
                  <span style={{ marginLeft: 8, background: MX.surface3, color: MX.dim, borderRadius: 20, padding: '1px 8px', fontSize: 11.5, fontWeight: 600 }}>
                    {exclusoes.length} empresa{exclusoes.length !== 1 ? 's' : ''}
                  </span>
                )}
              </div>
            </div>
            <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.dim, fontSize: 22, lineHeight: 1 }}>✕</button>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input className="mx-input" placeholder="Buscar empresa por nome ou ID…"
              value={busca} onChange={e => onBuscaChange(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && onAdd()}
              style={{ ...styleInput, flex: 1 }} />
            <button onClick={onAdd} style={{ ...btnSoft, fontSize: 13 }}>Adicionar</button>
          </div>
        </div>

        {/* Lista */}
        <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '0 28px' }}>
          {exclusoes.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '36px 0', color: MX.dim, fontSize: 13.5 }}>Nenhuma empresa na lista.</div>
          ) : (
            <>
              <div style={{ border: `1px solid ${MX.border}`, borderRadius: 12, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
                  <thead><tr><th style={thStyle}>Nome</th><th style={thStyle}>ID</th><th style={{ ...thStyle, width: 44 }}></th></tr></thead>
                  <tbody>
                    {paginados.map((item, pos) => (
                      <tr key={item._id} style={{ borderBottom: pos === paginados.length - 1 ? 'none' : `1px solid ${MX.border}` }}>
                        <td style={{ padding: '10px 22px', fontWeight: 500, color: MX.text }}>{item.nome_da_empresa}</td>
                        <td style={{ padding: '10px 22px', color: MX.muted }} className="mono">#{item.id}</td>
                        <td style={{ padding: '10px 22px', textAlign: 'center' }}>
                          <button onClick={() => onRemove(item._id)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.red, fontSize: 16, lineHeight: 1 }}>✕</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {totalPages > 1 && (
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 2px 4px' }}>
                  <span style={{ fontSize: 12, color: MX.dim }}>
                    {(pg - 1) * EXCL_PER_PAGE + 1}–{Math.min(pg * EXCL_PER_PAGE, exclusoes.length)} de {exclusoes.length}
                  </span>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                    <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={pg === 1} style={navBtn(pg === 1)}>‹</button>
                    <span style={{ fontSize: 12, color: MX.muted, minWidth: 64, textAlign: 'center' }}>pág. {pg} / {totalPages}</span>
                    <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={pg === totalPages} style={navBtn(pg === totalPages)}>›</button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer fixo */}
        <div style={{ padding: '16px 28px 24px', flexShrink: 0, borderTop: `1px solid ${MX.border}`, display: 'flex', gap: 10, justifyContent: exclusoes.length > 0 ? 'space-between' : 'flex-end', alignItems: 'center', flexWrap: 'wrap' }}>
          {exclusoes.length > 0 && onClearAll && (
            <button onClick={onClearAll} style={{ ...btnDanger, fontSize: 13 }}>Limpar tudo</button>
          )}
          <button onClick={onClose} style={btnPrimary}>Fechar</button>
        </div>
      </div>
    </div>
  );
}

// ── Main page ───────────────────────────────────────────────────────────────
function EmpresasPage({ empresas, setEmpresas, categorias, cidade, gruposEmpresas, onSaveGrupo, onUpdateGrupo, onDeleteGrupo, exclusaoEmpresas, onAddExclusao, onRemoveExclusao, isLoading }) {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const styleInput = window.styleInput, btnPrimary = window.btnPrimary, btnGhost = window.btnGhost, btnSoft = window.btnSoft, btnDanger = window.btnDanger;
  const EmpresaStatusBadge = window.EmpresaStatusBadge, CatChip = window.CatChip;
  const SkeletonTable = window.SkeletonTable;

  const [selectedRows,    setSelectedRows]    = useState([]);
  const [filterText,      setFilterText]      = useState('');
  const [filterCat,       setFilterCat]       = useState('');
  const [filterStatus,    setFilterStatus]    = useState('');
  const [novaCategoria,   setNovaCategoria]   = useState('');
  const [novoStatus,      setNovoStatus]      = useState('');
  const [processing,      setProcessing]      = useState(false);
  const [selectedGrupo,   setSelectedGrupo]   = useState('');
  const [salvarCheck,     setSalvarCheck]     = useState(false);
  const [nomeGrupo,       setNomeGrupo]       = useState('');
  const [showGrupoModal,  setShowGrupoModal]  = useState(false);
  const [grupoModalData,  setGrupoModalData]  = useState(null);
  const [showExclusao,    setShowExclusao]    = useState(false);
  const [exclusaoBusca,   setExclusaoBusca]   = useState('');
  const [currentPage,     setCurrentPage]     = useState(1);

  // Reset para página 1 sempre que os filtros mudarem
  useEffect(() => { setCurrentPage(1); }, [filterText, filterCat, filterStatus]);

  const excludedIds = useMemo(() => exclusaoEmpresas.map(e => String(e.id)), [exclusaoEmpresas]);
  const filtered = useMemo(() => empresas.filter(emp => {
    if (excludedIds.includes(String(emp.id))) return false;
    const txt = filterText.toLowerCase();
    const matchTxt = !txt || emp.nome.toLowerCase().includes(txt) || String(emp.id).includes(txt);
    const matchCat = !filterCat || emp.categorias.map(String).includes(filterCat);
    const matchSt  = !filterStatus || emp.status_empresa === filterStatus;
    return matchTxt && matchCat && matchSt;
  }), [empresas, filterText, filterCat, filterStatus, excludedIds]);

  const getCatName = useCallback((id) => (categorias.find(c => c.id === id) || {}).nome || `Cat ${id}`, [categorias]);
  const selectedIds = selectedRows.map(r => r.id);
  const toggleRow = useCallback((emp) => {
    setSelectedRows(prev => prev.find(r => r.id === emp.id) ? prev.filter(r => r.id !== emp.id) : [...prev, emp]);
  }, []);
  const selecionarTodos = useCallback(() => {
    setSelectedRows(prev => { const n = [...prev]; filtered.forEach(e => { if (!n.find(r => r.id === e.id)) n.push(e); }); return n; });
    window.showToast && window.showToast({ message: `${filtered.length} empresas selecionadas.`, type: 'info' });
  }, [filtered]);

  const clearSelected = useCallback(() => { setSelectedRows([]); setSalvarCheck(false); setNomeGrupo(''); }, []);

  const aplicarCategoria = useCallback(async () => {
    setProcessing(true);
    try {
      const catId = parseInt(novaCategoria);
      const ids = selectedRows.map(r => r.id);
      
      const response = await window.API.updateEmpresas(ids, [catId], selectedRows.map(r => r.nome), cidade);
      
      if (response && response.success) {
        setEmpresas(prev => prev.map(e => ids.includes(e.id) ? { ...e, categorias: [catId] } : e));
        window.addLog && window.addLog({ _id: 'l' + Date.now(), dataHora: new Date().toISOString(), tipo: 'empresa', entidade: selectedRows.map(r => r.nome).join(', '), acao: `Categoria alterada → ${getCatName(catId)}`, sucesso: true, usuario: 'admin@movixpress.com' });
        window.showToast && window.showToast({ message: `Categoria "${getCatName(catId)}" aplicada em ${ids.length} empresa(s)!`, type: 'success' });
        clearSelected(); 
        setNovaCategoria('');
      } else {
        throw new Error(response.error || 'Erro desconhecido');
      }
    } catch (error) {
      console.error(error);
      window.showToast && window.showToast({ message: `Erro ao aplicar a categoria: ${error.message}`, type: 'error' });
    } finally {
      setProcessing(false);
    }
  }, [novaCategoria, selectedRows, getCatName, setEmpresas, clearSelected]);

  const aplicarStatus = useCallback(async () => {
    setProcessing(true);
    try {
      const ids = selectedRows.map(r => r.id);
      const nomes = selectedRows.map(r => r.nome);
      const response = await window.API.updateStatusEmpresas(ids, novoStatus, nomes, cidade);
      if (response && response.success) {
        const fresh = await window.API.fetchEmpresas(cidade);
        if (fresh?.success) setEmpresas(fresh.response);
        window.addLog && window.addLog({ _id: 'l' + Date.now(), dataHora: new Date().toISOString(), tipo: 'empresa', entidade: nomes.join(', '), acao: `Status alterado → ${novoStatus}`, sucesso: true, usuario: 'admin@movixpress.com' });
        window.showToast && window.showToast({ message: 'Status atualizado com sucesso!', type: 'success' });
        clearSelected(); setNovoStatus('');
      } else {
        throw new Error(response?.error || 'Erro desconhecido');
      }
    } catch (error) {
      console.error(error);
      window.showToast && window.showToast({ message: `Erro ao atualizar status: ${error.message}`, type: 'error' });
    } finally {
      setProcessing(false);
    }
  }, [novoStatus, selectedRows, setEmpresas, clearSelected, cidade]);

  const carregarGrupo = useCallback(() => {
    const g = gruposEmpresas.find(g => String(g._id) === selectedGrupo);
    if (!g) return;
    const emps = g.empresas.map(ge => empresas.find(e => e.id === ge.id) || { id: ge.id, nome: ge.nome, categorias: [], status_empresa: 'ATIVO' });
    setSelectedRows(prev => { const n = [...prev]; emps.forEach(e => { if (!n.find(r => r.id === e.id)) n.push(e); }); return n; });
    window.showToast && window.showToast({ message: `Grupo "${g.nomeGrupo}" carregado!`, type: 'info' });
  }, [gruposEmpresas, selectedGrupo, empresas]);

  const salvarGrupo = useCallback(async () => {
    if (!nomeGrupo.trim() || !selectedRows.length) return;
    await onSaveGrupo(nomeGrupo.trim(), selectedRows);
    setSalvarCheck(false); setNomeGrupo('');
  }, [nomeGrupo, selectedRows, onSaveGrupo]);

  const adicionarExclusao = useCallback(async () => {
    const q = exclusaoBusca.trim().toLowerCase();
    if (!q) return;
    const emp = empresas.find(e => e.nome.toLowerCase().includes(q) || String(e.id) === q);
    if (!emp) { window.showToast && window.showToast({ message: 'Empresa não encontrada.', type: 'warning' }); return; }
    if (exclusaoEmpresas.find(e => e.id === emp.id)) { window.showToast && window.showToast({ message: 'Já está na lista.', type: 'warning' }); return; }
    await onAddExclusao(emp.id, emp.nome);
    setExclusaoBusca('');
    window.showToast && window.showToast({ message: `"${emp.nome}" adicionada à exclusão.`, type: 'success' });
  }, [exclusaoBusca, empresas, exclusaoEmpresas, onAddExclusao]);

  const confirm = (cfg) => window.showConfirm && window.showConfirm(cfg);
  const filtersActive = !!(filterText || filterCat || filterStatus);

  return (
    <div style={{ padding: '36px 40px 60px', maxWidth: 1280 }}>
      {/* Page header */}
      <div style={{ marginBottom: 26, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 6 }}>Gerenciamento</div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, color: MX.text, letterSpacing: '-0.025em' }}>Empresas</h1>
          <p style={{ margin: '6px 0 0', fontSize: 14, color: MX.muted }}>
            Selecione empresas para alterar categoria ou status em lote.
          </p>
        </div>
        <div style={{ fontSize: 13, color: MX.muted, fontWeight: 500 }}>
          {filtered.length} {filtered.length === 1 ? 'empresa' : 'empresas'}
        </div>
      </div>

      {/* Filters bar */}
      <div style={{ ...card, padding: '14px 16px', marginBottom: 16, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 240 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={MX.dim} strokeWidth="2" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)' }}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input className="mx-input" placeholder="Buscar por nome ou ID…" value={filterText} onChange={e => setFilterText(e.target.value)}
            style={{ ...styleInput, paddingLeft: 38 }} />
        </div>
        <select className="mx-select" value={filterStatus} onChange={e => setFilterStatus(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 200 }}>
          <option value="">Todos os status</option>
          <option value="ATIVO">Ativo</option>
          <option value="SUSPENSO">Suspenso</option>
          <option value="AGUARDANDO ATIVAÇÃO">Aguardando Ativação</option>
        </select>
        {filtersActive && (
          <button onClick={() => { setFilterText(''); setFilterCat(''); setFilterStatus(''); }} style={{ ...btnGhost, padding: '10px 14px' }}>Limpar</button>
        )}
      </div>

      {/* Table card */}
      <div style={{ ...card, marginBottom: 18, overflow: 'hidden' }}>
        <div style={{ padding: '16px 22px', borderBottom: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontWeight: 700, fontSize: 14, color: MX.text }}>Empresas cadastradas</span>
          <button onClick={selecionarTodos} style={{ ...btnGhost, fontSize: 12.5, padding: '7px 14px' }}>Selecionar todos visíveis</button>
        </div>
        <div style={{ overflowX: 'auto', filter: isLoading ? 'blur(4px)' : 'none', opacity: isLoading ? 0.6 : 1, pointerEvents: isLoading ? 'none' : 'auto', transition: 'all 0.3s' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5, tableLayout: 'fixed' }}>
              <thead>
                <tr>
                  <th style={{ ...thStyle, width: '33.33%' }}>ID</th>
                  <th style={{ ...thStyle, width: '33.33%' }}>Nome da empresa</th>
                  <th style={{ ...thStyle, width: '33.33%' }}>Status</th>
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 ? (
                  <tr><td colSpan={3} style={{ textAlign: 'center', padding: '52px', color: MX.dim, fontSize: 13.5 }}>{isLoading ? 'Carregando empresas...' : 'Nenhuma empresa encontrada.'}</td></tr>
                ) : filtered.slice((currentPage - 1) * 8, currentPage * 8).map((emp, i) => {
                  const sel = selectedIds.includes(emp.id);
                  return (
                    <tr key={emp.id} onClick={() => toggleRow(emp)} style={{
                      background: sel ? MX.brandSoft : (i % 2 === 0 ? MX.surface : MX.surface2),
                      cursor: 'pointer',
                      borderLeft: sel ? `3px solid ${MX.brand}` : '3px solid transparent',
                      borderBottom: `1px solid ${MX.border}`,
                    }}>
                      <td style={{ padding: '15px 22px', color: MX.dim, fontSize: 12 }} className="mono">#{emp.id}</td>
                      <td style={{ padding: '15px 22px', fontWeight: sel ? 600 : 500, color: sel ? MX.brandStrong : MX.text }}>{emp.nome}</td>
                      <td style={{ padding: '15px 22px' }}><EmpresaStatusBadge status={emp.status_empresa} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        {Math.ceil(filtered.length / 8) > 1 && (
          <div style={{ padding: '12px 22px', display: 'flex', justifyContent: 'center', gap: 8, borderTop: `1px solid ${MX.border}` }}>
            <button disabled={currentPage === 1} onClick={() => setCurrentPage(p => p - 1)} style={{ ...btnSoft, padding: '4px 10px', fontSize: 12 }}>Anterior</button>
            <span style={{ fontSize: 13, color: MX.dim, display: 'flex', alignItems: 'center' }}>Página {currentPage} de {Math.ceil(filtered.length / 8)}</span>
            <button disabled={currentPage === Math.ceil(filtered.length / 8)} onClick={() => setCurrentPage(p => p + 1)} style={{ ...btnSoft, padding: '4px 10px', fontSize: 12 }}>Próxima</button>
          </div>
        )}
      </div>

      {/* Selection panel (sticky-like) */}
      {selectedRows.length > 0 && (
        <div style={{ ...card, marginBottom: 18, overflow: 'hidden', borderColor: MX.brandBg, boxShadow: `0 0 0 3px ${MX.brandSoft}` }}>
          <div style={{ padding: '16px 22px', borderBottom: `1px solid ${MX.brandBg}`, background: MX.brandSoft, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
            <span style={{ fontWeight: 700, fontSize: 14, color: MX.text, display: 'flex', alignItems: 'center', gap: 9 }}>
              <span style={{ background: MX.brand, color: '#FFF', borderRadius: 999, padding: '2px 11px', fontSize: 12, fontWeight: 700 }}>{selectedRows.length}</span>
              {selectedRows.length === 1 ? 'empresa selecionada' : 'empresas selecionadas'}
            </span>
            <button onClick={clearSelected} style={{ ...btnGhost, fontSize: 12.5, padding: '7px 14px' }}>Limpar seleção</button>
          </div>
          <div style={{ padding: '14px 18px', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {selectedRows.map(emp => (
              <span key={emp.id} style={{
                display: 'inline-flex', alignItems: 'center', gap: 7,
                background: MX.surface, border: `1px solid ${MX.brandBg}`,
                borderRadius: 999, padding: '5px 8px 5px 12px',
                fontSize: 12.5, color: MX.text, fontWeight: 500,
              }}>
                {emp.nome}
                <button onClick={() => setSelectedRows(prev => prev.filter(r => r.id !== emp.id))} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.dim, fontSize: 14, lineHeight: 1, padding: 0, width: 16, height: 16, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✕</button>
              </span>
            ))}
          </div>
          <div style={{ padding: '12px 22px', borderTop: `1px solid ${MX.brandBg}`, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: MX.muted, fontWeight: 500 }}>
              <input type="checkbox" checked={salvarCheck} onChange={e => setSalvarCheck(e.target.checked)} style={{ accentColor: MX.brand, width: 14, height: 14 }} />
              Salvar como grupo
            </label>
            {salvarCheck && <>
              <input className="mx-input" placeholder="Nome do grupo…" value={nomeGrupo} onChange={e => setNomeGrupo(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 200, padding: '7px 12px', fontSize: 13 }} />
              <button onClick={salvarGrupo} disabled={!nomeGrupo.trim()} style={{ ...btnSoft, fontSize: 12.5, padding: '7px 14px', opacity: nomeGrupo.trim() ? 1 : 0.4 }}>Salvar grupo</button>
            </>}
          </div>
        </div>
      )}

      {/* Actions + Groups */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <div style={{ ...card, padding: 24 }}>
          <h3 style={{ margin: '0 0 18px', fontSize: 15, fontWeight: 700, color: MX.text }}>Ações em lote</h3>
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>Alterar categoria</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <select className="mx-select" value={novaCategoria} onChange={e => setNovaCategoria(e.target.value)} style={{ ...styleInput, flex: 1 }}>
                <option value="">Selecionar categoria…</option>
                {categorias.map(c => <option key={c.id} value={String(c.id)}>{c.nome}</option>)}
              </select>
              <button
                disabled={processing || !novaCategoria || !selectedRows.length}
                onClick={() => confirm({ title: 'Alterar categoria', message: `${selectedRows.length} empresa(s) serão alteradas para "${getCatName(parseInt(novaCategoria))}". Deseja continuar?`, confirmText: 'Alterar', onConfirm: aplicarCategoria })}
                style={{ ...btnPrimary, opacity: (processing || !novaCategoria || !selectedRows.length) ? 0.4 : 1 }}
              >{processing ? '…' : 'Aplicar'}</button>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>Alterar status</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <select className="mx-select" value={novoStatus} onChange={e => setNovoStatus(e.target.value)} style={{ ...styleInput, flex: 1 }}>
                <option value="">Selecionar status…</option>
                <option value="ATIVO">Ativo</option>
                <option value="SUSPENSO">Suspenso</option>
                <option value="AGUARDANDO ATIVAÇÃO">Aguardando Ativação</option>
              </select>
              <button
                disabled={processing || !novoStatus || !selectedRows.length}
                onClick={() => confirm({ title: 'Alterar status', message: `${selectedRows.length} empresa(s) terão o status alterado para "${novoStatus}". Deseja continuar?`, confirmText: 'Alterar', onConfirm: aplicarStatus })}
                style={{ ...btnPrimary, opacity: (processing || !novoStatus || !selectedRows.length) ? 0.4 : 1 }}
              >{processing ? '…' : 'Aplicar'}</button>
            </div>
          </div>
          {!selectedRows.length && (
            <p style={{ margin: '18px 0 0', fontSize: 12.5, color: MX.dim, textAlign: 'center', borderTop: `1px solid ${MX.border}`, paddingTop: 14 }}>
              Selecione empresas na tabela para habilitar.
            </p>
          )}
        </div>

        <div style={{ ...card, padding: 24 }}>
          <h3 style={{ margin: '0 0 18px', fontSize: 15, fontWeight: 700, color: MX.text }}>Grupos de empresas</h3>
          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            <select className="mx-select" value={selectedGrupo} onChange={e => setSelectedGrupo(e.target.value)} style={{ ...styleInput, flex: 1 }}>
              <option value="">Selecionar grupo…</option>
              {gruposEmpresas.map(g => <option key={g._id} value={g._id}>{g.nomeGrupo}</option>)}
            </select>
            <button onClick={carregarGrupo} disabled={!selectedGrupo} style={{ ...btnSoft, fontSize: 12.5, padding: '10px 14px', opacity: selectedGrupo ? 1 : 0.4 }}>Carregar</button>
            <button
              onClick={() => { const g = gruposEmpresas.find(g => String(g._id) === selectedGrupo); if (g) { setGrupoModalData(g); setShowGrupoModal(true); } }}
              disabled={!selectedGrupo}
              style={{ ...btnGhost, fontSize: 12.5, padding: '10px 14px', opacity: selectedGrupo ? 1 : 0.4 }}
            >Gerenciar</button>
          </div>
          <button onClick={() => setShowExclusao(true)} style={{ ...btnGhost, fontSize: 13, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 4 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
            Lista de exclusão
            {exclusaoEmpresas.length > 0 && <span style={{ background: MX.redSoft, color: MX.red, borderRadius: 999, padding: '1px 8px', fontSize: 11, fontWeight: 700 }}>{exclusaoEmpresas.length}</span>}
          </button>
          {gruposEmpresas.length === 0 && (
            <p style={{ margin: '14px 0 0', fontSize: 12.5, color: MX.dim, textAlign: 'center' }}>Nenhum grupo salvo ainda.</p>
          )}
        </div>
      </div>

      {showGrupoModal && grupoModalData && (
        <EmpGrupoModal
          grupo={grupoModalData}
          onClose={() => { setShowGrupoModal(false); setGrupoModalData(null); }}
          onUpdate={async (updated) => { await onUpdateGrupo(updated); setGrupoModalData(updated); }}
          onDelete={async () => { await onDeleteGrupo(grupoModalData._id); setShowGrupoModal(false); setGrupoModalData(null); setSelectedGrupo(''); }}
          onAddAllToExclusao={async () => {
            const g = grupoModalData;
            for (const emp of g.empresas) {
              await onAddExclusao(emp.id, emp.nome);
            }
            window.showToast && window.showToast({ message: `Grupo "${g.nomeGrupo}" adicionado à exclusão.`, type: 'success' });
            setShowGrupoModal(false); setGrupoModalData(null);
          }}
        />
      )}
      {showExclusao && (
        <EmpExclusaoModal
          exclusoes={exclusaoEmpresas} busca={exclusaoBusca}
          onBuscaChange={setExclusaoBusca} onAdd={adicionarExclusao}
          onRemove={onRemoveExclusao}
          onClearAll={async () => {
            for (const e of exclusaoEmpresas) await onRemoveExclusao(e._id);
            window.showToast && window.showToast({ message: 'Lista de exclusão limpa.', type: 'info' });
          }}
          onClose={() => setShowExclusao(false)}
        />
      )}
    </div>
  );
}

Object.assign(window, { EmpresasPage });
