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

// ============================================================================
// MoviXpress design system — light & dark tokens
// ============================================================================

const MX_LIGHT = {
  bg: '#F5F3EC', surface: '#FFFFFF', surface2: '#FAF9F4', surface3: '#F2F0E8',
  border: '#E8E5D8', borderMd: '#D8D4C2',
  text: '#15181F', muted: '#6B6F7A', dim: '#9CA0AA', faint: '#C4C7CF',
  brand: '#F26520', brandStrong: '#D4510E', brandSoft: '#FFF1E8', brandBg: '#FBE9DC',
  green: '#0E9F6E', greenSoft: '#E6F7EF',
  red: '#DC2626', redSoft: '#FBEAEA',
  yellow: '#B45309', yellowSoft: '#FBF1D9',
  blue: '#1D4ED8', blueSoft: '#E5EDFD',
  purple: '#6D28D9', purpleSoft: '#EFE7FB',
  cyan: '#0891B2', cyanSoft: '#DEF4F8',
};

const MX_DARK = {
  bg: '#111318', surface: '#1C1F2A', surface2: '#161820', surface3: '#20232E',
  border: '#2C2F3E', borderMd: '#3A3D50',
  text: '#F0EDE6', muted: '#8A8FA0', dim: '#606578', faint: '#3A3D50',
  brand: '#F26520', brandStrong: '#FF7A38', brandSoft: '#2A1508', brandBg: '#3A1C0A',
  green: '#10B981', greenSoft: '#0A2218',
  red: '#EF4444', redSoft: '#2A0E0E',
  yellow: '#F59E0B', yellowSoft: '#2A1C06',
  blue: '#3B82F6', blueSoft: '#0C1A38',
  purple: '#8B5CF6', purpleSoft: '#1A0E38',
  cyan: '#06B6D4', cyanSoft: '#071E28',
};

window.MX_LIGHT = MX_LIGHT;
window.MX_DARK  = MX_DARK;

function applyTheme(dark) {
  const M = dark ? MX_DARK : MX_LIGHT;
  window.MX = M;

  const root = document.documentElement;
  root.style.setProperty('--bg',           M.bg);
  root.style.setProperty('--surface',      M.surface);
  root.style.setProperty('--surface-2',    M.surface2);
  root.style.setProperty('--surface-3',    M.surface3);
  root.style.setProperty('--border',       M.border);
  root.style.setProperty('--text',         M.text);
  root.style.setProperty('--text-muted',   M.muted);
  root.style.setProperty('--text-dim',     M.dim);
  document.body.style.background = M.bg;
  document.body.style.color      = M.text;

  const sb = {
    padding: '10px 18px', borderRadius: 10, border: 'none',
    fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
    transition: 'all 0.15s', whiteSpace: 'nowrap',
  };
  window.card       = { background: M.surface, borderRadius: 16, border: `1px solid ${M.border}` };
  window.thStyle    = { padding: '12px 22px', textAlign: 'left', fontWeight: 600, fontSize: 11, letterSpacing: '0.06em', color: M.dim, textTransform: 'uppercase', borderBottom: `1px solid ${M.border}`, background: M.surface2, whiteSpace: 'nowrap' };
  window.styleInput = { flex: 1, padding: '10px 14px', borderRadius: 10, border: `1px solid ${M.border}`, background: M.surface, fontSize: 13.5, color: M.text, outline: 'none', minWidth: 0, transition: 'border-color 0.15s, box-shadow 0.15s' };
  window.styleBtn   = sb;
  window.btnPrimary = { ...sb, background: M.brand,    color: '#FFF' };
  window.btnGhost   = { ...sb, background: M.surface,  color: M.muted,        border: `1px solid ${M.border}` };
  window.btnSoft    = { ...sb, background: M.brandSoft, color: M.brandStrong,  border: `1px solid ${M.brandBg}` };
  window.btnDanger  = { ...sb, background: M.redSoft,  color: M.red,          border: `1px solid ${M.redSoft}` };
  window.iconBtn    = { width: 36, height: 36, borderRadius: 10, border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: M.muted, transition: 'all 0.15s' };
}

window.applyTheme = applyTheme;
applyTheme(localStorage.getItem('mx_dark') === '1');

// Category color mapping (Moto, Carro, Van, Bicicleta, Caminhão, Patinete)
const CAT_COLORS = {
  1: { fg: MX_LIGHT.brand,  bg: MX_LIGHT.brandSoft,  label: 'Moto' },
  2: { fg: MX_LIGHT.blue,   bg: MX_LIGHT.blueSoft,   label: 'Carro' },
  3: { fg: MX_LIGHT.purple, bg: MX_LIGHT.purpleSoft, label: 'Van' },
  4: { fg: MX_LIGHT.green,  bg: MX_LIGHT.greenSoft,  label: 'Bicicleta' },
  5: { fg: MX_LIGHT.red,    bg: MX_LIGHT.redSoft,    label: 'Caminhão' },
  6: { fg: MX_LIGHT.cyan,   bg: MX_LIGHT.cyanSoft,   label: 'Patinete' },
};
window.CAT_COLORS = CAT_COLORS;

function CategoryIcon({ id, size = 16 }) {
  const map = {
    1: <path d="M5 17a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM19 17a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM7 15h10l-2-6h-3l-2-3H7v4h3" />,
    2: <path d="M5 17h14M6 17v-4l2-5h8l2 5v4M8 17v2M16 17v2M9 12h6" />,
    3: <path d="M3 17h2m12 0h4M3 17V8h11l3 4h4v5h-2M3 17v-2M14 8v4h7" />,
    4: <path d="M5 17a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19 17a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM10 14l4-7h3M9 14h7l-3-7" />,
    5: <path d="M3 16h11V6H3zM14 11h4l3 3v2h-7zM7 19a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM18 19a2 2 0 1 0 0-4 2 2 0 0 0 0 4z" />,
    6: <path d="M6 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM18 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM7 16l4-9h3l1 9" />,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      {map[id] || map[1]}
    </svg>
  );
}
window.CategoryIcon = CategoryIcon;

function CatChip({ id, size = 'md' }) {
  const c = CAT_COLORS[id]; if (!c) return null;
  const small = size === 'sm';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: small ? 4 : 6,
      background: c.bg, color: c.fg,
      borderRadius: 999, padding: small ? '2px 8px 2px 6px' : '3px 10px 3px 7px',
      fontSize: small ? 11 : 11.5, fontWeight: 600, whiteSpace: 'nowrap',
    }}>
      <CategoryIcon id={id} size={small ? 11 : 13} />
      {c.label}
    </span>
  );
}
window.CatChip = CatChip;

function MxLogo({ size = 30 }) {
  return (
    <img
      src="uploads/LOGO-1.png"
      alt="MoviXpress"
      style={{
        width: size,
        height: size,
        objectFit: 'contain',
        flexShrink: 0
      }}
    />
  );
}
window.MxLogo = MxLogo;

// ============================================================================
// TOAST
// ============================================================================
function ToastItem({ id, message, type, onRemove }) {
  const MX = window.MX;
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const t1 = setTimeout(() => setVisible(true), 10);
    const t2 = setTimeout(() => setVisible(false), 3300);
    const t3 = setTimeout(() => onRemove(id), 3600);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);
  const cfg = {
    success: { fg: MX.green,  bg: MX.greenSoft,  icon: '✓' },
    error:   { fg: MX.red,    bg: MX.redSoft,    icon: '✕' },
    warning: { fg: MX.yellow, bg: MX.yellowSoft, icon: '!' },
    info:    { fg: MX.blue,   bg: MX.blueSoft,   icon: 'i' },
  }[type] || { fg: MX.blue, bg: MX.blueSoft, icon: 'i' };
  return (
    <div onClick={() => onRemove(id)} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      background: MX.surface,
      border: `1px solid ${MX.border}`,
      borderLeft: `3px solid ${cfg.fg}`,
      borderRadius: 12,
      padding: '12px 16px', maxWidth: 380, minWidth: 280,
      boxShadow: '0 12px 32px rgba(20,20,30,0.10)',
      cursor: 'pointer',
      transform: visible ? 'translateX(0) scale(1)' : 'translateX(130%) scale(0.95)',
      opacity: visible ? 1 : 0,
      transition: 'all 0.32s cubic-bezier(0.34,1.56,0.64,1)',
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: '50%',
        background: cfg.bg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: cfg.fg, fontSize: 12, fontWeight: 800, flexShrink: 0,
      }}>{cfg.icon}</div>
      <span style={{ fontSize: 13.5, color: MX.text, fontWeight: 500, lineHeight: 1.4, flex: 1 }}>{message}</span>
    </div>
  );
}

