import { useContext, useEffect } from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import GlobalStateContext from "./Contexts/GlobalStateContext";
import DefaultLayout from "./Layouts/DefaultLayout";
import Login from "./Pages/Login";
import { RouteLink } from "./Routes/Routes";
import ForgotPassword from "./Pages/ForgotPassword";
import VerifyEnterOTP from "./Pages/VerifyEnterOTP";
import SetNewPassword from "./Pages/SetNewPassword";

function App() {
  const context = useContext(GlobalStateContext);
  if (!context) throw new Error("App must be used within a GlobalStateProvider");

  const { isAuthenticate, setIsAuthenticate } = context;

  useEffect(() => {
    const token = localStorage.getItem("token");
    setIsAuthenticate(!!token); // Converts token to boolean
  }, [setIsAuthenticate]);

  console.log("Auth Status:", isAuthenticate);

  return (
    <Router>
      <Routes>
        {/* Redirect logged-in users away from login */}
        <Route path="/login" element={isAuthenticate && localStorage.getItem("token") ? <Navigate to="/" /> : <Login />} />
        <Route path="/forgot-password" element={<ForgotPassword />} />
        <Route path="/forgot-password/verify-otp" element={<VerifyEnterOTP />} />
        <Route path="/forgot-password/reset-password" element={<SetNewPassword />} />

        {/* Protected Routes */}
        <Route
          path="/*"
          element={isAuthenticate && localStorage.getItem("token") ? (
            <DefaultLayout>
              <Routes>
                {RouteLink.map(({ path, Component }, index) => (
                  <Route key={index} path={path} element={<Component />} />
                ))}
              </Routes>
            </DefaultLayout>
          ) : (
            <Routes>
              {/* Allow only forgot password flows */}
              <Route path="/forgot-password" element={<ForgotPassword />} />
              <Route path="/forgot-password/verify" element={<VerifyEnterOTP />} />  {/* ✅ Add this line */}
              <Route path="/forgot-password/verify-otp" element={<VerifyEnterOTP />} />
              <Route path="/forgot-password/reset-password" element={<SetNewPassword />} />

              {/* Default to login */}
              <Route path="*" element={<Navigate to="/login" />} />
            </Routes>
          )}
        />

        {/* Catch-all route to prevent unauthorized access */}
        <Route path="*" element={<Navigate to="/login" />} />
      </Routes>
    </Router>
  );
}

export default App;
