import { useState, useEffect, useCallback } from 'react'; import { api, ApiError } from '@/lib/api'; interface AuthState { isAuthenticated: boolean; username: string | null; isLoading: boolean; } export function useAuth() { const [state, setState] = useState({ isAuthenticated: false, username: null, isLoading: true, }); const checkSession = useCallback(async () => { try { const data = await api.me(); setState({ isAuthenticated: true, username: data.username, isLoading: false }); } catch { setState({ isAuthenticated: false, username: null, isLoading: false }); } }, []); useEffect(() => { checkSession(); }, [checkSession]); const login = async (username: string, password: string) => { try { await api.login(username, password); setState({ isAuthenticated: true, username, isLoading: false }); return true; } catch (err) { if (err instanceof ApiError) throw err; throw new Error('Login failed'); } }; const logout = async () => { await api.logout(); setState({ isAuthenticated: false, username: null, isLoading: false }); }; return { ...state, login, logout, checkSession }; }