import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { ThemeProvider } from '@/lib/hooks/use-theme'
import { I18nProvider } from '@/lib/hooks/use-i18n'
import { Toaster } from '@/components/ui/sonner'
import { ServerProvidersInit } from '@/components/server-providers-init'
import { AccessCodeGuard } from '@/components/access-code-guard'
import { lazy, Suspense } from 'react'

// Lazy load pages for code splitting
const HomePage = lazy(() => import('@/pages/HomePage'))
const ClassroomPage = lazy(() => import('@/pages/ClassroomPage'))
const GenerationPreviewPage = lazy(() => import('@/pages/generation-preview/page'))
const WhiteboardEvalPage = lazy(() => import('@/pages/eval/whiteboard/page'))

function LoadingFallback() {
  return (
    <div className="flex-1 flex items-center justify-center min-h-screen bg-gray-50 dark:bg-gray-900">
      <div className="text-center text-muted-foreground">
        <p>Loading...</p>
      </div>
    </div>
  )
}

function AppLayout({ children }: { children: React.ReactNode }) {
  return (
    <ThemeProvider>
      <I18nProvider>
        <ServerProvidersInit />
        <AccessCodeGuard>{children}</AccessCodeGuard>
        <Toaster position="top-center" />
      </I18nProvider>
    </ThemeProvider>
  )
}

function App() {
  return (
    <BrowserRouter>
      <AppLayout>
        <Suspense fallback={<LoadingFallback />}>
          <Routes>
            <Route path="/" element={<HomePage />} />
            <Route path="/classroom/:id" element={<ClassroomPage />} />
            <Route path="/generation-preview" element={<GenerationPreviewPage />} />
            <Route path="/eval/whiteboard" element={<WhiteboardEvalPage />} />
          </Routes>
        </Suspense>
      </AppLayout>
    </BrowserRouter>
  )
}

export default App
