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

const ENT_STATUS_MAP = {
  A: 'Ativo', E: 'Em análise', F: 'Fila de espera',
  I: 'Inativo', S: 'Suspenso', R: 'Rejeitado', D: 'Deletado',
};
const ENT_STATUS_OPTS = Object.entries(ENT_STATUS_MAP).map(([v, l]) => ({ value: v, label: l }));

function parseDateTime(str) {
  if (!str) return null;
  return new Date(str.replace(' ', 'T'));
}
function formatDate(str) {
  const d = parseDateTime(str);
  if (!d) return '—';
  return d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
}

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

function EntGrupoModal({ 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 [data, setData] = useState({ ...grupo });
  const [busca, setBusca] = useState('');
  const [page, setPage] = useState(1);

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

  const remove = (idx) => {
    const up = {
      ...data,
      entregadores: data.entregadores.filter((_, i) => i !== idx),
      ids: data.ids.filter((_, i) => i !== idx),
      situacaoCadastral: data.situacaoCadastral.filter((_, i) => i !== idx),
      vtr: data.vtr.filter((_, i) => i !== idx),
    };
    setData(up); onUpdate(up);
  };

  const total = data.entregadores.length;
  const indices = data.entregadores.map((_, i) => i);
  const filtrados = busca.trim()
    ? indices.filter(i => data.entregadores[i].toLowerCase().includes(busca.toLowerCase()) || String(data.ids[i]).includes(busca))
    : indices;

  const totalPages = Math.max(1, Math.ceil(filtrados.length / GRUPO_PER_PAGE));
  const pg = Math.min(page, totalPages);
  const paginados = filtrados.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: 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' }}>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 }}>
                  {total} entregador{total !== 1 ? 'es' : ''}
                </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 */}
        <div style={{ flex: 1, minHeight: 0, padding: '0 28px', overflowY: 'auto' }}>
          {total === 0 ? (
            <div style={{ textAlign: 'center', padding: '32px 0', color: MX.dim, fontSize: 13.5 }}>Grupo vazio.</div>
          ) : filtrados.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}>Entregador</th>
                    <th style={thStyle}>VTR</th>
                    <th style={{ ...thStyle, width: 50 }}></th>
                  </tr>
                </thead>
                <tbody>
                  {paginados.map((i, pos) => (
                    <tr key={data.ids[i]} style={{ borderBottom: pos === paginados.length - 1 ? 'none' : `1px solid ${MX.border}` }}>
                      <td style={{ padding: '10px 22px' }}>
                        <div style={{ fontWeight: 500, color: MX.text }}>{data.entregadores[i]}</div>
                        <div style={{ fontSize: 11.5, color: MX.dim, marginTop: 2 }} className="mono">ID: {data.ids[i]}</div>
                      </td>
                      <td style={{ padding: '10px 22px', color: MX.muted, fontSize: 12.5 }}>{data.vtr[i] || '—'}</td>
                      <td style={{ padding: '10px 22px', textAlign: 'center' }}>
                        <button onClick={() => remove(i)} 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, filtrados.length)} de {filtrados.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 EntExclusaoModal({ 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: 560, 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 }}>
                Entregadores ignorados 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} entregador{exclusoes.length !== 1 ? 'es' : ''}
                  </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 por nome, ID ou VTR…"
              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 }}>Nenhum entregador 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}>VTR</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_do_entregador}</td>
                        <td style={{ padding: '10px 22px', color: MX.muted }} className="mono">#{item.id}</td>
                        <td style={{ padding: '10px 22px', color: MX.muted, fontSize: 12.5 }}>{item.vtr || '—'}</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 EntregadoresPage({ entregadores, setEntregadores, categorias, cidade, gruposEntregadores, onSaveGrupo, onUpdateGrupo, onDeleteGrupo, exclusaoEntregadores, 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;
  const EntregadorStatusBadge = window.EntregadorStatusBadge;
  const SkeletonTable         = window.SkeletonTable;

  const [selectedRows,     setSelectedRows]     = useState([]);
  const [filterText,       setFilterText]       = useState('');
  const [filterMin,        setFilterMin]        = useState('');
  const [filterStatus,     setFilterStatus]     = useState('');
  const [catsSelecionadas, setCatsSelecionadas] = useState([]);
  const [novoStatus,       setNovoStatus]       = useState('');
  const [processing,       setProcessing]       = useState(false);
  const [selectedGrupo,    setSelectedGrupo]    = useState('');
  const [salvarCheck,      setSalvarCheck]      = useState(false);
  const [nomeGrupo,        setNomeGrupo]        = useState('');
  const [editingGrupoId,   setEditingGrupoId]   = useState(null);
  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, filterMin, filterStatus]);

  const excludedIds = useMemo(() => exclusaoEntregadores.map(e => String(e.id)), [exclusaoEntregadores]);
  const filtered = useMemo(() => entregadores.filter(ent => {
    if (excludedIds.includes(String(ent.id))) return false;
    const txt = filterText.toLowerCase();
    const matchTxt = !txt || ent.nome.toLowerCase().includes(txt) || String(ent.id).includes(txt) || (ent.vtr && ent.vtr.toLowerCase().includes(txt)) || (ENT_STATUS_MAP[ent.status] || '').toLowerCase().includes(txt);
    const matchSt = !filterStatus || ent.status === filterStatus;
    let matchTime = true;
    if (filterMin) {
      const ul = parseDateTime(ent.ultima_corrida);
      if (!ul) matchTime = false;
      else matchTime = (Date.now() - ul.getTime()) / 60000 <= parseInt(filterMin);
    }
    return matchTxt && matchTime && matchSt;
  }), [entregadores, filterText, filterMin, 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((ent) => {
    setSelectedRows(prev => prev.find(r => r.id === ent.id) ? prev.filter(r => r.id !== ent.id) : [...prev, ent]);
  }, []);

  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} entregadores selecionados.`, type: 'info' });
  }, [filtered]);

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

  const aplicarCategoria = useCallback(async () => {
    setProcessing(true);

    try {
      const catIds = catsSelecionadas.map(Number);
      const ids = selectedRows.map(r => r.id);
      const nomes = selectedRows.map(r => r.nome);

      const response = await window.API.updateCategoriasEntregadores(ids, catIds, nomes, cidade);

      if (response && response.success) {
        setEntregadores(prev => prev.map(e => ids.includes(e.id) ? { ...e, categorias: catIds } : e));
        const catNames = catsSelecionadas.map(id => getCatName(parseInt(id))).join(', ');
        window.addLog && window.addLog({ _id: 'l' + Date.now(), dataHora: new Date().toISOString(), tipo: 'entregador', entidade: nomes.join(', '), acao: `Categoria alterada → ${catNames}`, sucesso: true, usuario: 'admin@movixpress.com' });
        window.showToast && window.showToast({ message: `Categorias aplicadas em ${ids.length} entregador(es)!`, type: 'success' });
        clearSelected();
        setCatsSelecionadas([]);
      } else {
        throw new Error(response.error || 'Alguns erraram.');
      }
    } catch (error) {
      console.error(error);
      window.showToast && window.showToast({ message: `Erro ao adicionar as categorias: ${error.message}`, type: 'error' });
    } finally {
      setProcessing(false);
    }
  }, [catsSelecionadas, selectedRows, getCatName, setEntregadores, clearSelected]);

  const aplicarStatus = useCallback(async () => {
    setProcessing(true);
    try {
      const ids = selectedRows.map(r => r.id);
      const response = await window.API.updateStatusEntregadores(ids, novoStatus, [], cidade);

      if (response && response.success) {
        const fresh = await window.API.fetchEntregadores(cidade);
        if (fresh?.success) setEntregadores(fresh.response);
        window.addLog && window.addLog({ _id: 'l' + Date.now(), dataHora: new Date().toISOString(), tipo: 'entregador', entidade: selectedRows.map(r => r.nome).join(', '), acao: `Situação alterada → ${ENT_STATUS_MAP[novoStatus]}`, sucesso: true, usuario: 'admin@movixpress.com' });
        window.showToast && window.showToast({ message: 'Situação atualizada com sucesso!', type: 'success' });
        clearSelected();
        setNovoStatus('');
      } else {
        throw new Error('Erro na atualização');
      }
    } catch (error) {
      console.error(error);
      window.showToast && window.showToast({ message: `Erro ao aplicar o status!`, type: 'error' });
    } finally {
      setProcessing(false);
    }
  }, [novoStatus, selectedRows, setEntregadores, clearSelected, cidade]);

  const carregarGrupo = useCallback(() => {
    const g = gruposEntregadores.find(g => String(g._id) === selectedGrupo);
    if (!g) return;
    const ents = g.ids.map((id, i) => entregadores.find(e => e.id === id) || { id, nome: g.entregadores[i], status: 'A', vtr: g.vtr[i], ultima_corrida: null, categorias: [] });
    setSelectedRows(prev => { const n = [...prev]; ents.forEach(e => { if (!n.find(r => r.id === e.id)) n.push(e); }); return n; });
    setEditingGrupoId(selectedGrupo); setSalvarCheck(true); setNomeGrupo(g.nomeGrupo);
    window.showToast && window.showToast({ message: `Grupo "${g.nomeGrupo}" carregado!`, type: 'info' });
  }, [gruposEntregadores, selectedGrupo, entregadores]);

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

  const adicionarExclusao = useCallback(async () => {
    const q = exclusaoBusca.trim().toLowerCase();
    if (!q) return;
    const ent = entregadores.find(e => e.nome.toLowerCase().includes(q) || String(e.id) === q || (e.vtr && e.vtr.toLowerCase().includes(q)));
    if (!ent) { window.showToast && window.showToast({ message: 'Entregador não encontrado.', type: 'warning' }); return; }
    if (exclusaoEntregadores.find(e => e.id === ent.id)) { window.showToast && window.showToast({ message: 'Entregador já está na lista.', type: 'warning' }); return; }
    await onAddExclusao(ent.id, ent.nome, ent.vtr || '');
    setExclusaoBusca('');
    window.showToast && window.showToast({ message: `"${ent.nome}" adicionado à exclusão.`, type: 'success' });
  }, [exclusaoBusca, entregadores, exclusaoEntregadores, onAddExclusao]);

  const confirm = (cfg) => window.showConfirm && window.showConfirm(cfg);
  const filtersActive = !!(filterText || filterMin || 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' }}>Entregadores</h1>
          <p style={{ margin: '6px 0 0', fontSize: 14, color: MX.muted }}>
            Gerencie categorias, situação e grupos em lote.
          </p>
        </div>
        <div style={{ fontSize: 13, color: MX.muted, fontWeight: 500 }}>
          {filtered.length} {filtered.length === 1 ? 'entregador' : 'entregadores'}
        </div>
      </div>

      {/* Filters */}
      <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, ID ou VTR…" 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: 180 }}>
          <option value="">Todas as situações</option>
          {ENT_STATUS_OPTS.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
        </select>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, padding: '0 4px' }}>
          <span style={{ fontSize: 12.5, color: MX.muted, whiteSpace: 'nowrap' }}>Última corrida &lt;</span>
          <input className="mx-input" type="number" placeholder="60" value={filterMin} onChange={e => setFilterMin(e.target.value)} min="0" style={{ ...styleInput, flex: '0 0 auto', width: 80 }} />
          <span style={{ fontSize: 12.5, color: MX.muted }}>min</span>
        </div>
        {filtersActive && (
          <button onClick={() => { setFilterText(''); setFilterMin(''); 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 }}>Entregadores cadastrados</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 }}>
              <thead><tr>{['ID', 'Nome', 'VTR', 'Situação', 'Última corrida'].map(col => <th key={col} style={thStyle}>{col}</th>)}</tr></thead>
              <tbody>
                {filtered.length === 0 ? (<tr><td colSpan={5} style={{ textAlign: 'center', padding: '52px', color: MX.dim, fontSize: 13.5 }}>{isLoading ? 'Carregando entregadores...' : 'Nenhum entregador encontrado.'}</td></tr>
                ) : filtered.slice((currentPage - 1) * 8, currentPage * 8).map((ent, i) => {
                  const sel = selectedIds.includes(ent.id);
                  return (
                    <tr key={ent.id} onClick={() => toggleRow(ent)} 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">#{ent.id}</td>
                      <td style={{ padding: '15px 22px', fontWeight: sel ? 600 : 500, color: sel ? MX.brandStrong : MX.text }}>{ent.nome}</td>
                      <td style={{ padding: '15px 22px', color: MX.muted, fontSize: 12.5 }}>{ent.vtr || '—'}</td>
                      <td style={{ padding: '15px 22px' }}><EntregadorStatusBadge status={ent.status} /></td>
                      <td style={{ padding: '15px 22px', color: MX.muted, fontSize: 12.5 }}>{formatDate(ent.ultima_corrida)}</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 */}
      {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 ? 'entregador selecionado' : 'entregadores selecionados'}
            </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(ent => (
              <span key={ent.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,
              }}>
                {ent.nome}
                <button onClick={() => setSelectedRows(prev => prev.filter(r => r.id !== ent.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 }} />
              {editingGrupoId ? 'Atualizar grupo' : '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 }}>
                {editingGrupoId ? 'Salvar alterações' : '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: 20 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 10 }}>Alterar categorias</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 12 }}>
              {categorias.map(cat => {
                const checked = catsSelecionadas.includes(String(cat.id));
                return (
                  <label key={cat.id} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    background: checked ? MX.brandSoft : MX.surface2,
                    border: `1px solid ${checked ? MX.brandBg : MX.border}`,
                    borderRadius: 999, padding: '6px 12px', cursor: 'pointer',
                    fontSize: 12.5, fontWeight: checked ? 600 : 500,
                    color: checked ? MX.brandStrong : MX.muted,
                    transition: 'all 0.15s', userSelect: 'none',
                  }}>
                    <input type="checkbox" checked={checked} onChange={() => setCatsSelecionadas(prev => checked ? prev.filter(c => c !== String(cat.id)) : [...prev, String(cat.id)])} style={{ display: 'none' }} />
                    {cat.nome}
                  </label>
                );
              })}
            </div>
            <button
              disabled={processing || !catsSelecionadas.length || !selectedRows.length}
              onClick={() => { const names = catsSelecionadas.map(id => getCatName(parseInt(id))).join(', '); confirm({ title: 'Alterar categorias', message: `${selectedRows.length} entregador(es) serão alterados para: "${names}". Deseja continuar?`, confirmText: 'Alterar', onConfirm: aplicarCategoria }); }}
              style={{ ...btnPrimary, width: '100%', opacity: (processing || !catsSelecionadas.length || !selectedRows.length) ? 0.4 : 1 }}
            >{processing ? 'Processando…' : 'Aplicar categorias'}</button>
          </div>

          <div style={{ borderTop: `1px solid ${MX.border}`, paddingTop: 18 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>Alterar situação</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 situação…</option>
                {ENT_STATUS_OPTS.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
              </select>
              <button
                disabled={processing || !novoStatus || !selectedRows.length}
                onClick={() => confirm({ title: 'Alterar situação', message: `${selectedRows.length} entregador(es) terão a situação alterada para "${ENT_STATUS_MAP[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 entregadores 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 entregadores</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>
              {gruposEntregadores.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 = gruposEntregadores.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
            {exclusaoEntregadores.length > 0 && <span style={{ background: MX.redSoft, color: MX.red, borderRadius: 999, padding: '1px 8px', fontSize: 11, fontWeight: 700 }}>{exclusaoEntregadores.length}</span>}
          </button>
          {gruposEntregadores.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 && (
        <EntGrupoModal
          grupo={grupoModalData}
          onClose={() => { setShowGrupoModal(false); setGrupoModalData(null); }}
          onUpdate={async (up) => { await onUpdateGrupo(up); setGrupoModalData(up); }}
          onDelete={async () => { await onDeleteGrupo(grupoModalData._id); setShowGrupoModal(false); setGrupoModalData(null); setSelectedGrupo(''); }}
          onAddAllToExclusao={async () => {
            const g = grupoModalData;
            for (let i = 0; i < g.ids.length; i++) {
              await onAddExclusao(g.ids[i], g.entregadores[i], g.vtr[i] || '');
            }
            window.showToast && window.showToast({ message: `Grupo "${g.nomeGrupo}" adicionado à exclusão.`, type: 'success' });
            setShowGrupoModal(false); setGrupoModalData(null);
          }}
        />
      )}
      {showExclusao && (
        <EntExclusaoModal
          exclusoes={exclusaoEntregadores} busca={exclusaoBusca}
          onBuscaChange={setExclusaoBusca} onAdd={adicionarExclusao}
          onRemove={onRemoveExclusao}
          onClearAll={async () => {
            for (const e of exclusaoEntregadores) await onRemoveExclusao(e._id);
            window.showToast && window.showToast({ message: 'Lista de exclusão limpa.', type: 'info' });
          }}
          onClose={() => setShowExclusao(false)}
        />
      )}
    </div>
  );
}

Object.assign(window, { EntregadoresPage });
