import { Navigate, Route, Routes } from 'react-router-dom'
import { Layout } from './components/Layout'
import { Dashboard } from './pages/Dashboard'
import { NewCourse } from './pages/NewCourse'
import { CourseWorkspace } from './pages/CourseWorkspace'
import { AuthPage } from './pages/AuthPage'
import { Profile } from './pages/Profile'
import { AdminLayout } from './pages/admin/AdminLayout'
import { AdminDashboard } from './pages/admin/AdminDashboard'
import { AdminCourses } from './pages/admin/AdminCourses'
import { AdminCourseDetail } from './pages/admin/AdminCourseDetail'
import { AdminUsers } from './pages/admin/AdminUsers'
import { AdminLoginPage } from './pages/admin/AdminLoginPage'
import { useAuth } from './AuthContext'

export default function App() {
  const { user, loading } = useAuth()

  if (loading) return <div className="center-loading">正在加载星痕工坊…</div>

  return (
    <Routes>
      {/* ================= 管理员专属体系 (/admin/*) ================= */}
      <Route path="admin/login" element={<AdminLoginPage />} />
      <Route path="admin" element={<AdminLayout />}>
        <Route index element={<AdminDashboard />} />
        <Route path="courses" element={<AdminCourses />} />
        <Route path="courses/:id" element={<AdminCourseDetail />} />
        <Route path="users" element={<AdminUsers />} />
        <Route path="*" element={<Navigate to="/admin" replace />} />
      </Route>

      {/* ================= 普通用户体系 ================= */}
      <Route path="login" element={<AuthPage />} />
      {user ? (
        <Route element={<Layout />}>
          <Route index element={<Dashboard />} />
          <Route path="courses/new" element={<NewCourse />} />
          <Route path="courses/:id" element={<CourseWorkspace />} />
          <Route path="profile" element={<Profile />} />
        </Route>
      ) : null}

      {/* 默认兜底重定向 */}
      <Route path="*" element={<Navigate to={user ? '/' : '/login'} replace />} />
    </Routes>
  )
}
