import { Navigate, Route, Routes } from 'react-router-dom';
import { Layout } from '@/components/Layout';
import { ProtectedRoute } from '@/components/ProtectedRoute';
import { ToastViewport } from '@/components/Toast';
import { LoginPage } from '@/pages/LoginPage';
import { EngagementsListPage } from '@/pages/EngagementsListPage';
import { EngagementFormPage } from '@/pages/EngagementFormPage';
import { EngagementDetailPage } from '@/pages/EngagementDetailPage';
import { UsersAdminPage } from '@/pages/UsersAdminPage';

/**
 * Router. Auth + role gates handled by <ProtectedRoute />.
 * Default `/` redirects to /engagements (guarded — kicks to /login if no token).
 */
export function App(): JSX.Element {
  return (
    <>
      <Routes>
        <Route path="/login" element={<LoginPage />} />

        {/* All authenticated routes share the Layout chrome. */}
        <Route element={<ProtectedRoute />}>
          <Route element={<Layout />}>
            <Route path="/" element={<Navigate to="/engagements" replace />} />
            <Route path="/engagements" element={<EngagementsListPage />} />
            <Route path="/engagements/:id" element={<EngagementDetailPage />} />

            {/* redteam + admin write actions */}
            <Route element={<ProtectedRoute roles={['admin', 'redteam']} />}>
              <Route path="/engagements/new" element={<EngagementFormPage />} />
              <Route path="/engagements/:id/edit" element={<EngagementFormPage />} />
            </Route>

            {/* admin-only routes */}
            <Route element={<ProtectedRoute roles={['admin']} />}>
              <Route path="/admin/users" element={<UsersAdminPage />} />
            </Route>
          </Route>
        </Route>

        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>

      <ToastViewport />
    </>
  );
}
