import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from "react"; import { auth as authApi, global as globalApi } from "../api/client"; import type { GlobalSettings, User } from "../api/types"; type AuthContextValue = { user: User | null; loading: boolean; settings: GlobalSettings | null; setUser: (u: User | null) => void; refresh: () => Promise; logout: () => Promise; }; const AuthContext = createContext({ user: null, loading: true, settings: null, setUser: () => {}, refresh: async () => {}, logout: async () => {}, }); export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [settings, setSettings] = useState(null); const refresh = useCallback(async () => { try { const me = await authApi.me(); setUser(me); } catch { setUser(null); } }, []); useEffect(() => { (async () => { globalApi.get().then(setSettings).catch(() => {}); await refresh(); setLoading(false); })(); }, [refresh]); const logout = useCallback(async () => { await authApi.logout().catch(() => {}); setUser(null); }, []); return ( {children} ); } export const useAuth = () => useContext(AuthContext);