import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { AdminRoute } from './components/AdminRoute';
import { ProtectedRoute } from './components/ProtectedRoute';
import { AuthProvider, useAuth } from './context/AuthContext';
import { AdminLayout } from './layouts/AdminLayout';
import { UserLayout } from './layouts/UserLayout';
import { AdminHomePage } from './pages/admin/AdminHomePage';
import { RolesPage } from './pages/admin/RolesPage';
import { UserRolesPage } from './pages/admin/UserRolesPage';
import { RolePermissionsPage } from './pages/admin/RolePermissionsPage';
import { ConfirmPage } from './pages/user/ConfirmPage';
import { ForgotPasswordPage } from './pages/user/ForgotPasswordPage';
import { HomePage } from './pages/user/HomePage';
import { LoginPage } from './pages/user/LoginPage';
import { OAuthCallbackPage } from './pages/user/OAuthCallbackPage';
import { ProfilePage } from './pages/user/ProfilePage';
import { RegisterPage } from './pages/user/RegisterPage';
import { SecurityPage } from './pages/user/SecurityPage';
import './App.css';

function RootRedirect() {
  const { ready, token } = useAuth();
  if (!ready) return <p className="loading">載入中…</p>;
  return <Navigate to={token ? '/app' : '/login'} replace />;
}

function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route
            path="/auth/callback/login"
            element={<OAuthCallbackPage mode="login" />}
          />
          <Route path="/register" element={<RegisterPage />} />
          <Route
            path="/auth/callback/register"
            element={<OAuthCallbackPage mode="register" />}
          />
          <Route path="/register/confirm" element={<ConfirmPage />} />
          <Route path="/password/forgot" element={<ForgotPasswordPage />} />

          <Route element={<ProtectedRoute />}>
            <Route element={<UserLayout />}>
              <Route path="/app" element={<HomePage />} />
              <Route path="/app/profile" element={<ProfilePage />} />
              <Route path="/app/security" element={<SecurityPage />} />
            </Route>
          </Route>

          <Route element={<AdminRoute />}>
            <Route element={<AdminLayout />}>
              <Route path="/admin" element={<AdminHomePage />} />
              <Route path="/admin/roles" element={<RolesPage />} />
              <Route path="/admin/role-permissions" element={<RolePermissionsPage />} />
              <Route path="/admin/users" element={<UserRolesPage />} />
            </Route>
          </Route>

          <Route path="/" element={<RootRedirect />} />
          <Route path="*" element={<RootRedirect />} />
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  );
}

export default App;
