'use client'

import { createContext, useContext, useEffect, useState } from 'react';

export const AuthContext = createContext();

export function AuthProvider({ children }) {
    const [user, setUser] = useState(null);

    useEffect(() => {
        async function fetchUser() {
            try {
                const response = await fetch('/api/auth/user', { method: 'GET' });
                if (response.ok) {
                    const data = await response.json();
                    setUser(data);
                } else {
                    setUser({ isLoggedIn: false });
                }
            } catch (error) {
                console.error(error);
                setUser({ isLoggedIn: false });
            }
        }
        fetchUser();
    }, []);

    return (
        <AuthContext.Provider value={{ user }}>
            {children}
        </AuthContext.Provider>
    );
}

export function useAuth() {
    return useContext(AuthContext);
}