import { useState, useEffect } from 'react';

const PUBLIC_USER_API_URL = import.meta.env.PUBLIC_USER_API_URL;
export const useIsLoggedIn = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(null); // null means "unknown"
    const [sessionData, setSessionData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const checkLoginStatus = async () => {
            try {
                const response = await fetch(`${PUBLIC_USER_API_URL}?query=isLoggedIn`, {
                    credentials: 'include'
                });
                const data = await response.json();
                setIsLoggedIn(!!data?.isLoggedIn);
                setSessionData(data?.session_data || null);
                setLoading(false);
            } catch (err) {
                setError(err);
                setIsLoggedIn(false);
                setSessionData(null);
                setLoading(false);
            }
        };

        checkLoginStatus();
    }, []);

    return { isLoggedIn, sessionData, loading, error };
};

const IsLoggedIn = ({ children, fallback = null }) => {
    const { isLoggedIn, loading, error } = useIsLoggedIn();

    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error checking login status</div>;
    
    return isLoggedIn ? children : fallback;
};

export default IsLoggedIn;