import { createContext, useContext, useState, useEffect, ReactNode } from 'react'; import { api } from '@/lib/api'; import type { UserProfileSchema } from '@/lib/types'; type User = UserProfileSchema; interface AuthContextType { user: User | null; loading: boolean; login: (email: string, password: string) => Promise; logout: () => void; isAuthenticated: boolean; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { checkAuth(); }, []); const checkAuth = async () => { const token = localStorage.getItem('access_token'); if (token) { try { const profile = await api.getProfile(); setUser(profile as User); } catch (error) { localStorage.removeItem('access_token'); localStorage.removeItem('refresh_token'); } } setLoading(false); }; const login = async (email: string, password: string) => { const response = await api.login({ email, password }); localStorage.setItem('access_token', response.access_token); localStorage.setItem('refresh_token', response.refresh_token); await checkAuth(); }; const logout = () => { localStorage.removeItem('access_token'); localStorage.removeItem('refresh_token'); 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; }