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

function LoginPage({ onLogin }) {
  const MX = window.MX, MxLogo = window.MxLogo;
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(''); setLoading(true);
    try {
      const data = await window.API.login(email, password);
      onLogin(data.user);
    } catch (err) {
      setError(err.message || 'E-mail ou senha inválidos.');
      setLoading(false);
    }
  };

  const inputS = {
    width: '100%', padding: '13px 16px', borderRadius: 11,
    border: `1px solid ${MX.border}`, background: MX.surface,
    fontSize: 14, color: MX.text, outline: 'none',
    transition: 'border-color 0.18s, box-shadow 0.18s',
  };

  return (
    <div style={{ minHeight: '100vh', background: MX.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px 20px' }}>
      <div style={{ width: '100%', maxWidth: 410 }}>
        <div style={{ marginBottom: 32, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <MxLogo size={48} />
          <div style={{ marginTop: 16, fontSize: 17, fontWeight: 700, color: MX.text, letterSpacing: '-0.01em' }}>
            movi<span style={{ color: MX.brand }}>x</span>press
          </div>
          <div style={{ fontSize: 11, color: MX.dim, marginTop: 4, fontWeight: 500, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
            Painel Admin
          </div>
        </div>

        <div style={{ background: MX.surface, borderRadius: 18, padding: '32px 30px', border: `1px solid ${MX.border}`, boxShadow: '0 12px 36px rgba(20,20,30,0.05)' }}>
          <h2 style={{ fontSize: 20, fontWeight: 700, color: MX.text, margin: '0 0 6px', letterSpacing: '-0.01em' }}>Entrar na conta</h2>
          <p style={{ fontSize: 13, color: MX.muted, margin: '0 0 24px' }}>Use suas credenciais de acesso</p>

          <form onSubmit={handleSubmit}>
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.1em', display: 'block', marginBottom: 7, textTransform: 'uppercase' }}>E-mail</label>
              <input className="mx-input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="seu@email.com" required style={inputS} />
            </div>
            <div style={{ marginBottom: 22 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.1em', display: 'block', marginBottom: 7, textTransform: 'uppercase' }}>Senha</label>
              <input className="mx-input" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" required style={inputS} />
            </div>

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

            <button type="submit" disabled={loading} style={{ width: '100%', padding: '13px', borderRadius: 11, border: 'none', background: loading ? MX.surface3 : MX.brand, color: loading ? MX.dim : '#FFF', fontSize: 14, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', transition: 'all 0.2s' }}>
              {loading ? 'Verificando…' : 'Entrar no sistema'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [loggedIn, setLoggedIn]       = useState(false);
  const [authChecked, setAuthChecked] = useState(false);
  const [user, setUser]               = useState(null);
  const [page, setPage]               = useState('dashboard');
  const [confirmConfig, setConfirmConfig] = useState(null);

  const [cidade,               setCidade]               = useState(() => localStorage.getItem('mx_cidade') || 'tbt');
  const [empresas,             setEmpresas]             = useState([]);
  const [entregadores,         setEntregadores]         = useState([]);
  const [logs,                 setLogs]                 = useState([]);
  const [gruposEmpresas,       setGruposEmpresas]       = useState([]);
  const [gruposEntregadores,   setGruposEntregadores]   = useState([]);
  const [exclusaoEmpresas,     setExclusaoEmpresas]     = useState([]);
  const [exclusaoEntregadores, setExclusaoEntregadores] = useState([]);
  const [categorias,           setCategorias]           = useState([]);
  const [apiLoading,           setApiLoading]           = useState(false);

  const [darkMode,             setDarkMode]             = useState(() => localStorage.getItem('mx_dark') === '1');
  const [autoRefresh,          setAutoRefresh]          = useState(() => localStorage.getItem('mx_refresh') || '0');
  const [showSettings,         setShowSettings]         = useState(false);
  const [showAccountSettings,  setShowAccountSettings]  = useState(false);

  const handleCidadeChange = useCallback((novaCidade) => {
    localStorage.setItem('mx_cidade', novaCidade);
    setCidade(novaCidade);
  }, []);

  const handleToggleDark = useCallback((val) => {
    window.applyTheme(val);
    localStorage.setItem('mx_dark', val ? '1' : '0');
    setDarkMode(val);
  }, []);

  const handleAutoRefreshChange = useCallback((val) => {
    localStorage.setItem('mx_refresh', val);
    setAutoRefresh(val);
  }, []);

  useEffect(() => {
    window.showConfirm = setConfirmConfig;
    window.addLog = (entry) => setLogs(prev => [entry, ...prev]);
  }, []);

  // Restaura sessão ao abrir o app
  useEffect(() => {
    window.API.me().then(data => {
      if (data?.user) {
        setUser(data.user);
        setLoggedIn(true);
      }
    }).finally(() => setAuthChecked(true));
  }, []);

  // Auto-logout quando o token expira (evento disparado pelo api-client.js)
  useEffect(() => {
    const onAutoLogout = () => {
      setLoggedIn(false);
      setUser(null);
      setPage('dashboard');
      window.showToast && window.showToast({ message: 'Sessão expirada. Faça login novamente.', type: 'warning' });
    };
    window.addEventListener('mx:logout', onAutoLogout);
    return () => window.removeEventListener('mx:logout', onAutoLogout);
  }, []);

  const loadData = useCallback(async () => {
    setApiLoading(true);
    try {
      const [catsRes, empRes, entRes, logsRes, gEmpRes, gEntRes, exEmpRes, exEntRes] = await Promise.all([
        window.API.fetchCategorias(cidade),
        window.API.fetchEmpresas(cidade),
        window.API.fetchEntregadores(cidade),
        window.API.fetchLogs(),
        window.API.fetchGruposEmpresas(),
        window.API.fetchGruposEntregadores(),
        window.API.fetchExclusaoEmpresas(),
        window.API.fetchExclusaoEntregadores(),
      ]);
      if (catsRes?.success)  setCategorias(catsRes.response);
      if (empRes?.success)   setEmpresas(empRes.response);
      if (entRes?.success)   setEntregadores(entRes.response);
      if (logsRes?.success)  setLogs(logsRes.response);
      if (gEmpRes?.success)  setGruposEmpresas(gEmpRes.response);
      if (gEntRes?.success)  setGruposEntregadores(gEntRes.response);
      if (exEmpRes?.success) setExclusaoEmpresas(exEmpRes.response);
      if (exEntRes?.success) setExclusaoEntregadores(exEntRes.response);
    } catch (err) {
      console.error("Erro ao carregar dados da API", err);
      window.showToast && window.showToast({ message: "Erro ao conectar à API", type: 'error' });
    } finally {
      setApiLoading(false);
    }
  }, [cidade]);

  // Carrega dados ao logar ou ao trocar de cidade
  useEffect(() => {
    if (!loggedIn) return;
    loadData();
  }, [loggedIn, cidade]);

  // Auto-atualização em background
  const autoRefreshRef = useRef(null);
  useEffect(() => {
    if (autoRefreshRef.current) clearInterval(autoRefreshRef.current);
    const secs = parseInt(autoRefresh);
    if (loggedIn && secs > 0) {
      autoRefreshRef.current = setInterval(loadData, secs * 1000);
    }
    return () => { if (autoRefreshRef.current) clearInterval(autoRefreshRef.current); };
  }, [autoRefresh, loggedIn, loadData]);

  // ── Callbacks Grupos Empresas ──────────────────────────────────────────────

  const onSaveGrupoEmpresas = useCallback(async (nomeGrupo, empresaRows) => {
    const payload = empresaRows.map(r => ({ id: r.id, nome: r.nome, categorias: Array.isArray(r.categorias) ? r.categorias.join(', ') : (r.categorias || '') }));
    const res = await window.API.saveGrupoEmpresas(nomeGrupo, payload);
    if (res.success) {
      setGruposEmpresas(prev => [...prev, { _id: res.id, nomeGrupo, empresas: payload }]);
      window.showToast && window.showToast({ message: `Grupo "${nomeGrupo}" salvo!`, type: 'success' });
    } else {
      window.showToast && window.showToast({ message: 'Erro ao salvar grupo.', type: 'error' });
    }
  }, []);

  const onUpdateGrupoEmpresas = useCallback(async (updatedGrupo) => {
    const payload = updatedGrupo.empresas.map(e => ({ id: e.id, nome: e.nome, categorias: Array.isArray(e.categorias) ? e.categorias.join(', ') : (e.categorias || '') }));
    const res = await window.API.updateGrupoEmpresas(updatedGrupo._id, updatedGrupo.nomeGrupo, payload);
    if (res.success) {
      setGruposEmpresas(prev => prev.map(g => g._id === updatedGrupo._id ? updatedGrupo : g));
    } else {
      window.showToast && window.showToast({ message: 'Erro ao atualizar grupo.', type: 'error' });
    }
  }, []);

  const onDeleteGrupoEmpresas = useCallback(async (grupoId) => {
    const res = await window.API.deleteGrupoEmpresas(grupoId);
    if (res.success) {
      setGruposEmpresas(prev => prev.filter(g => g._id !== grupoId));
      window.showToast && window.showToast({ message: 'Grupo excluído.', type: 'info' });
    } else {
      window.showToast && window.showToast({ message: 'Erro ao excluir grupo.', type: 'error' });
    }
  }, []);

  const onAddExclusaoEmpresa = useCallback(async (empresa_id, empresa_nome) => {
    const res = await window.API.addExclusaoEmpresa(empresa_id, empresa_nome);
    if (res.success) {
      setExclusaoEmpresas(prev => [...prev, { _id: res.id, id: empresa_id, nome_da_empresa: empresa_nome }]);
    } else {
      window.showToast && window.showToast({ message: res.error || 'Erro ao adicionar à exclusão.', type: 'error' });
    }
  }, []);

  const onRemoveExclusaoEmpresa = useCallback(async (rowId) => {
    const res = await window.API.deleteExclusaoEmpresa(rowId);
    if (res.success) {
      setExclusaoEmpresas(prev => prev.filter(e => e._id !== rowId));
    }
  }, []);

  // ── Callbacks Grupos Entregadores ──────────────────────────────────────────

  const onSaveGrupoEntregadores = useCallback(async (nomeGrupo, entRows, editingId = null) => {
    const payload = entRows.map(r => ({ id: r.id, nome: r.nome, situacaoCadastral: r.situacaoCadastral || r.status || '', vtr: r.vtr || '' }));
    if (editingId) {
      const res = await window.API.updateGrupoEntregadores(editingId, nomeGrupo, payload);
      if (res.success) {
        const updated = { _id: editingId, nomeGrupo, entregadores: entRows.map(r => r.nome), ids: entRows.map(r => r.id), situacaoCadastral: payload.map(r => r.situacaoCadastral), vtr: payload.map(r => r.vtr) };
        setGruposEntregadores(prev => prev.map(g => g._id === editingId ? updated : g));
        window.showToast && window.showToast({ message: `Grupo "${nomeGrupo}" atualizado!`, type: 'success' });
      } else {
        window.showToast && window.showToast({ message: 'Erro ao atualizar grupo.', type: 'error' });
      }
    } else {
      const res = await window.API.saveGrupoEntregadores(nomeGrupo, payload);
      if (res.success) {
        const novo = { _id: res.id, nomeGrupo, entregadores: entRows.map(r => r.nome), ids: entRows.map(r => r.id), situacaoCadastral: payload.map(r => r.situacaoCadastral), vtr: payload.map(r => r.vtr) };
        setGruposEntregadores(prev => [...prev, novo]);
        window.showToast && window.showToast({ message: `Grupo "${nomeGrupo}" salvo!`, type: 'success' });
      } else {
        window.showToast && window.showToast({ message: 'Erro ao salvar grupo.', type: 'error' });
      }
    }
  }, []);

  const onUpdateGrupoEntregadores = useCallback(async (updatedGrupo) => {
    const payload = updatedGrupo.ids.map((id, i) => ({ id, nome: updatedGrupo.entregadores[i], situacaoCadastral: updatedGrupo.situacaoCadastral[i] || '', vtr: updatedGrupo.vtr[i] || '' }));
    const res = await window.API.updateGrupoEntregadores(updatedGrupo._id, updatedGrupo.nomeGrupo, payload);
    if (res.success) {
      setGruposEntregadores(prev => prev.map(g => g._id === updatedGrupo._id ? updatedGrupo : g));
    } else {
      window.showToast && window.showToast({ message: 'Erro ao atualizar grupo.', type: 'error' });
    }
  }, []);

  const onDeleteGrupoEntregadores = useCallback(async (grupoId) => {
    const res = await window.API.deleteGrupoEntregadores(grupoId);
    if (res.success) {
      setGruposEntregadores(prev => prev.filter(g => g._id !== grupoId));
      window.showToast && window.showToast({ message: 'Grupo excluído.', type: 'info' });
    } else {
      window.showToast && window.showToast({ message: 'Erro ao excluir grupo.', type: 'error' });
    }
  }, []);

  const onAddExclusaoEntregador = useCallback(async (entregador_id, entregador_nome, vtr = '') => {
    const res = await window.API.addExclusaoEntregador(entregador_id, entregador_nome, vtr);
    if (res.success) {
      setExclusaoEntregadores(prev => [...prev, { _id: res.id, id: entregador_id, nome_do_entregador: entregador_nome, vtr }]);
    } else {
      window.showToast && window.showToast({ message: res.error || 'Erro ao adicionar à exclusão.', type: 'error' });
    }
  }, []);

  const onRemoveExclusaoEntregador = useCallback(async (rowId) => {
    const res = await window.API.deleteExclusaoEntregador(rowId);
    if (res.success) {
      setExclusaoEntregadores(prev => prev.filter(e => e._id !== rowId));
    }
  }, []);

  const ToastContainer        = window.ToastContainer;
  const ConfirmModal          = window.ConfirmModal;
  const SettingsModal         = window.SettingsModal;
  const AccountSettingsModal  = window.AccountSettingsModal;
  const AppSidebar            = window.AppSidebar;
  const AppHeader             = window.AppHeader;
  const DashboardPage    = window.DashboardPage;
  const EmpresasPage     = window.EmpresasPage;
  const EntregadoresPage = window.EntregadoresPage;
  const LogsPage         = window.LogsPage;
  const SuperAdminPage   = window.SuperAdminPage;

  if (!authChecked) return null;

  if (!loggedIn) return (
    <>
      <LoginPage onLogin={(u) => { setUser(u); setLoggedIn(true); }} />
      <ToastContainer />
    </>
  );

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: window.MX.bg }}>
      <AppHeader
        user={user}
        onLogout={() => { window.API.logout(); setLoggedIn(false); setUser(null); setPage('dashboard'); }}
        cidade={cidade}
        onCidadeChange={handleCidadeChange}
        onSettingsClick={() => setShowSettings(true)}
        onAccountSettingsClick={() => setShowAccountSettings(true)}
      />
      <AppSidebar currentPage={page} onNavigate={setPage} totalEmpresas={empresas.length} totalEntregadores={entregadores.length} user={user} />
      <main style={{ flex: 1, marginLeft: 240, paddingTop: 64, minHeight: '100vh', overflowX: 'hidden' }}>
        {page === 'dashboard' && (
          <DashboardPage empresas={empresas} entregadores={entregadores} logs={logs} categorias={categorias} onNavigate={setPage} isLoading={apiLoading} />
        )}
        {page === 'empresas' && (
          <EmpresasPage
            empresas={empresas} setEmpresas={setEmpresas}
            categorias={categorias}
            cidade={cidade}
            gruposEmpresas={gruposEmpresas}
            onSaveGrupo={onSaveGrupoEmpresas}
            onUpdateGrupo={onUpdateGrupoEmpresas}
            onDeleteGrupo={onDeleteGrupoEmpresas}
            exclusaoEmpresas={exclusaoEmpresas}
            onAddExclusao={onAddExclusaoEmpresa}
            onRemoveExclusao={onRemoveExclusaoEmpresa}
            isLoading={apiLoading}
          />
        )}
        {page === 'entregadores' && (
          <EntregadoresPage
            entregadores={entregadores} setEntregadores={setEntregadores}
            categorias={categorias}
            cidade={cidade}
            gruposEntregadores={gruposEntregadores}
            onSaveGrupo={onSaveGrupoEntregadores}
            onUpdateGrupo={onUpdateGrupoEntregadores}
            onDeleteGrupo={onDeleteGrupoEntregadores}
            exclusaoEntregadores={exclusaoEntregadores}
            onAddExclusao={onAddExclusaoEntregador}
            onRemoveExclusao={onRemoveExclusaoEntregador}
            isLoading={apiLoading}
          />
        )}
        {page === 'logs' && <LogsPage logs={logs} isLoading={apiLoading} />}
        {page === 'super-admin' && <SuperAdminPage user={user} />}
      </main>
      <ToastContainer />
      <ConfirmModal config={confirmConfig} onClose={() => setConfirmConfig(null)} />
      {showSettings && (
        <SettingsModal
          onClose={() => setShowSettings(false)}
          darkMode={darkMode}
          onToggleDark={handleToggleDark}
          onReload={loadData}
          autoRefresh={autoRefresh}
          onAutoRefreshChange={handleAutoRefreshChange}
          logs={logs}
        />
      )}
      {showAccountSettings && (
        <AccountSettingsModal
          user={user}
          onClose={() => setShowAccountSettings(false)}
          onUpdate={(updatedUser) => setUser(updatedUser)}
        />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
