import { lazy, Suspense } from 'react'
import { Navigate, Route, Routes } from 'react-router-dom'
import { AppShell } from './components/AppShell'
import LoginPage from './pages/LoginPage'
import { usePortal } from './state/PortalContext'
import { roleHomes } from './utils'

const DirectorDashboard = lazy(() => import('./pages/DirectorDashboard'))
const AdminDashboard = lazy(() => import('./pages/AdminDashboard'))
const ApprovalsPage = lazy(() => import('./pages/ApprovalsPage'))
const RequisitionsPage = lazy(() => import('./pages/RequisitionsPage'))
const RequisitionDetailPage = lazy(() => import('./pages/RequisitionDetailPage'))
const CapacityPage = lazy(() => import('./pages/CapacityPage'))
const ReportsPage = lazy(() => import('./pages/ReportsPage'))
const NotificationsPage = lazy(() => import('./pages/NotificationsPage'))
const NewRequisitionPage = lazy(() => import('./pages/NewRequisitionPage'))
const PipelinePage = lazy(() => import('./pages/PipelinePage'))

function LoadingPage() {
  return <div className="loading-page" role="status"><span /><p>Cargando vista…</p></div>
}

export function App() {
  const { authenticated, role } = usePortal()

  if (!authenticated) {
    return <Routes><Route path="*" element={<LoginPage />} /></Routes>
  }

  return (
    <Suspense fallback={<LoadingPage />}>
      <Routes>
        <Route element={<AppShell />}>
          <Route index element={<Navigate to={roleHomes[role]} replace />} />
          <Route path="dashboard" element={<DirectorDashboard />} />
          <Route path="administracion" element={<AdminDashboard />} />
          <Route path="aprobaciones" element={<ApprovalsPage />} />
          <Route path="requisiciones" element={<RequisitionsPage />} />
          <Route path="mis-requisiciones" element={<RequisitionsPage ownOnly />} />
          <Route path="requisiciones/nueva" element={<NewRequisitionPage />} />
          <Route path="requisiciones/:id" element={<RequisitionDetailPage />} />
          <Route path="capacidad" element={<CapacityPage />} />
          <Route path="reportes" element={<ReportsPage />} />
          <Route path="pipeline" element={<PipelinePage />} />
          <Route path="notificaciones" element={<NotificationsPage />} />
          <Route path="*" element={<Navigate to={roleHomes[role]} replace />} />
        </Route>
      </Routes>
    </Suspense>
  )
}
