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

const SA_PER_PAGE = 10;

// ── helpers ──────────────────────────────────────────────────────────────────

function fmtDate(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' });
}

function RoleBadge({ role }) {
  const MX = window.MX;
  const cfg = role === 'super_admin'
    ? { label: 'Super Admin', fg: MX.purple, bg: MX.purpleSoft }
    : { label: 'Admin',       fg: MX.blue,   bg: MX.blueSoft   };
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: cfg.bg, color: cfg.fg, borderRadius: 999, padding: '2px 9px', fontSize: 11, fontWeight: 700 }}>
      {cfg.label}
    </span>
  );
}

function CidadeBadge({ cidade }) {
  const MX = window.MX;
  const map = {
    tbt:   { label: 'Taubaté', fg: MX.brandStrong, bg: MX.brandSoft },
    sjc:   { label: 'SJC',     fg: MX.blue,        bg: MX.blueSoft  },
    todas: { label: 'Todas',   fg: MX.green,       bg: MX.greenSoft },
  };
  const cfg = map[cidade] || { label: cidade, fg: MX.muted, bg: MX.surface3 };
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', background: cfg.bg, color: cfg.fg, borderRadius: 999, padding: '2px 9px', fontSize: 11, fontWeight: 700 }}>
      {cfg.label}
    </span>
  );
}

function StatCard({ label, value, sub, color }) {
  const MX = window.MX;
  return (
    <div style={{ ...window.card, padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.10em', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 28, fontWeight: 700, color: color || MX.text, letterSpacing: '-0.025em', lineHeight: 1 }}>
        {value ?? '—'}
      </div>
      {sub && <div style={{ fontSize: 12, color: MX.muted }}>{sub}</div>}
    </div>
  );
}

function NavBtn({ style, disabled, onClick, children }) {
  const MX = window.MX;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      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,
      ...style,
    }}>{children}</button>
  );
}

// ── User Modal ────────────────────────────────────────────────────────────────

