import { Navigate, Route, Routes } from 'react-router-dom'
import { AppShell } from './layout/AppShell'
import { useAuthSession } from './features/auth/useAuthSession'
import { LoadingPage } from './pages/LoadingPage'
import { LoginPage } from './pages/LoginPage'
import { MainPage } from './pages/MainPage'
import { MatchesPage } from './pages/MatchesPage'
import { RegisterPage } from './pages/RegisterPage'
import { AdminCompetitionsPage } from './pages/AdminCompetitionsPage'
import { AdminTeamsPage } from './pages/AdminTeamsPage'
import { AdminMatchesPage } from './pages/AdminMatchesPage'
import { AdminPendingResultsPage } from './pages/AdminPendingResultsPage'
import { LeaderboardPage } from './pages/LeaderboardPage'

function App() {
  const { session, authLoading, handleLogin, handleLogout } = useAuthSession()

  if (authLoading) {
    return <LoadingPage />
  }

  return (
    <Routes>
      <Route
        path="/login"
        element={
          session ? (
            <Navigate to="/" replace />
          ) : (
            <LoginPage onLogin={handleLogin} />
          )
        }
      />
      <Route
        path="/register"
        element={
          session ? (
            <Navigate to="/" replace />
          ) : (
            <RegisterPage />
          )
        }
      />
      <Route
        path="/"
        element={
          session ? (
            <AppShell session={session} onLogout={handleLogout} />
          ) : (
            <Navigate to="/login" replace />
          )
        }
      >
        <Route index element={<MainPage />} />
        <Route path="matches" element={<MatchesPage />} />
        <Route path="leaderboard" element={<LeaderboardPage />} />
        <Route path="admin/pending-results" element={<AdminPendingResultsPage />} />
        <Route path="admin/competitions" element={<AdminCompetitionsPage />} />
        <Route path="admin/teams" element={<AdminTeamsPage />} />
        <Route path="admin/matches" element={<AdminMatchesPage />} />
      </Route>
      <Route
        path="*"
        element={<Navigate to={session ? '/' : '/login'} replace />}
      />
    </Routes>
  )
}

export default App
