import { useEffect } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import MainLayout from "./layouts/MainLayout";
import FullWidthLayout from "./layouts/FullWidthLayout";
import Home from "./pages/Home";
import NewGame from "./pages/NewGame";
import PlayGame from "./pages/PlayGame";
import GameOver from "./pages/GameOver";
import History from "./pages/History";
import Players from "./pages/Players";
import Locations from "./pages/Locations";
import Profiles from "./pages/Profiles";
import Friends from "./pages/Friends";
import Games from "./pages/Games";
import ImportedGames from "./pages/ImportedGames";
import Auth from "./pages/Auth";
import Settings from "./pages/Settings";
import Statistics from "./pages/Stats";
import { useAppStore } from "./stores/appStore";
import { useProfileStore } from "./stores/profileStore";
import { useAuthStore } from "./stores/authStore";
import { startSyncTriggers } from "./sync/syncEngine";
import { startGamesRegistry } from "./games";

function App() {
  const { loadSettings } = useAppStore();
  const { loadProfiles } = useProfileStore();
  const restoreAuth = useAuthStore((s) => s.restore);

  useEffect(() => {
    startGamesRegistry();
    // Order matters: profiles must be loaded before auth restore triggers a sync.
    loadProfiles().then(() => {
      restoreAuth();
      startSyncTriggers();
    });
    loadSettings();
  }, [loadProfiles, loadSettings, restoreAuth]);

  return (
    <BrowserRouter>
      <Routes>
        <Route element={<MainLayout />}>
          <Route path="/" element={<Home />} />
          <Route path="/history" element={<History />} />
          <Route path="/jeux" element={<Games />} />
          <Route path="/players" element={<Players />} />
          <Route path="/locations" element={<Locations />} />
          <Route path="/profiles" element={<Profiles />} />
          <Route path="/friends" element={<Friends />} />
          <Route path="/games" element={<ImportedGames />} />
          <Route path="/login" element={<Auth />} />
          <Route path="/stats" element={<Statistics />} />
          <Route path="/settings" element={<Settings />} />
        </Route>
        <Route element={<FullWidthLayout />}>
          <Route path="/new/:gameId" element={<NewGame />} />
          <Route path="/play/:sessionId" element={<PlayGame />} />
          <Route path="/gameover/:sessionId" element={<GameOver />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;
