import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import Home from './pages/Home';
import WebLayout from "./layouts/WebLayout";
import NotFound from './pages/NotFound';

import ROUTE_CONSTANTS from './types/routes';
import Create from './pages/Create';
import Favorites from './pages/Favorites';
import Profile from './pages/Profile';
import ShoppingList from './pages/ShoppingList';
import LoginPage from './pages/Login';
import { use, type ReactNode } from 'react';
import { AuthContext } from './context/AuthContext';
import RecipePage from './pages/Recipe';
import SearchPage from './pages/Search';

function ProtectedRoute({ children }: { children: ReactNode }) {
  const { isLoggedIn } = use(AuthContext)
  // Wait until the value is set
  if (isLoggedIn === undefined) {
    // Still checking auth state: don't render anything yet, or show a spinner if desired
    return null; // or <Loading />
  }

  if (isLoggedIn) return children;

  // Redirect to login page if not authenicated
  return <Navigate to="/v2/web/login" replace />
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Navigate to={ROUTE_CONSTANTS.Home} replace />} />

        {/* Login page does not inherit WebLayout */}
        <Route path="/v2/web/login" element={<LoginPage />} />

        <Route path="/v2/web" element={<WebLayout />}>
          <Route index element={<Navigate to={ROUTE_CONSTANTS.Home} replace />} />
          <Route path="home" element={<Home />} />
          <Route path="search" element={<SearchPage />} />
          <Route path="favorites" element={<ProtectedRoute><Favorites /></ProtectedRoute>} />
          <Route path="create" element={<ProtectedRoute><Create /></ProtectedRoute>} />
          <Route path="profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />
          <Route path="list" element={<ProtectedRoute><ShoppingList /></ProtectedRoute>} />

          <Route path="recipe/:id" element={<RecipePage />} />

        </Route>

        {/* 404: Not Found */}
        <Route path="*" element={<WebLayout />}>
          <Route path="*" element={<NotFound />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App
