"use client"; import { createContext, useCallback, useContext, useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import { api, login as apiLogin, setToken, getToken } from "./api"; type Me = { id: number; email: string; full_name: string | null; role: "admin" | "support" | "readonly"; is_active: boolean; }; type AuthCtx = { user: Me | null; loading: boolean; login: (email: string, password: string) => Promise; logout: () => void; }; const Ctx = createContext({ user: null, loading: true, login: async () => {}, logout: () => {}, }); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const router = useRouter(); const loadMe = useCallback(async () => { if (!getToken()) { setUser(null); setLoading(false); return; } try { const me = await api("/api/auth/me"); setUser(me); } catch { setUser(null); } finally { setLoading(false); } }, []); useEffect(() => { loadMe(); }, [loadMe]); const login = async (email: string, password: string) => { const res = await apiLogin(email, password); setToken(res.access_token); await loadMe(); router.push("/"); }; const logout = () => { setToken(null); setUser(null); router.push("/login"); }; return {children}; } export const useAuth = () => useContext(Ctx); export function roleAtLeast(role: string | undefined, min: "readonly" | "support" | "admin") { const rank: Record = { readonly: 0, support: 1, admin: 2 }; return (rank[role || "readonly"] ?? 0) >= rank[min]; }