import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { api, type User } from '../api'; interface AuthValue { user: User | null; loading: boolean; login: (email: string, password: string) => Promise; signup: (email: string, password: string) => Promise; logout: () => Promise; } const Ctx = createContext(null); export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { api .me() .then(setUser) .catch(() => setUser(null)) .finally(() => setLoading(false)); }, []); const value: AuthValue = { user, loading, login: async (email, password) => setUser(await api.login(email, password)), signup: async (email, password) => setUser(await api.signup(email, password)), logout: async () => { await api.logout(); setUser(null); }, }; return {children}; } export function useAuth() { const ctx = useContext(Ctx); if (!ctx) throw new Error('useAuth must be used within AuthProvider'); return ctx; }