import { createContext, useContext, useState, useEffect, ReactNode } from 'react'; import { authApi, getAccessToken } from '../api/client'; import type { User } from '../types'; interface AuthContextType { user: User | null; isLoading: boolean; isAuthenticated: boolean; isAdmin: boolean; login: (email: string, password: string) => Promise; register: (email: string, password: string) => Promise; logout: () => void; refreshUser: () => Promise; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); const refreshUser = async () => { try { const userData = await authApi.getMe(); setUser(userData); } catch { setUser(null); } }; useEffect(() => { const initAuth = async () => { if (getAccessToken()) { await refreshUser(); } setIsLoading(false); }; initAuth(); }, []); const login = async (email: string, password: string) => { await authApi.login(email, password); await refreshUser(); }; const register = async (email: string, password: string) => { await authApi.register(email, password); await authApi.login(email, password); await refreshUser(); }; const logout = () => { authApi.logout(); setUser(null); }; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }