import { lazy, Suspense } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { Layout } from './components/layout/Layout'
import { useAuth } from './contexts/AuthContext'

const Dashboard = lazy(() => import('./pages/Dashboard').then(m => ({ default: m.Dashboard })))
const Models = lazy(() => import('./pages/Models').then(m => ({ default: m.Models })))
const Datasets = lazy(() => import('./pages/Datasets').then(m => ({ default: m.Datasets })))
const Training = lazy(() => import('./pages/Training').then(m => ({ default: m.Training })))
const Evaluation = lazy(() => import('./pages/Evaluation').then(m => ({ default: m.Evaluation })))
const Deployment = lazy(() => import('./pages/Deployment').then(m => ({ default: m.Deployment })))
const Inference = lazy(() => import('./pages/Inference').then(m => ({ default: m.Inference })))
const Login = lazy(() => import('./pages/AuthLogin').then(m => ({ default: m.Login })))
const AuthCallback = lazy(() => import('./pages/AuthCallback').then(m => ({ default: m.AuthCallback })))

function PageFallback() {
  return <div style={{ padding: 24, color: '#94a3b8' }}>加载中...</div>
}

function AuthRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuth()
  return isAuthenticated ? <>{children}</> : <Navigate to="/login" replace />
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<Suspense fallback={<PageFallback />}><Login /></Suspense>} />
      <Route path="/auth/callback" element={<Suspense fallback={<PageFallback />}><AuthCallback /></Suspense>} />
      <Route path="/*" element={
        <AuthRoute>
          <Layout>
            <Suspense fallback={<PageFallback />}>
              <Routes>
                <Route path="/" element={<Dashboard />} />
                <Route path="/models" element={<Models />} />
                <Route path="/datasets" element={<Datasets />} />
                <Route path="/training" element={<Training />} />
                <Route path="/evaluation" element={<Evaluation />} />
                <Route path="/deployment" element={<Deployment />} />
                <Route path="/inference" element={<Inference />} />
              </Routes>
            </Suspense>
          </Layout>
        </AuthRoute>
      } />
    </Routes>
  )
}