function ToastContainer() {
  const [toasts, setToasts] = useState([]);
  const addToast = useCallback(({ message, type = 'info' }) => {
    const id = Date.now() + Math.random();
    setToasts(prev => [...prev, { id, message, type }]);
  }, []);
  const removeToast = useCallback((id) => setToasts(prev => prev.filter(t => t.id !== id)), []);
  useEffect(() => { window.showToast = addToast; return () => { window.showToast = null; }; }, [addToast]);
  return (
    <div style={{ position: 'fixed', top: 84, right: 24, zIndex: 9999, display: 'flex', flexDirection: 'column', gap: 10, pointerEvents: 'none' }}>
      {toasts.map(t => (
        <div key={t.id} style={{ pointerEvents: 'all' }}>
          <ToastItem {...t} onRemove={removeToast} />
        </div>
      ))}
    </div>
  );
}

// ============================================================================
// CONFIRM MODAL
// ============================================================================
function ConfirmModal({ config, onClose }) {
  const MX = window.MX;
  if (!config) return null;
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      background: 'rgba(20,20,30,0.42)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{
        background: MX.surface,
        border: `1px solid ${MX.border}`,
        borderRadius: 16, padding: '32px 30px',
        maxWidth: 440, width: '90%',
        boxShadow: '0 32px 80px rgba(20,20,30,0.20)',
        animation: 'modalIn 0.22s ease',
      }}>
        <div style={{ marginBottom: 26 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: MX.yellowSoft, color: MX.yellow,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 18, fontSize: 20, fontWeight: 700,
          }}>!</div>
          <h3 style={{ margin: '0 0 8px', fontSize: 18, fontWeight: 700, color: MX.text, letterSpacing: '-0.01em' }}>
            {config.title || 'Confirmar ação'}
          </h3>
          <p style={{ margin: 0, fontSize: 14, color: MX.muted, lineHeight: 1.55 }}>{config.message}</p>
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={{
            padding: '11px 20px', borderRadius: 10,
            border: `1px solid ${MX.border}`, background: MX.surface, color: MX.muted,
            fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
          }}>Cancelar</button>
          <button onClick={() => { config.onConfirm(); onClose(); }} style={{
            padding: '11px 22px', borderRadius: 10, border: 'none',
            background: MX.brand, color: '#fff',
            fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
          }}>{config.confirmText || 'Confirmar'}</button>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// SETTINGS MODAL
