import { lazy, Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider } from './contexts/AuthContext';
import { ProtectedRoute } from './components/shared/ProtectedRoute';
import { IntranetLayout } from './components/layout/IntranetLayout';
import { PageLoader } from './components/shared/PageLoader';

// ── Pages (lazy-loaded) ──────────────────────────────────────────────────────

const LoginPage            = lazy(() => import('./pages/LoginPage'));
const IntranetDashboard    = lazy(() => import('./pages/intranet/IntranetDashboard'));
const IntranetBugs         = lazy(() => import('./pages/intranet/IntranetBugs'));
const IntranetFeed         = lazy(() => import('./pages/intranet/IntranetFeed'));
const IntranetEvents       = lazy(() => import('./pages/intranet/IntranetEvents'));
const IntranetUsers        = lazy(() => import('./pages/intranet/IntranetUsers'));
const IntranetModeration   = lazy(() => import('./pages/intranet/IntranetModeration'));
const IntranetServices     = lazy(() => import('./pages/intranet/IntranetServices'));

// ── App ────────────────────────────────────────────────────────────────────────

export default function App() {
  return (
    <AuthProvider>
      <Routes>
        {/* Login — own Suspense so the full-page loader only shows here */}
        <Route
          path="/login"
          element={
            <Suspense fallback={<PageLoader />}>
              <LoginPage />
            </Suspense>
          }
        />

        {/* Intranet (staff only) — Suspense is inside IntranetLayout */}
        <Route
          path="/intranet"
          element={
            <ProtectedRoute staffOnly redirectTo="/login">
              <IntranetLayout />
            </ProtectedRoute>
          }
        >
          <Route index element={<IntranetDashboard />} />
          <Route path="bugs" element={<IntranetBugs />} />
          <Route path="feed" element={<IntranetFeed />} />
          <Route path="events" element={<IntranetEvents />} />
          <Route path="users" element={<IntranetUsers />} />
          <Route path="moderation" element={<IntranetModeration />} />
          <Route path="services" element={<IntranetServices />} />
        </Route>

        {/* Redirect root to intranet */}
        <Route path="/" element={<Navigate to="/intranet" replace />} />

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