// Auth context: who is seated at the table. Wraps the /auth REST endpoints // and exposes { user, checking, login, register, logout } to the app. import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import type { ReactNode } from 'react' import * as api from '../api' import type { User } from '../api' export type AuthApi = { user: User | null checking: boolean login: (username: string, password: string) => Promise register: (username: string, password: string) => Promise logout: () => Promise } const AuthContext = createContext(null) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) const [checking, setChecking] = useState(true) useEffect(() => { api .me() .then(setUser) .catch(() => setUser(null)) .finally(() => setChecking(false)) }, []) const login = useCallback(async (username: string, password: string) => { const u = await api.login(username, password) setUser(u) return u }, []) const register = useCallback( async (username: string, password: string) => { await api.register(username, password) return login(username, password) }, [login], ) const logout = useCallback(async () => { await api.logout() setUser(null) }, []) const value = useMemo( () => ({ user, checking, login, register, logout }), [user, checking, login, register, logout], ) return {children} } export function useAuth(): AuthApi { const ctx = useContext(AuthContext) if (!ctx) throw new Error('useAuth must be used inside ') return ctx }