// src/auth/ProtectedRoute.js
import React, { useContext } from "react";
import { Navigate } from "react-router-dom";
import { CircularProgress, Box } from "@mui/material";
import { AuthContext } from "./AuthContext";

const ProtectedRoute = ({ children }) => {
  const { auth, loading } = useContext(AuthContext);

  // 1. Show a loading spinner while the auth state is being determined
  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', width: '100vw' }}>
        <CircularProgress />
      </Box>
    );
  }

  // 2. Once loading is false, check if the user is authenticated
  if (!auth) {
    // Redirect to the login page if not authenticated
    return <Navigate to="/login" replace />;
  }

  // 3. If authenticated, render the child components (the protected page)
  return children;
};

export default ProtectedRoute;