import { useEffect, useState } from "react";
import { Routes, Route, useNavigate, useLocation } from "react-router-dom";

import LoginPage from "./pages/LoginPage";
import ModeSelectPage from "./pages/ModeSelectPage";
import QuizPage from "./pages/QuizPage";
import SolutionsPage from "./pages/SolutionsPage";

function App() {
  const [authenticated, setAuthenticated] = useState(false);
  const [mode, setMode] = useState(null);

  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const isAuth = sessionStorage.getItem("authenticated") === "true";
    const savedMode = sessionStorage.getItem("mode");
    if (isAuth) setAuthenticated(true);
    if (savedMode) setMode(savedMode);
  }, []);

  const handleModeSelect = (newMode) => {
    sessionStorage.setItem("mode", newMode);
    setMode(newMode);
  };


  if (location.pathname === "/solutions") {
    return <SolutionsPage mode={mode || "d"} onBack={() => navigate("/")} />;
  }

  if (!authenticated) return <LoginPage onSuccess={() => setAuthenticated(true)} />;
  if (!mode) return <ModeSelectPage onSelect={handleModeSelect} />;
  return <QuizPage mode={mode} onBack={() => setMode(null)} />;
}

export default App;
