// ProtectedRoute.jsx
import React, { useState, useEffect } from 'react';  // Add React and useState
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import { useToast } from '@/hooks/use-toast';
const ProtectedRoute = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const location = useLocation();
  const { toast } = useToast();
  const navigate = useNavigate();

  useEffect(() => {
    let mounted = true;
    
    const checkAuth = async () => {
      try {
        const response = await fetch('/auth/check', {
          credentials: 'include',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        });
        
        if (!mounted) {
          return;
        }

        if (response.status === 401) {
          setIsAuthenticated(false);
          navigate('/login', { state: { from: location } });
          return;
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        
        if (mounted) {
          setIsAuthenticated(data.authenticated);
          
          if (!data.authenticated) {
            navigate('/login', { state: { from: location } });
          }
        }
      } catch (error) {
        if (mounted) {
          setIsAuthenticated(false);
          toast({
            title: "Error",
            description: "Authentication failed. Please try in again.",
            variant: "destructive",
          });
          navigate('/login', { state: { from: location } });
        }
      } finally {
        if (mounted) {
          setIsLoading(false);
        }
      }
    };

    checkAuth();
    return () => {
      mounted = false;
    };
  }, [location.pathname, toast, navigate]);

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-white"></div>
      </div>
    );
  }

  return isAuthenticated ? children : null;
};

// Make sure to add this default export
export default ProtectedRoute;