import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import { ThemeProvider } from './context/ThemeContext';
import { ProjectProvider } from './context/ProjectContext';
import { PermissionsProvider } from './context/PermissionsContext';
import { LanguageProvider } from './context/LanguageContext';
import Layout from './components/shared/Layout';

const LoginPage     = lazy(() => import('./components/auth/LoginPage'));
const Dashboard     = lazy(() => import('./components/dashboard/Dashboard'));
const ProjectsPage  = lazy(() => import('./components/projects/ProjectsPage'));
const ProjectDetail = lazy(() => import('./components/projects/ProjectDetail'));
const GanttPage        = lazy(() => import('./components/gantt/GanttPage'));
const BudgetPage       = lazy(() => import('./components/budget/BudgetPage'));
const TeamPage         = lazy(() => import('./components/team/TeamPage'));
const ReportsPage      = lazy(() => import('./components/reports/ReportsPage'));
const NewProjectPage   = lazy(() => import('./components/projects/NewProjectPage'));
const WBSPage          = lazy(() => import('./components/wbs/WBSPage'));
const RisksPage        = lazy(() => import('./components/risks/RisksPage'));
const EVMPage          = lazy(() => import('./components/evm/EVMPage'));
const MessagesPage     = lazy(() => import('./components/messages/MessagesPage'));
const WorkOrdersPage   = lazy(() => import('./components/workorders/WorkOrdersPage'));
const ProcurementPage  = lazy(() => import('./components/procurement/ProcurementPage'));
const ResourcesPage    = lazy(() => import('./components/resources/ResourcesPage'));
const SettingsPage          = lazy(() => import('./components/settings/SettingsPage'));
const AccountingPage        = lazy(() => import('./components/accounting/AccountingPage'));
const UsersPage              = lazy(() => import('./components/admin/UsersPage'));
const ProjectFinancialReport = lazy(() => import('./components/reports/ProjectFinancialReport'));
const BillingPage            = lazy(() => import('./components/billing/BillingPage'));
const DocumentsPage          = lazy(() => import('./components/documents/DocumentsPage'));
const QualityPage            = lazy(() => import('./components/quality/QualityPage'));
const HSEPage                = lazy(() => import('./components/hse/HSEPage'));
const BidsPage               = lazy(() => import('./components/bids/BidsPage'));
const ContractsPage          = lazy(() => import('./components/contracts/ContractsPage'));
const VendorsPage            = lazy(() => import('./components/vendors/VendorsPage'));
const ChangeManagementPage   = lazy(() => import('./components/changes/ChangeManagementPage'));
const ReceptionPage          = lazy(() => import('./components/reception/ReceptionPage'));
const ProjectClosurePage     = lazy(() => import('./components/closure/ProjectClosurePage'));
const ClientPortalPage       = lazy(() => import('./components/client/ClientPortalPage'));
const PortfolioPage      = lazy(() => import('./components/portfolio/PortfolioPage'));
const BurndownPage       = lazy(() => import('./components/burndown/BurndownPage'));
const TimeTrackingPage   = lazy(() => import('./components/timetracking/TimeTrackingPage'));
const MeetingsPage       = lazy(() => import('./components/meetings/MeetingsPage'));
const LessonsLearnedPage = lazy(() => import('./components/lessons/LessonsLearnedPage'));
const ScenarioSimulatorPage = lazy(() => import('./components/simulator/ScenarioSimulatorPage'));
const StandupPage           = lazy(() => import('./components/standup/StandupPage'));
const ResourceCalendarPage  = lazy(() => import('./components/resources/ResourceCalendarPage'));
const PDFExportPage = lazy(() => import('./components/exports/PDFExportPage'));
const NPSPage       = lazy(() => import('./components/nps/NPSPage'));

const Spinner = () => (
  <div className="flex items-center justify-center h-screen bg-slate-50 dark:bg-surface-900 transition-colors">
    <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
  </div>
);

function PrivateRoute({ children }) {
  const { user, loading } = useAuth();
  if (loading) return <Spinner />;
  return user ? children : <Navigate to="/login" replace />;
}

function PublicRoute({ children }) {
  const { user, loading } = useAuth();
  if (loading) return null;
  return user ? <Navigate to="/" replace /> : children;
}

export default function App() {
  return (
    <ThemeProvider>
      <LanguageProvider>
      <AuthProvider>
        <ProjectProvider>
        <PermissionsProvider>
        <BrowserRouter>
          <Suspense fallback={<Spinner />}>
            <Routes>
              <Route path="/login" element={<PublicRoute><LoginPage /></PublicRoute>} />
              <Route path="/" element={<PrivateRoute><Layout /></PrivateRoute>}>
                <Route index element={<Dashboard />} />
                <Route path="projects" element={<ProjectsPage />} />
                <Route path="projects/:id" element={<ProjectDetail />} />
                <Route path="projects/new" element={<NewProjectPage />} />
                <Route path="gantt"        element={<GanttPage />} />
                <Route path="budget"       element={<BudgetPage />} />
                <Route path="team"         element={<TeamPage />} />
                <Route path="reports"      element={<ReportsPage />} />
                <Route path="wbs"          element={<WBSPage />} />
                <Route path="risks"        element={<RisksPage />} />
                <Route path="evm"          element={<EVMPage />} />
                <Route path="messages"     element={<MessagesPage />} />
                <Route path="work-orders" element={<WorkOrdersPage />} />
                <Route path="procurement" element={<ProcurementPage />} />
                <Route path="resources"  element={<ResourcesPage />} />
                <Route path="settings"          element={<SettingsPage />} />
                <Route path="accounting"       element={<AccountingPage />} />
                <Route path="financial-report" element={<ProjectFinancialReport />} />
                <Route path="admin/users"     element={<UsersPage />} />
                <Route path="billing"         element={<BillingPage />} />
                <Route path="documents"       element={<DocumentsPage />} />
                <Route path="quality"         element={<QualityPage />} />
                <Route path="hse"             element={<HSEPage />} />
                <Route path="bids"            element={<BidsPage />} />
                <Route path="contracts"       element={<ContractsPage />} />
                <Route path="vendors"         element={<VendorsPage />} />
                <Route path="changes"         element={<ChangeManagementPage />} />
                <Route path="reception"      element={<ReceptionPage />} />
                <Route path="project-closure" element={<ProjectClosurePage />} />
                <Route path="client-portal"  element={<ClientPortalPage />} />
                <Route path="portfolio"      element={<PortfolioPage />} />
                <Route path="burndown"       element={<BurndownPage />} />
                <Route path="time-tracking"  element={<TimeTrackingPage />} />
                <Route path="meetings"       element={<MeetingsPage />} />
                <Route path="lessons"        element={<LessonsLearnedPage />} />
                <Route path="simulator"         element={<ScenarioSimulatorPage />} />
                <Route path="standup"           element={<StandupPage />} />
                <Route path="resource-calendar" element={<ResourceCalendarPage />} />
                <Route path="exports" element={<PDFExportPage />} />
                <Route path="nps"     element={<NPSPage />} />
              </Route>
            </Routes>
          </Suspense>
        </BrowserRouter>
        </PermissionsProvider>
        </ProjectProvider>
      </AuthProvider>
      </LanguageProvider>
    </ThemeProvider>
  );
}
