import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' import * as authApi from '../api/auth' import { ApiError } from '../api/client' import type { User } from '../types' interface AuthContextValue { user: User | null loading: boolean login: (usernameOrEmail: string, password: string) => Promise logout: () => Promise } const AuthContext = createContext(undefined) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { authApi .me() .then(setUser) .catch((err) => { if (!(err instanceof ApiError && err.status === 401)) { console.error('Failed to load current user', err) } }) .finally(() => setLoading(false)) }, []) async function login(usernameOrEmail: string, password: string) { setUser(await authApi.login(usernameOrEmail, password)) } async function logout() { await authApi.logout() setUser(null) } return ( {children} ) } export function useAuth(): AuthContextValue { const ctx = useContext(AuthContext) if (!ctx) throw new Error('useAuth must be used within an AuthProvider') return ctx }