import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { ThemeProvider } from './context/ThemeContext';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import Game from './pages/Game';
import Queue from './pages/Queue';
import RankedGame from './pages/RankedGame';
import Settings from './pages/Settings';
import About from './pages/About';
import FAQ from './pages/FAQ';

function getValidStoredToken() {
  const token = sessionStorage.getItem('ranked_token');
  if (!token) return null;
  try {
    const { exp } = JSON.parse(atob(token.split('.')[1]));
    if (exp * 1000 <= Date.now()) {
      sessionStorage.removeItem('ranked_token');
      return null;
    }
    return token;
  } catch {
    sessionStorage.removeItem('ranked_token');
    return null;
  }
}

// OAuth callback lands at /dashboard?token=<jwt> — token is in the URL, not yet
// in sessionStorage, so we must accept it here or the guard bounces the user back to /.
function hasUrlToken() {
  return !!new URLSearchParams(window.location.search).get('token');
}

export default function App() {
  const loggedIn = !!getValidStoredToken();
  return (
    <ThemeProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={loggedIn ? <Navigate to="/dashboard" replace /> : <Login />} />
          <Route path="/dashboard" element={(loggedIn || hasUrlToken()) ? <Dashboard /> : <Navigate to="/" replace />} />
          <Route path="/game" element={(loggedIn || hasUrlToken()) ? <Game />: <Navigate to="/" replace />} />
          <Route path="/queue" element={(loggedIn || hasUrlToken()) ? <Queue /> : <Navigate to="/" replace />} />
          <Route path="/ranked-game" element={(loggedIn || hasUrlToken()) ? <RankedGame /> : <Navigate to="/" replace />} />
          <Route path="/settings" element={(loggedIn || hasUrlToken()) ? <Settings /> : <Navigate to="/" replace />} />
          <Route path="/about" element={<About />} />
          <Route path="/faq" element={<FAQ />} />
        </Routes>
      </BrowserRouter>
    </ThemeProvider>
  );
}
