import { Routes, Route, Navigate } from 'react-router-dom'
import { useAuthStore } from '@/store/auth'

// Layout
import { Layout } from '@/components/layout/Layout'

// Pages
import { HomePage } from '@/pages/HomePage'
import { LoginPage } from '@/pages/LoginPage'
import { RegisterPage } from '@/pages/RegisterPage'
import { MarathonsPage } from '@/pages/MarathonsPage'
import { CreateMarathonPage } from '@/pages/CreateMarathonPage'
import { MarathonPage } from '@/pages/MarathonPage'
import { LobbyPage } from '@/pages/LobbyPage'
import { PlayPage } from '@/pages/PlayPage'
import { LeaderboardPage } from '@/pages/LeaderboardPage'

// Protected route wrapper
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  return <>{children}</>
}

// Public route wrapper (redirect if authenticated)
function PublicRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (isAuthenticated) {
    return <Navigate to="/marathons" replace />
  }

  return <>{children}</>
}

function App() {
  return (
    <Routes>
      <Route path="/" element={<Layout />}>
        <Route index element={<HomePage />} />

        <Route
          path="login"
          element={
            <PublicRoute>
              <LoginPage />
            </PublicRoute>
          }
        />

        <Route
          path="register"
          element={
            <PublicRoute>
              <RegisterPage />
            </PublicRoute>
          }
        />

        <Route
          path="marathons"
          element={
            <ProtectedRoute>
              <MarathonsPage />
            </ProtectedRoute>
          }
        />

        <Route
          path="marathons/create"
          element={
            <ProtectedRoute>
              <CreateMarathonPage />
            </ProtectedRoute>
          }
        />

        <Route
          path="marathons/:id"
          element={
            <ProtectedRoute>
              <MarathonPage />
            </ProtectedRoute>
          }
        />

        <Route
          path="marathons/:id/lobby"
          element={
            <ProtectedRoute>
              <LobbyPage />
            </ProtectedRoute>
          }
        />

        <Route
          path="marathons/:id/play"
          element={
            <ProtectedRoute>
              <PlayPage />
            </ProtectedRoute>
          }
        />

        <Route
          path="marathons/:id/leaderboard"
          element={
            <ProtectedRoute>
              <LeaderboardPage />
            </ProtectedRoute>
          }
        />
      </Route>
    </Routes>
  )
}

export default App