function UserModal({ editingUser, currentUserId, onSave, onClose }) {
  const MX = window.MX, card = window.card, btnPrimary = window.btnPrimary;
  const isEdit = !!editingUser;

  const [nome,   setNome]   = useState(editingUser?.nome   || '');
  const [email,  setEmail]  = useState(editingUser?.email  || '');
  const [senha,  setSenha]  = useState('');
  const [role,   setRole]   = useState(editingUser?.role   || 'admin');
  const [cidade, setCidade] = useState(editingUser?.cidade || 'tbt');
  const [ativo,  setAtivo]  = useState(editingUser?.ativo  !== false);
  const [error,  setError]  = useState('');
  const [saving, setSaving] = useState(false);

  const isSelf = isEdit && editingUser.id === currentUserId;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!nome.trim())  return setError('O nome não pode estar vazio.');
    if (!email.trim()) return setError('O e-mail não pode estar vazio.');
    if (!isEdit && senha.length < 8) return setError('A senha deve ter pelo menos 8 caracteres.');
    if (isEdit && senha && senha.length < 8) return setError('A senha deve ter pelo menos 8 caracteres.');

    setSaving(true);
    try {
      const data = { nome: nome.trim(), email: email.trim().toLowerCase(), role, cidade };
      if (senha) data.senha = senha;
      if (isEdit) data.ativo = ativo;
      await onSave(data);
    } catch (err) {
      setError(err.message || 'Erro ao salvar.');
      setSaving(false);
    }
  };

  const inputS = {
    width: '100%', padding: '10px 14px', borderRadius: 10,
    border: `1px solid ${MX.border}`, background: MX.surface,
    fontSize: 13.5, color: MX.text, outline: 'none', boxSizing: 'border-box',
  };
  const lbl = { fontSize: 11, fontWeight: 600, color: MX.dim, display: 'block', marginBottom: 7, letterSpacing: '0.10em', textTransform: 'uppercase' };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9500, background: 'rgba(20,20,30,0.44)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ ...card, width: 460, maxWidth: '93vw', maxHeight: '90vh', overflowY: 'auto', padding: 28, animation: 'modalIn 0.22s ease', boxShadow: '0 32px 80px rgba(20,20,30,0.22)' }}>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: MX.text }}>{isEdit ? 'Editar usuário' : 'Novo usuário'}</div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.dim, fontSize: 22, lineHeight: 1 }}>✕</button>
        </div>

        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: 14 }}>
            <label style={lbl}>Nome</label>
            <input className="mx-input" type="text" value={nome} onChange={e => setNome(e.target.value)} style={inputS} required />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label style={lbl}>E-mail</label>
            <input className="mx-input" type="email" value={email} onChange={e => setEmail(e.target.value)} style={inputS} required />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label style={lbl}>Senha {isEdit && <span style={{ fontWeight: 400, fontSize: 10, textTransform: 'none', color: MX.faint }}>(deixe vazio para não alterar)</span>}</label>
            <input className="mx-input" type="password" value={senha} onChange={e => setSenha(e.target.value)} placeholder={isEdit ? '••••••••' : 'Mínimo 8 caracteres'} style={inputS} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14 }}>
            <div>
              <label style={lbl}>Role</label>
              <select className="mx-select" value={role} onChange={e => setRole(e.target.value)} disabled={isSelf} style={{ ...inputS, cursor: isSelf ? 'not-allowed' : 'pointer', opacity: isSelf ? 0.5 : 1 }}>
                <option value="admin">Admin</option>
                <option value="super_admin">Super Admin</option>
              </select>
            </div>
            <div>
              <label style={lbl}>Cidade</label>
              <select className="mx-select" value={cidade} onChange={e => setCidade(e.target.value)} style={inputS}>
                <option value="tbt">Taubaté</option>
                <option value="sjc">SJC</option>
                <option value="todas">Todas</option>
              </select>
            </div>
          </div>
          {isEdit && (
            <div style={{ marginBottom: 18 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: isSelf ? 'not-allowed' : 'pointer', fontSize: 13, color: MX.muted, fontWeight: 500 }}>
                <input type="checkbox" checked={ativo} disabled={isSelf} onChange={e => setAtivo(e.target.checked)} style={{ accentColor: MX.brand, width: 14, height: 14 }} />
                Conta ativa
              </label>
            </div>
          )}
          {error && (
            <div style={{ background: MX.redSoft, borderLeft: `3px solid ${MX.red}`, borderRadius: 10, padding: '10px 14px', marginBottom: 16, fontSize: 13, color: MX.red }}>
              {error}
            </div>
          )}
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
            <button type="button" onClick={onClose} style={{ padding: '10px 20px', borderRadius: 10, border: `1px solid ${MX.border}`, background: MX.surface, color: MX.muted, fontSize: 13.5, fontWeight: 600, cursor: 'pointer' }}>Cancelar</button>
            <button type="submit" disabled={saving} style={{ ...btnPrimary, opacity: saving ? 0.6 : 1 }}>{saving ? 'Salvando…' : 'Salvar'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Usuários Tab ──────────────────────────────────────────────────────────────

function UsuariosTab({ currentUser }) {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const btnSoft = window.btnSoft, btnDanger = window.btnDanger, btnPrimary = window.btnPrimary;

  const [users,       setUsers]       = useState([]);
  const [loading,     setLoading]     = useState(true);
  const [showModal,   setShowModal]   = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [busca,       setBusca]       = useState('');
  const [page,        setPage]        = useState(1);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await window.API.adminFetchUsuarios();
      if (res?.success) setUsers(res.response);
    } catch (e) {
      window.showToast && window.showToast({ message: 'Erro ao carregar usuários.', type: 'error' });
    } finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  const filtered = useMemo(() => {
    const q = busca.toLowerCase();
    return !q ? users : users.filter(u => u.nome.toLowerCase().includes(q) || u.email.toLowerCase().includes(q));
  }, [users, busca]);

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

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

  const handleSave = async (data) => {
    if (editingUser) {
      const res = await window.API.adminUpdateUsuario(editingUser.id, data);
      if (!res?.success) throw new Error(res?.detail || 'Erro ao atualizar.');
      window.showToast && window.showToast({ message: 'Usuário atualizado!', type: 'success' });
    } else {
      const res = await window.API.adminCreateUsuario(data);
      if (!res?.success) throw new Error(res?.detail || 'Erro ao criar.');
      window.showToast && window.showToast({ message: 'Usuário criado!', type: 'success' });
    }
    setShowModal(false); setEditingUser(null);
    load();
  };

  const handleToggle = async (u) => {
    const res = await window.API.adminUpdateUsuario(u.id, { ativo: !u.ativo });
    if (res?.success) {
      setUsers(prev => prev.map(x => x.id === u.id ? { ...x, ativo: !u.ativo } : x));
      window.showToast && window.showToast({ message: `Conta ${!u.ativo ? 'ativada' : 'desativada'}.`, type: 'info' });
    }
  };

  const handleDelete = (u) => {
    window.showConfirm && window.showConfirm({
      title: 'Excluir usuário',
      message: `Tem certeza que deseja excluir "${u.nome}"? Esta ação não pode ser desfeita.`,
      confirmText: 'Excluir',
      onConfirm: async () => {
        const res = await window.API.adminDeleteUsuario(u.id);
        if (res?.success) {
          setUsers(prev => prev.filter(x => x.id !== u.id));
          window.showToast && window.showToast({ message: 'Usuário excluído.', type: 'info' });
        } else {
          window.showToast && window.showToast({ message: res?.detail || 'Erro ao excluir.', type: 'error' });
        }
      },
    });
  };

  const iconBtn = (onClick, title, color, icon) => (
    <button title={title} onClick={onClick} style={{
      background: 'transparent', border: 'none', cursor: 'pointer',
      color, fontSize: 15, padding: '4px 6px', borderRadius: 7, lineHeight: 1,
    }}>{icon}</button>
  );

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 16 }}>
        <input className="mx-input" placeholder="Buscar por nome ou e-mail…" value={busca} onChange={e => setBusca(e.target.value)}
          style={{ ...window.styleInput, maxWidth: 320 }} />
        <button onClick={() => { setEditingUser(null); setShowModal(true); }} style={{ ...btnPrimary, display: 'flex', alignItems: 'center', gap: 7 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          Novo usuário
        </button>
      </div>

      <div style={{ ...card, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
          <thead>
            <tr>
              <th style={thStyle}>Usuário</th>
              <th style={thStyle}>Role</th>
              <th style={thStyle}>Cidade</th>
              <th style={thStyle}>Status</th>
              <th style={thStyle}>Último acesso</th>
              <th style={{ ...thStyle, textAlign: 'right' }}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={6} style={{ textAlign: 'center', padding: 48, color: MX.dim }}>Carregando…</td></tr>
            ) : paginados.length === 0 ? (
              <tr><td colSpan={6} style={{ textAlign: 'center', padding: 48, color: MX.dim }}>Nenhum usuário encontrado.</td></tr>
            ) : paginados.map((u, i) => (
              <tr key={u.id} style={{ borderBottom: `1px solid ${MX.border}`, background: i % 2 === 0 ? MX.surface : MX.surface2 }}>
                <td style={{ padding: '13px 22px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', background: u.id === currentUser?.id ? MX.brand : MX.surface3, color: u.id === currentUser?.id ? '#FFF' : MX.muted, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, flexShrink: 0 }}>
                      {u.nome[0].toUpperCase()}
                    </div>
                    <div>
                      <div style={{ fontWeight: 600, color: MX.text }}>{u.nome} {u.id === currentUser?.id && <span style={{ fontSize: 10, color: MX.muted, fontWeight: 400 }}>(você)</span>}</div>
                      <div style={{ fontSize: 12, color: MX.muted }} className="mono">{u.email}</div>
                    </div>
                  </div>
                </td>
                <td style={{ padding: '13px 22px' }}><RoleBadge role={u.role} /></td>
                <td style={{ padding: '13px 22px' }}><CidadeBadge cidade={u.cidade} /></td>
                <td style={{ padding: '13px 22px' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: u.ativo ? MX.greenSoft : MX.surface3, color: u.ativo ? MX.green : MX.dim, borderRadius: 999, padding: '2px 9px', fontSize: 11, fontWeight: 700 }}>
                    <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'currentColor' }}></span>
                    {u.ativo ? 'Ativo' : 'Inativo'}
                  </span>
                </td>
                <td style={{ padding: '13px 22px', color: MX.muted, fontSize: 12.5 }}>{fmtDate(u.ultimo_acesso)}</td>
                <td style={{ padding: '13px 22px', textAlign: 'right' }}>
                  {iconBtn(() => { setEditingUser(u); setShowModal(true); }, 'Editar', MX.blue,
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                  )}
                  {u.id !== currentUser?.id && iconBtn(() => handleToggle(u), u.ativo ? 'Desativar' : 'Ativar', u.ativo ? MX.yellow : MX.green,
                    u.ativo
                      ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
                      : <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                  )}
                  {u.id !== currentUser?.id && iconBtn(() => handleDelete(u), 'Excluir', MX.red,
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/></svg>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {totalPages > 1 && (
          <div style={{ padding: '12px 22px', borderTop: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 12, color: MX.dim }}>{(pg - 1) * SA_PER_PAGE + 1}–{Math.min(pg * SA_PER_PAGE, filtered.length)} de {filtered.length}</span>
            <div style={{ display: 'flex', gap: 6 }}>
              <NavBtn disabled={pg === 1} onClick={() => setPage(p => p - 1)}>‹</NavBtn>
              <span style={{ fontSize: 12, color: MX.muted, padding: '3px 8px' }}>pág. {pg} / {totalPages}</span>
              <NavBtn disabled={pg === totalPages} onClick={() => setPage(p => p + 1)}>›</NavBtn>
            </div>
          </div>
        )}
      </div>

      {showModal && (
        <UserModal
          editingUser={editingUser}
          currentUserId={currentUser?.id}
          onSave={handleSave}
          onClose={() => { setShowModal(false); setEditingUser(null); }}
        />
      )}
    </div>
  );
}

// ── Logs Admin Tab ────────────────────────────────────────────────────────────

function LogsAdminTab() {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const styleInput = window.styleInput, btnSoft = window.btnSoft, btnGhost = window.btnGhost;

  const [logs,       setLogs]       = useState([]);
  const [loading,    setLoading]    = useState(true);
  const [exporting,  setExporting]  = useState(false);
  const [page,       setPage]       = useState(1);
  const [busca,      setBusca]      = useState('');
  const [tipo,       setTipo]       = useState('');
  const [cidade,     setCidade]     = useState('');
  const [sucesso,    setSucesso]    = useState('');
  const [dataInicio, setDataInicio] = useState('');
  const [dataFim,    setDataFim]    = useState('');

  const params = useMemo(() => ({ tipo, cidade, sucesso, data_inicio: dataInicio, data_fim: dataFim }), [tipo, cidade, sucesso, dataInicio, dataFim]);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await window.API.adminFetchLogs(params);
      if (res?.success) setLogs(res.response);
    } catch { window.showToast && window.showToast({ message: 'Erro ao carregar logs.', type: 'error' }); }
    finally { setLoading(false); }
  }, [params]);

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

  const filtered = useMemo(() => {
    const q = busca.toLowerCase();
    return !q ? logs : logs.filter(l => l.entidade.toLowerCase().includes(q) || l.acao.toLowerCase().includes(q));
  }, [logs, busca]);

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

  const handleExport = async () => {
    setExporting(true);
    try {
      await window.API.adminExportLogsCSV(params);
      window.showToast && window.showToast({ message: 'CSV exportado com sucesso!', type: 'success' });
    } catch (e) {
      window.showToast && window.showToast({ message: e.message, type: 'error' });
    } finally { setExporting(false); }
  };

  const clearFilters = () => { setTipo(''); setCidade(''); setSucesso(''); setDataInicio(''); setDataFim(''); setBusca(''); };
  const hasFilters = tipo || cidade || sucesso || dataInicio || dataFim || busca;

  return (
    <div>
      {/* Filter bar */}
      <div style={{ ...card, padding: '14px 16px', marginBottom: 16, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <input className="mx-input" placeholder="Buscar entidade ou ação…" value={busca} onChange={e => setBusca(e.target.value)} style={{ ...styleInput, minWidth: 220, flex: 1 }} />
        <select className="mx-select" value={tipo} onChange={e => setTipo(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 160 }}>
          <option value="">Todos os tipos</option>
          <option value="empresa">Empresa</option>
          <option value="entregador">Entregador</option>
        </select>
        <select className="mx-select" value={cidade} onChange={e => setCidade(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 140 }}>
          <option value="">Todas as cidades</option>
          <option value="tbt">Taubaté</option>
          <option value="sjc">SJC</option>
        </select>
        <select className="mx-select" value={sucesso} onChange={e => setSucesso(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 130 }}>
          <option value="">Todos os status</option>
          <option value="sim">Sucesso</option>
          <option value="nao">Falha</option>
        </select>
        <input className="mx-input" type="date" value={dataInicio} onChange={e => setDataInicio(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', width: 150 }} />
        <input className="mx-input" type="date" value={dataFim} onChange={e => setDataFim(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', width: 150 }} />
        {hasFilters && <button onClick={clearFilters} style={{ ...btnGhost, padding: '10px 14px' }}>Limpar</button>}
        <button onClick={handleExport} disabled={exporting || loading} style={{ ...btnSoft, display: 'flex', alignItems: 'center', gap: 7, flexShrink: 0, opacity: (exporting || loading) ? 0.6 : 1 }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          {exporting ? 'Exportando…' : 'Exportar CSV'}
        </button>
      </div>

      <div style={{ ...card, overflow: 'hidden' }}>
        <div style={{ padding: '12px 22px', borderBottom: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: MX.text }}>{filtered.length} operações encontradas</span>
          {loading && <span style={{ fontSize: 12, color: MX.dim }}>Carregando…</span>}
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr>
                <th style={thStyle}>Data/Hora</th>
                <th style={thStyle}>Tipo</th>
                <th style={thStyle}>Entidade</th>
                <th style={thStyle}>Ação</th>
                <th style={thStyle}>Status</th>
                <th style={thStyle}>Cidade</th>
                <th style={{ ...thStyle, textAlign: 'center' }}>IDs</th>
              </tr>
            </thead>
            <tbody>
              {paginados.length === 0 ? (
                <tr><td colSpan={7} style={{ textAlign: 'center', padding: 48, color: MX.dim }}>Nenhum log encontrado.</td></tr>
              ) : paginados.map((l, i) => (
                <tr key={l._id} style={{ borderBottom: `1px solid ${MX.border}`, background: i % 2 === 0 ? MX.surface : MX.surface2 }}>
                  <td style={{ padding: '11px 22px', color: MX.muted, fontSize: 12, whiteSpace: 'nowrap' }} className="mono">{fmtDate(l.dataHora)}</td>
                  <td style={{ padding: '11px 22px' }}>
                    <span style={{ background: l.tipo === 'empresa' ? MX.brandSoft : MX.blueSoft, color: l.tipo === 'empresa' ? MX.brandStrong : MX.blue, borderRadius: 999, padding: '2px 8px', fontSize: 11, fontWeight: 700 }}>
                      {l.tipo === 'empresa' ? 'Empresa' : 'Entregador'}
                    </span>
                  </td>
                  <td style={{ padding: '11px 22px', color: MX.text, maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.entidade}</td>
                  <td style={{ padding: '11px 22px', color: MX.muted, fontSize: 12.5 }}>{l.acao}</td>
                  <td style={{ padding: '11px 22px' }}>
                    <span style={{ background: l.sucesso ? MX.greenSoft : MX.redSoft, color: l.sucesso ? MX.green : MX.red, borderRadius: 999, padding: '2px 8px', fontSize: 11, fontWeight: 700 }}>
                      {l.sucesso ? 'OK' : 'Falha'}
                    </span>
                  </td>
                  <td style={{ padding: '11px 22px' }}><CidadeBadge cidade={l.cidade} /></td>
                  <td style={{ padding: '11px 22px', textAlign: 'center' }}>
                    <span title={l.ids.slice(0, 10).join(', ')} style={{ background: MX.surface3, color: MX.muted, borderRadius: 999, padding: '2px 8px', fontSize: 11, fontWeight: 700, cursor: l.total_ids > 0 ? 'help' : 'default' }}>
                      {l.total_ids}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {totalPages > 1 && (
          <div style={{ padding: '12px 22px', borderTop: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 12, color: MX.dim }}>{(pg - 1) * SA_PER_PAGE + 1}–{Math.min(pg * SA_PER_PAGE, filtered.length)} de {filtered.length}</span>
            <div style={{ display: 'flex', gap: 6 }}>
              <NavBtn disabled={pg === 1} onClick={() => setPage(p => p - 1)}>‹</NavBtn>
              <span style={{ fontSize: 12, color: MX.muted, padding: '3px 8px' }}>pág. {pg} / {totalPages}</span>
              <NavBtn disabled={pg === totalPages} onClick={() => setPage(p => p + 1)}>›</NavBtn>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Login History Tab ─────────────────────────────────────────────────────────

function LoginHistoryTab() {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const styleInput = window.styleInput;

  const [history, setHistory]   = useState([]);
  const [loading, setLoading]   = useState(true);
  const [busca,   setBusca]     = useState('');
  const [page,    setPage]      = useState(1);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await window.API.adminFetchLoginHistory(200);
      if (res?.success) setHistory(res.response);
    } catch { window.showToast && window.showToast({ message: 'Erro ao carregar histórico.', type: 'error' }); }
    finally { setLoading(false); }
  }, []);

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

  const filtered = useMemo(() => {
    const q = busca.toLowerCase();
    return !q ? history : history.filter(h => h.email.toLowerCase().includes(q));
  }, [history, busca]);

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

  const failRate = history.length > 0 ? Math.round((history.filter(h => !h.sucesso).length / history.length) * 100) : 0;

  return (
    <div>
      <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <input className="mx-input" placeholder="Filtrar por e-mail…" value={busca} onChange={e => setBusca(e.target.value)} style={{ ...styleInput, maxWidth: 300 }} />
        <span style={{ fontSize: 12.5, color: MX.dim, marginLeft: 4 }}>
          {history.filter(h => !h.sucesso).length} falha(s) nos últimos {history.length} registros
          {history.length > 0 && ` (${failRate}%)`}
        </span>
      </div>

      <div style={{ ...card, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
          <thead>
            <tr>
              <th style={thStyle}>Data/Hora</th>
              <th style={thStyle}>E-mail</th>
              <th style={thStyle}>Resultado</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={3} style={{ textAlign: 'center', padding: 48, color: MX.dim }}>Carregando…</td></tr>
            ) : paginados.length === 0 ? (
              <tr><td colSpan={3} style={{ textAlign: 'center', padding: 48, color: MX.dim }}>Nenhum registro encontrado.</td></tr>
            ) : paginados.map((h, i) => (
              <tr key={h._id} style={{ borderBottom: `1px solid ${MX.border}`, background: (!h.sucesso) ? MX.redSoft : (i % 2 === 0 ? MX.surface : MX.surface2) }}>
                <td style={{ padding: '12px 22px', color: MX.muted, fontSize: 12 }} className="mono">{fmtDate(h.dataHora)}</td>
                <td style={{ padding: '12px 22px', color: MX.text, fontWeight: 500 }} className="mono">{h.email}</td>
                <td style={{ padding: '12px 22px' }}>
                  <span style={{ background: h.sucesso ? MX.greenSoft : MX.redSoft, color: h.sucesso ? MX.green : MX.red, borderRadius: 999, padding: '3px 10px', fontSize: 11.5, fontWeight: 700 }}>
                    {h.sucesso ? '✓ Login OK' : '✕ Falha'}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {totalPages > 1 && (
          <div style={{ padding: '12px 22px', borderTop: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 12, color: MX.dim }}>{(pg - 1) * SA_PER_PAGE + 1}–{Math.min(pg * SA_PER_PAGE, filtered.length)} de {filtered.length}</span>
            <div style={{ display: 'flex', gap: 6 }}>
              <NavBtn disabled={pg === 1} onClick={() => setPage(p => p - 1)}>‹</NavBtn>
              <span style={{ fontSize: 12, color: MX.muted, padding: '3px 8px' }}>pág. {pg} / {totalPages}</span>
              <NavBtn disabled={pg === totalPages} onClick={() => setPage(p => p + 1)}>›</NavBtn>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Stats Tab ─────────────────────────────────────────────────────────────────

function StatsTab() {
  const MX = window.MX;
  const [stats,        setStats]        = useState(null);
  const [loading,      setLoading]      = useState(true);
  const [lastUpdated,  setLastUpdated]  = useState(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await window.API.adminFetchStats();
      if (res?.success) { setStats(res.response); setLastUpdated(new Date()); }
    } catch { window.showToast && window.showToast({ message: 'Erro ao carregar estatísticas.', type: 'error' }); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  const s = stats;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
        {lastUpdated && <span style={{ fontSize: 12, color: MX.dim }}>Atualizado: {lastUpdated.toLocaleTimeString('pt-BR')}</span>}
        <button onClick={load} disabled={loading} style={{ ...window.btnGhost, fontSize: 12.5, padding: '7px 14px', opacity: loading ? 0.6 : 1 }}>
          {loading ? 'Atualizando…' : 'Atualizar'}
        </button>
      </div>

      {loading && !s ? (
        <div style={{ textAlign: 'center', padding: 64, color: MX.dim }}>Carregando estatísticas…</div>
      ) : s && (
        <>
          <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>Usuários</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 14, marginBottom: 28 }}>
            <StatCard label="Usuários ativos"  value={s.usuarios_ativos}  color={MX.green}  sub={`de ${s.usuarios_total} total`} />
            <StatCard label="Falhas de login (24h)" value={s.falhas_login_24h} color={s.falhas_login_24h > 10 ? MX.red : MX.yellow} sub="tentativas falhas" />
          </div>

          <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>Operações</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 14, marginBottom: 28 }}>
            <StatCard label="Logs (24h)"     value={s.logs_24h}    color={MX.brand}  sub="operações nas últimas 24h" />
            <StatCard label="Logs (7 dias)"  value={s.logs_7d}     color={MX.purple} sub="operações nos últimos 7 dias" />
            <StatCard label="Total de logs"  value={s.logs_total}  sub="registros no banco" />
          </div>

          <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>Dados salvos</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 14 }}>
            <StatCard label="Grupos empresas"      value={s.grupos_empresas}     color={MX.blue}   sub="grupos salvos" />
            <StatCard label="Grupos entregadores"  value={s.grupos_entregadores} color={MX.cyan}   sub="grupos salvos" />
            <StatCard label="Exclusões empresas"   value={s.excl_empresas}       color={MX.red}    sub="empresas ignoradas" />
            <StatCard label="Exclusões entregadores" value={s.excl_entregadores} color={MX.yellow} sub="entregadores ignorados" />
          </div>
        </>
      )}
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────

function SuperAdminPage({ user }) {
  const MX = window.MX, card = window.card;
  const [tab, setTab] = useState('stats');

  if (!user || user.role !== 'super_admin') {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '60vh' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: MX.redSoft, color: MX.red, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px', fontSize: 26, fontWeight: 700 }}>✕</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: MX.text, marginBottom: 8 }}>Acesso negado</div>
          <div style={{ fontSize: 14, color: MX.muted }}>Esta área é restrita a super administradores.</div>
        </div>
      </div>
    );
  }

  const TABS = [
    { id: 'stats',         label: 'Visão Geral' },
    { id: 'usuarios',      label: 'Usuários' },
    { id: 'logs',          label: 'Logs Detalhados' },
    { id: 'login-history', label: 'Histórico de Login' },
  ];

  return (
    <div style={{ padding: '36px 40px 60px', maxWidth: 1280 }}>
      {/* Header */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Sistema</div>
          <span style={{ background: MX.purpleSoft, color: MX.purple, borderRadius: 999, padding: '1px 9px', fontSize: 10, fontWeight: 700, letterSpacing: '0.06em' }}>SUPER ADMIN</span>
        </div>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, color: MX.text, letterSpacing: '-0.025em' }}>Painel Dev</h1>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: MX.muted }}>Gerenciamento avançado de usuários, logs e monitoramento do sistema.</p>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 24, background: MX.surface2, border: `1px solid ${MX.border}`, borderRadius: 12, padding: 4, width: 'fit-content' }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 18px', borderRadius: 9, border: 'none', cursor: 'pointer',
            background: tab === t.id ? MX.surface : 'transparent',
            color: tab === t.id ? MX.text : MX.muted,
            fontSize: 13.5, fontWeight: tab === t.id ? 600 : 500,
            boxShadow: tab === t.id ? '0 1px 4px rgba(20,20,30,0.08)' : 'none',
            transition: 'all 0.15s',
          }}>{t.label}</button>
        ))}
      </div>

      {/* Content */}
      {tab === 'stats'         && <StatsTab />}
      {tab === 'usuarios'      && <UsuariosTab currentUser={user} />}
      {tab === 'logs'          && <LogsAdminTab />}
      {tab === 'login-history' && <LoginHistoryTab />}
    </div>
  );
}

Object.assign(window, { SuperAdminPage });
