import { Routes, Route, Navigate } from "react-router-dom";
import { AuthProvider, useAuth } from "@/context/Auth";
import { AppShell } from "@/components/AppShell";
import { LoadingState } from "@/components/ui";
import { DashboardPage } from "@/pages/Dashboard";
import { AttendancePage } from "@/pages/Attendance";
import { ProjectsPage } from "@/pages/Projects";
import { ProjectDetailPage } from "@/pages/ProjectDetail";
import { IncentivePage } from "@/pages/Incentive";
import { ProfilePage } from "@/pages/Profile";
import { InboxPage } from "@/pages/Inbox";
import { ApprovalsPage } from "@/pages/admin/Approvals";
import { AttendanceAdminPage } from "@/pages/admin/AttendanceAdmin";
import { ProjectsAdminPage } from "@/pages/admin/ProjectsAdmin";
import { IncentiveAdminPage } from "@/pages/admin/IncentiveAdmin";
import { AccountingPage } from "@/pages/admin/Accounting";
import { MembersPage } from "@/pages/admin/Members";
import { SettingsPage } from "@/pages/admin/Settings";

function RequireAdmin({ children }: { children: JSX.Element }) {
  const { isAdmin, loading } = useAuth();
  if (loading) return <LoadingState />;
  return isAdmin ? children : <Navigate to="/" replace />;
}

function Shell() {
  const { loading } = useAuth();
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-canvas">
        <LoadingState label="spin 로딩 중…" />
      </div>
    );
  }
  return (
    <Routes>
      <Route element={<AppShell />}>
        <Route path="/" element={<DashboardPage />} />
        <Route path="/attendance" element={<AttendancePage />} />
        <Route path="/projects" element={<ProjectsPage />} />
        <Route path="/projects/:id" element={<ProjectDetailPage />} />
        <Route path="/incentive" element={<IncentivePage />} />
        <Route path="/profile" element={<ProfilePage />} />
        <Route path="/inbox" element={<InboxPage />} />
        <Route path="/admin/approvals" element={<RequireAdmin><ApprovalsPage /></RequireAdmin>} />
        <Route path="/admin/attendance" element={<RequireAdmin><AttendanceAdminPage /></RequireAdmin>} />
        <Route path="/admin/projects" element={<RequireAdmin><ProjectsAdminPage /></RequireAdmin>} />
        <Route path="/admin/incentive" element={<RequireAdmin><IncentiveAdminPage /></RequireAdmin>} />
        <Route path="/admin/accounting" element={<RequireAdmin><AccountingPage /></RequireAdmin>} />
        <Route path="/admin/members" element={<RequireAdmin><MembersPage /></RequireAdmin>} />
        <Route path="/admin/settings" element={<RequireAdmin><SettingsPage /></RequireAdmin>} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Route>
    </Routes>
  );
}

export default function App() {
  return (
    <AuthProvider>
      <Shell />
    </AuthProvider>
  );
}
