import { useEffect } from 'react';
import { BrowserRouter, Navigate, Routes, Route } from 'react-router-dom';
import { useAuth } from '../contexts';
import { AppShell } from '../components/layout/AppShell';
import { LoginPage } from '../pages/Login/LoginPage';
import { OverviewPage } from '../pages/Overview/OverviewPage';
import { StatusPage } from '../pages/Status/StatusPage';
import { PerceptionPage } from '../pages/Perception/PerceptionPage';
import { DocsPage } from '../pages/Docs/DocsPage';
import { CompliancePage } from '../pages/Compliance/CompliancePage';
import { RagChatPage } from '../pages/RagChat/RagChatPage';

/** Redirect to /login when not authenticated. */
function RequireAuth({ children }: { children: React.ReactNode }) {
  const { token, loading } = useAuth();
  if (loading) return null; // wait for localStorage token validation
  if (!token) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

/** Redirect to / when already authenticated. */
function GuestOnly({ children }: { children: React.ReactNode }) {
  const { token, loading } = useAuth();
  if (loading) return null;
  if (token) return <Navigate to="/" replace />;
  return <>{children}</>;
}

export function AppRouter() {
  const { logout } = useAuth();

  // Listen for global 401 events emitted by the API layer.
  useEffect(() => {
    function onUnauthorized() { logout(); }
    window.addEventListener('auth:unauthorized', onUnauthorized);
    return () => window.removeEventListener('auth:unauthorized', onUnauthorized);
  }, [logout]);

  return (
    <BrowserRouter>
      <Routes>
        {/* Public route */}
        <Route path="/login" element={<GuestOnly><LoginPage /></GuestOnly>} />

        {/* Protected routes */}
        <Route
          path="/"
          element={
            <RequireAuth>
              <AppShell />
            </RequireAuth>
          }
        >
          <Route index element={<OverviewPage />} />
          <Route path="status" element={<StatusPage />} />
          <Route path="signals" element={<PerceptionPage />} />
          <Route path="documents" element={<DocsPage />} />
          <Route path="compliance" element={<CompliancePage />} />
          <Route path="chat" element={<RagChatPage />} />
        </Route>

        {/* Catch-all */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </BrowserRouter>
  );
}
