import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react"; import { api, type Me } from "./api"; interface AuthState { me: Me | null; loading: boolean; refresh: () => Promise; setMe: (me: Me | null) => void; logout: () => Promise; can: (perm: string) => boolean; } const AuthContext = createContext(null); export function AuthProvider({ children }: { children: ReactNode }) { const [me, setMe] = useState(null); const [loading, setLoading] = useState(true); const refresh = useCallback(async () => { try { setMe(await api.get("/api/auth/me")); } catch { setMe(null); } finally { setLoading(false); } }, []); useEffect(() => { void refresh(); const onUnauthorized = () => setMe(null); window.addEventListener("pg-unauthorized", onUnauthorized); return () => window.removeEventListener("pg-unauthorized", onUnauthorized); }, [refresh]); const logout = async () => { await api.post("/api/auth/logout"); setMe(null); }; const can = (perm: string) => !!me?.permissions.includes(perm); return ( {children} ); } export function useAuth() { const ctx = useContext(AuthContext); if (!ctx) throw new Error("AuthProvider missing"); return ctx; }