import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import axios from "axios";

const PrivateRoute = ({ element: Element, ...rest }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(null); // Track authentication status

  useEffect(() => {
    // Call the server to validate the token
    const checkAuth = async () => {
      try {
        const response = await axios.get("http://localhost:8080/api/auth-check", {
          withCredentials: true, // Include cookies in the request
        });

        if (response.status === 200) {
          setIsAuthenticated(true); // User is authenticated
        }
      } catch (error) {
        setIsAuthenticated(false); // User is not authenticated
      }
    };

    checkAuth();
  }, []);

  // If still checking authentication, render nothing or a loading spinner
  if (isAuthenticated === null) {
    return <div>Loading...</div>;
  }

  // If authenticated, render the component. Otherwise, redirect to the login page
  return isAuthenticated ? Element : <Navigate to="/" />;
};

export default PrivateRoute;
