import { JSX, useContext } from "react";
import { Navigate, Route, BrowserRouter as Router, Routes } from "react-router-dom";
import { GameItemsContext, GameItemsProvider } from "./context/GameItemsContext";
import LobbyPage from "./pages/LobbyPage";
import LoginPage from "./pages/LoginPage";

function RequireAuth({ children }: { children: JSX.Element }) {
	const { player } = useContext(GameItemsContext);
	return player.token ? children : <Navigate to="/login" replace />;
}

export default function App() {
	return (
		<GameItemsProvider>
			<Router>
				<Routes>
					<Route path="/login" element={<LoginPage />} />
					<Route
						path="/lobby"
						element={
							<RequireAuth>
								<LobbyPage />
							</RequireAuth>
						}
					/>
					<Route path="*" element={<Navigate to="/login" replace />} />
				</Routes>
			</Router>
		</GameItemsProvider>
	);
}
