import { createContext, useContext, useState, useCallback, useEffect } from "react";
import { apiRequest } from "../api/client";

const AuthContext = createContext();

export function AuthProvider({ children }) {
    const [token, setToken] = useState(() => localStorage.getItem("token"));
    const [user, setUser] = useState(null);

    // Fetch user on mount if token exists
    useEffect(() => {
        if (token && !user) {
            apiRequest("/auth/me").then((data) => {
                if (data && !data.detail) setUser(data);
            }).catch(() => {});
        }
    }, [token]); // eslint-disable-line react-hooks/exhaustive-deps

    const login = useCallback((accessToken, userData = null) => {
        localStorage.setItem("token", accessToken);
        setToken(accessToken);
        if (userData) setUser(userData);
    }, []);

    const logout = useCallback(() => {
        localStorage.removeItem("token");
        setToken(null);
        setUser(null);
    }, []);

    const value = {
        token,
        user,
        setUser,
        isAuthenticated: Boolean(token),
        login,
        logout,
    };

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

export const useAuth = () => useContext(AuthContext);
