import { useState } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import { useAuth } from "./context/AuthContext";
import Header from "./components/Header";
import MapPage from "./pages/MapPage";
import AccountPage from "./pages/AccountPage";
import AdminPage from "./pages/AdminPage";
import "./App.css";

export default function App() {
  const { user, authLoading } = useAuth();
  const [mapTitle, setMapTitle] = useState<string | null>(null);

  return (
    <div className="app">
      <Header mapTitle={mapTitle} />
      <div className="app-body">
        <Routes>
          <Route index element={<Navigate to="/map" replace />} />
          <Route path="/map" element={<MapPage setMapTitle={setMapTitle} />} />
          <Route
            path="/map/:mapId"
            element={<MapPage setMapTitle={setMapTitle} />}
          />
          <Route
            path="/account"
            element={
              authLoading ? null : user ? (
                <AccountPage />
              ) : (
                <Navigate to="/map" replace />
              )
            }
          />
          <Route
            path="/admin"
            element={
              authLoading ? null : user?.role === "admin" ? (
                <AdminPage />
              ) : (
                <Navigate to="/map" replace />
              )
            }
          />
          <Route path="*" element={<Navigate to="/map" replace />} />
        </Routes>
      </div>
    </div>
  );
}
