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) => {
    const savedMode = sessionStorage.getItem("mode");
    if (savedMode !== newMode) {
      sessionStorage.removeItem("quiz_questions");
      sessionStorage.removeItem("quiz_current_idx");
      sessionStorage.removeItem("quiz_score");
      sessionStorage.removeItem("quiz_wrong_questions");
      sessionStorage.removeItem("quiz_answer_status");
      sessionStorage.removeItem("quiz_processed");
    }
    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;