// ============================================================================
function SettingsModal({ onClose, darkMode, onToggleDark, onReload, autoRefresh, onAutoRefreshChange, logs }) {
  const MX          = window.MX;
  const card        = window.card;
  const btnSoft     = window.btnSoft;
  const btnGhost    = window.btnGhost;
  const styleInput  = window.styleInput;
  const [reloading, setReloading] = useState(false);

  const handleReload = async () => {
    setReloading(true);
    try { await onReload(); } finally { setReloading(false); }
  };

  const exportLogs = () => {
    if (!logs || !logs.length) {
      window.showToast && window.showToast({ message: 'Nenhum log para exportar.', type: 'warning' });
      return;
    }
    const esc = s => `"${String(s || '').replace(/"/g, '""')}"`;
    const header = ['Data/Hora', 'Tipo', 'Entidade', 'Ação', 'Sucesso', 'Cidade'];
    const rows = logs.map(l => [
      l.dataHora ? new Date(l.dataHora).toLocaleString('pt-BR') : '',
      l.tipo || '',
      esc(l.entidade),
      esc(l.acao),
      l.sucesso ? 'Sim' : 'Não',
      l.cidade || 'tbt',
    ]);
    const csv = [header.join(','), ...rows.map(r => r.join(','))].join('\n');
    const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `logs_movixpress_${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    window.showToast && window.showToast({ message: `${logs.length} logs exportados com sucesso!`, type: 'success' });
  };

  const REFRESH_OPTS = [
    { value: '0',    label: 'Desativado' },
    { value: '300',  label: '5 minutos'  },
    { value: '600',  label: '10 minutos' },
    { value: '1800', label: '30 minutos' },
  ];

  const sec = { fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 14 };
  const hr  = { borderTop: `1px solid ${MX.border}`, margin: '22px 0' };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9100, background: 'rgba(20,20,30,0.42)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ ...card, padding: 28, width: 420, maxWidth: '93vw', animation: 'modalIn 0.22s ease', boxShadow: '0 32px 80px rgba(20,20,30,0.20)' }}>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 26 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 34, height: 34, borderRadius: 10, background: MX.surface2, border: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: MX.muted }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: MX.text, letterSpacing: '-0.01em' }}>Configurações</div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.dim, fontSize: 22, lineHeight: 1 }}>✕</button>
        </div>

        {/* Dados */}
        <div>
          <div style={sec}>Dados</div>
          <button onClick={handleReload} disabled={reloading} style={{ ...btnSoft, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, opacity: reloading ? 0.6 : 1 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"
                 style={{ animation: reloading ? 'spin 0.8s linear infinite' : 'none', transformOrigin: 'center' }}>
              <polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
            </svg>
            {reloading ? 'Recarregando…' : 'Recarregar dados'}
          </button>
        </div>

        <div style={hr} />

        {/* Aparência */}
        <div>
          <div style={sec}>Aparência</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500, color: MX.text }}>Tema escuro</div>
              <div style={{ fontSize: 12.5, color: MX.muted, marginTop: 3 }}>Alterna entre o tema claro e escuro</div>
            </div>
            <button
              onClick={() => onToggleDark(!darkMode)}
              style={{ width: 46, height: 26, borderRadius: 13, border: 'none', cursor: 'pointer', padding: 0, position: 'relative', transition: 'background 0.22s', background: darkMode ? MX.brand : MX.borderMd, flexShrink: 0 }}
            >
              <span style={{
                position: 'absolute', top: 3,
                left: darkMode ? 23 : 3,
                width: 20, height: 20, borderRadius: '50%',
                background: '#FFF', transition: 'left 0.22s',
                boxShadow: '0 1px 4px rgba(0,0,0,0.22)',
                display: 'block',
              }} />
            </button>
          </div>
        </div>

        <div style={hr} />

        {/* Auto-atualização */}
        <div>
          <div style={sec}>Auto-atualização</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500, color: MX.text }}>Intervalo de atualização</div>
              <div style={{ fontSize: 12.5, color: MX.muted, marginTop: 3 }}>Recarrega os dados automaticamente em background</div>
            </div>
            <select
              value={autoRefresh}
              onChange={e => onAutoRefreshChange(e.target.value)}
              className="mx-select"
              style={{ ...styleInput, flex: '0 0 auto', width: 148, padding: '8px 12px', fontSize: 13 }}
            >
              {REFRESH_OPTS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </div>
        </div>

        <div style={hr} />

        {/* Exportar logs */}
        <div>
          <div style={sec}>Logs</div>
          <button onClick={exportLogs} style={{ ...btnGhost, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="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>
            Exportar logs (.csv)
          </button>
        </div>

      </div>
    </div>
  );
}

// ============================================================================
// SIDEBAR
// ============================================================================
function AppSidebar({ currentPage, onNavigate, totalEmpresas, totalEntregadores, user }) {
  const MX = window.MX;
  const navItems = [
    { id: 'dashboard', label: 'Início',
      icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12l9-9 9 9v9a2 2 0 0 1-2 2h-4v-7h-6v7H5a2 2 0 0 1-2-2z"/></svg> },
    { id: 'empresas', label: 'Empresas',
      icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="7" width="18" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></svg> },
    { id: 'entregadores', label: 'Entregadores',
      icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.5"/><path d="M3 20v-1a5 5 0 0 1 5-5h2a5 5 0 0 1 5 5v1"/><circle cx="18" cy="9" r="2.5"/><path d="M16 20v-1a4 4 0 0 1 4-4"/></svg> },
    { id: 'logs', label: 'Logs',
      icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="14 3 14 9 20 9"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="13" y2="17"/></svg> },
  ];

  const navBtn = (item) => {
    const active = currentPage === item.id;
    return (
      <button
        key={item.id} data-active={active}
        onClick={() => onNavigate(item.id)}
        style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 12,
          padding: '11px 13px', borderRadius: 10, border: 'none',
          background: active ? MX.brandSoft : 'transparent',
          color: active ? MX.brandStrong : MX.muted,
          fontSize: 14, fontWeight: active ? 600 : 500,
          cursor: 'pointer', marginBottom: 3, textAlign: 'left',
          transition: 'all 0.15s',
        }}
      >
        <span className="nav-icon-wrap" style={{ display: 'flex', flexShrink: 0, color: active ? MX.brand : MX.dim, transition: 'color 0.15s' }}>{item.icon}</span>
        {item.label}
      </button>
    );
  };

  return (
    <aside style={{
      width: 240, minHeight: '100vh',
      background: MX.surface2,
      borderRight: `1px solid ${MX.border}`,
      display: 'flex', flexDirection: 'column',
      position: 'fixed', left: 0, top: 0, bottom: 0, zIndex: 100,
      paddingTop: 64,
    }}>
      <nav style={{ flex: 1, padding: '24px 14px 20px' }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.16em', color: MX.dim, padding: '0 12px', marginBottom: 12, textTransform: 'uppercase' }}>
          Gerenciamento
        </div>
        {navItems.map(navBtn)}

        {user?.role === 'super_admin' && (
          <>
            <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.16em', color: MX.dim, padding: '16px 12px 8px', textTransform: 'uppercase' }}>
              Sistema
            </div>
            {navBtn({
              id: 'super-admin',
              label: 'Dev Admin',
              icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>,
            })}
          </>
        )}
      </nav>

      <div style={{ padding: '20px 22px 22px', borderTop: `1px solid ${MX.border}` }}>
        <div style={{ fontSize: 11, color: MX.dim, marginBottom: 6, fontWeight: 500 }}>Empresas cadastradas</div>
        <div style={{ fontSize: 22, fontWeight: 700, color: MX.text, letterSpacing: '-0.02em', marginBottom: 12 }}>
          {totalEmpresas?.toLocaleString('pt-BR') || '—'}
        </div>
        <div style={{ fontSize: 11, color: MX.dim, marginBottom: 6, fontWeight: 500 }}>Entregadores</div>
        <div style={{ fontSize: 22, fontWeight: 700, color: MX.text, letterSpacing: '-0.02em' }}>
          {totalEntregadores?.toLocaleString('pt-BR') || '—'}
        </div>
      </div>
    </aside>
  );
}

// ============================================================================
// ACCOUNT SETTINGS MODAL
// ============================================================================
function AccountSettingsModal({ user, onClose, onUpdate }) {
  const MX       = window.MX;
  const card     = window.card;

  const [nome,            setNome]            = useState(user?.nome  || '');
  const [email,           setEmail]           = useState(user?.email || '');
  const [senhaAtual,      setSenhaAtual]      = useState('');
  const [novaSenha,       setNovaSenha]       = useState('');
  const [confirmarSenha,  setConfirmarSenha]  = useState('');
  const [loading,         setLoading]         = useState(false);
  const [error,           setError]           = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (!nome.trim())  { setError('O nome não pode estar vazio.');  return; }
    if (!email.trim()) { setError('O e-mail não pode estar vazio.'); return; }

    if (novaSenha) {
      if (novaSenha.length < 8)           { setError('A nova senha deve ter pelo menos 8 caracteres.'); return; }
      if (novaSenha !== confirmarSenha)    { setError('A confirmação da nova senha não coincide.'); return; }
      if (!senhaAtual)                     { setError('Informe a senha atual para trocar a senha.'); return; }
    }

    setLoading(true);
    try {
      const data = await window.API.updateProfile(
        nome,
        email,
        senhaAtual || undefined,
        novaSenha  || undefined,
      );
      onUpdate(data.user);
      window.showToast && window.showToast({ message: 'Perfil atualizado com sucesso!', type: 'success' });
      onClose();
    } catch (err) {
      setError(err.message || 'Erro ao atualizar perfil.');
    } finally {
      setLoading(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.1em', textTransform: 'uppercase' };
  const sec = { fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 14 };
  const hr  = { borderTop: `1px solid ${MX.border}`, margin: '22px 0' };

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

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 26 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 34, height: 34, borderRadius: 10, background: MX.surface2, border: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: MX.muted }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: MX.text, letterSpacing: '-0.01em' }}>Configurações da conta</div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: MX.dim, fontSize: 22, lineHeight: 1 }}>✕</button>
        </div>

        <form onSubmit={handleSubmit}>

          {/* Informações pessoais */}
          <div>
            <div style={sec}>Informações pessoais</div>
            <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} />
            </div>
            <div>
              <label style={lbl}>E-mail</label>
              <input className="mx-input" type="email" value={email} onChange={e => setEmail(e.target.value)} style={inputS} />
            </div>
          </div>

          <div style={hr} />

          {/* Alterar senha */}
          <div>
            <div style={sec}>
              Alterar senha
              <span style={{ fontWeight: 400, fontSize: 10, letterSpacing: 0, textTransform: 'none', color: MX.faint, marginLeft: 6 }}>(deixe em branco para não alterar)</span>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={lbl}>Senha atual</label>
              <input className="mx-input" type="password" value={senhaAtual} onChange={e => setSenhaAtual(e.target.value)} placeholder="••••••••" style={inputS} />
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={lbl}>Nova senha</label>
              <input className="mx-input" type="password" value={novaSenha} onChange={e => setNovaSenha(e.target.value)} placeholder="Mínimo 8 caracteres" style={inputS} />
            </div>
            <div>
              <label style={lbl}>Confirmar nova senha</label>
              <input className="mx-input" type="password" value={confirmarSenha} onChange={e => setConfirmarSenha(e.target.value)} placeholder="••••••••" style={inputS} />
            </div>
          </div>

          {error && (
            <div style={{ background: MX.redSoft, borderLeft: `3px solid ${MX.red}`, borderRadius: 10, padding: '11px 14px', marginTop: 18, fontSize: 13, color: MX.red, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontWeight: 700 }}>✕</span> {error}
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 26 }}>
            <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={loading} style={{ padding: '10px 22px', borderRadius: 10, border: 'none', background: loading ? MX.surface3 : MX.brand, color: loading ? MX.dim : '#FFF', fontSize: 13.5, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', transition: 'all 0.2s' }}>
              {loading ? 'Salvando…' : 'Salvar alterações'}
            </button>
          </div>

        </form>
      </div>
    </div>
  );
}

// ============================================================================
// TOP HEADER
// ============================================================================
function AppHeader({ user, onLogout, cidade = "tbt", onCidadeChange, onSettingsClick, onAccountSettingsClick }) {
  const MX = window.MX;
  const iconBtn = window.iconBtn;
  const [menuOpen, setMenuOpen] = useState(false);
  const ref = useRef(null);
  const CIDADES = [
    { id: "tbt", label: "Taubaté" },
    { id: "sjc", label: "São José dos Campos" },
  ];
  useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, height: 64, zIndex: 200,
      background: MX.surface2,
      borderBottom: `1px solid ${MX.border}`,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '0 28px 0 22px',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <MxLogo size={32} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <div style={{ color: MX.text, fontWeight: 700, fontSize: 15, letterSpacing: '-0.01em', lineHeight: 1 }}>
            movi<span style={{ color: MX.brand }}>x</span>press
          </div>
          <div style={{ color: MX.dim, fontSize: 10, fontWeight: 500, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
            Painel admin
          </div>
        </div>
      </div>

      {/* City switcher */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 2,
        background: MX.surface3, borderRadius: 10,
        border: `1px solid ${MX.border}`, padding: 3,
      }}>
        {CIDADES.map(c => (
          <button
            key={c.id}
            onClick={() => onCidadeChange && onCidadeChange(c.id)}
            style={{
              padding: '5px 14px', borderRadius: 8, border: 'none',
              fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
              transition: 'all 0.15s',
              background: cidade === c.id ? MX.brand : 'transparent',
              color: cidade === c.id ? '#FFF' : MX.muted,
              boxShadow: cidade === c.id ? '0 1px 4px rgba(242,101,32,0.3)' : 'none',
            }}
          >{c.label}</button>
        ))}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <button title="Configurações" onClick={onSettingsClick} style={iconBtn}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>
        </button>

        <div ref={ref} style={{ position: 'relative' }}>
          <button onClick={() => setMenuOpen(!menuOpen)} style={{
            display: 'flex', alignItems: 'center', gap: 9, marginLeft: 8,
            padding: '5px 10px 5px 5px', borderRadius: 99,
            border: `1px solid ${menuOpen ? MX.borderMd : MX.border}`,
            background: menuOpen ? MX.surface3 : MX.surface,
            cursor: 'pointer', transition: 'all 0.15s',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: '50%',
              background: MX.brand, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, fontWeight: 700,
            }}>{(user?.nome || 'A')[0].toUpperCase()}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: MX.text }}>
              {(user?.nome || 'Admin').split(' ')[0]}
            </div>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={MX.dim} strokeWidth="2"><polyline points="6 9 12 15 18 9"/></svg>
          </button>
          {menuOpen && (
            <div style={{
              position: 'absolute', top: 'calc(100% + 8px)', right: 0,
              background: MX.surface, border: `1px solid ${MX.border}`, borderRadius: 12,
              boxShadow: '0 18px 40px rgba(20,20,30,0.10)', minWidth: 240,
              padding: 8, animation: 'modalIn 0.18s ease',
            }}>
              <div style={{ padding: '10px 12px 12px', borderBottom: `1px solid ${MX.border}`, marginBottom: 6 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: MX.text }}>{user?.nome}</div>
                <div style={{ fontSize: 12, color: MX.muted, marginTop: 2 }}>{user?.email}</div>
              </div>
              <button onClick={() => { setMenuOpen(false); onAccountSettingsClick && onAccountSettingsClick(); }} style={{
                display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left',
                padding: '9px 12px', borderRadius: 8, border: 'none',
                background: 'transparent', cursor: 'pointer',
                fontSize: 13, color: MX.text, fontWeight: 500,
              }}
              onMouseEnter={e => e.currentTarget.style.background = MX.surface3}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M6 20v-1a6 6 0 0 1 12 0v1"/></svg>
                Configurações da conta
              </button>
              <button onClick={() => { setMenuOpen(false); onLogout(); }} style={{
                display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left',
                padding: '9px 12px', borderRadius: 8, border: 'none',
                background: 'transparent', cursor: 'pointer',
                fontSize: 13, color: MX.text, fontWeight: 500,
              }}
              onMouseEnter={e => e.currentTarget.style.background = MX.surface3}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
                Sair da conta
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

// ============================================================================
// BADGES
// ============================================================================
function StatusBadge({ color, label }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      background: color.bg, color: color.fg,
      borderRadius: 999, padding: '3px 10px 3px 8px',
      fontSize: 11.5, fontWeight: 600, whiteSpace: 'nowrap',
    }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: color.fg, flexShrink: 0 }}></span>
      {label}
    </span>
  );
}

function EmpresaStatusBadge({ status }) {
  const MX = window.MX;
  const map = {
    'ATIVO':               { fg: MX.green,  bg: MX.greenSoft,  label: 'Ativo' },
    'SUSPENSO':            { fg: MX.red,    bg: MX.redSoft,    label: 'Suspenso' },
    'AGUARDANDO ATIVAÇÃO': { fg: MX.yellow, bg: MX.yellowSoft, label: 'Aguardando' },
  };
  const c = map[status] || { fg: MX.muted, bg: MX.surface3, label: status };
  return <StatusBadge color={c} label={c.label} />;
}

function EntregadorStatusBadge({ status }) {
  const MX = window.MX;
  const map = {
    A: { label: 'Ativo',          fg: MX.green,  bg: MX.greenSoft  },
    E: { label: 'Em análise',     fg: MX.cyan,   bg: MX.cyanSoft   },
    F: { label: 'Fila de espera', fg: MX.yellow, bg: MX.yellowSoft },
    I: { label: 'Inativo',        fg: MX.muted,  bg: MX.surface3   },
    S: { label: 'Suspenso',       fg: MX.red,    bg: MX.redSoft    },
    R: { label: 'Rejeitado',      fg: MX.purple, bg: MX.purpleSoft },
    D: { label: 'Deletado',       fg: MX.faint,  bg: MX.surface3   },
  };
  const c = map[status] || { label: status, fg: MX.muted, bg: MX.surface3 };
  return <StatusBadge color={c} label={c.label} />;
}

function SkeletonTable({ rows = 6, cols = 4 }) {
  return (
    <div>
      {Array.from({ length: rows }).map((_, ri) => (
        <div key={ri} style={{ display: 'flex', gap: 16, padding: '16px 22px', borderBottom: `1px solid ${window.MX.border}`, alignItems: 'center' }}>
          {Array.from({ length: cols }).map((_, ci) => (
            <div key={ci} style={{
              flex: ci === 0 ? 0.4 : (ci === 1 ? 2.5 : 1), height: 12, borderRadius: 6,
              background: 'linear-gradient(90deg, #EFEDE4 25%, #F7F5EE 50%, #EFEDE4 75%)',
              backgroundSize: '200% 100%', animation: 'shimmer 1.6s infinite',
            }}></div>
          ))}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  ToastContainer, ConfirmModal, SettingsModal, AccountSettingsModal,
  AppSidebar, AppHeader,
  EmpresaStatusBadge, EntregadorStatusBadge, SkeletonTable,
  CategoryIcon, CatChip, MxLogo, StatusBadge,
});
