// src/contexts/AuthContext.tsx import React, { createContext, useContext, useEffect, useState, useCallback } from 'react'; import { authService, UserProfile } from '../api/auth/authService'; import { tokenManager } from '../api/auth/tokenManager'; interface AuthContextType { user: UserProfile | null; isAuthenticated: boolean; isLoading: boolean; login: (email: string, password: string) => Promise; register: (data: any) => Promise; logout: () => Promise; updateProfile: (updates: Partial) => Promise; refreshUser: () => Promise; } const AuthContext = createContext(null); export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }; export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); // Initialize auth state useEffect(() => { const initAuth = async () => { try { await tokenManager.initialize(); if (authService.isAuthenticated()) { const profile = await authService.getCurrentUser(); setUser(profile); } } catch (error) { console.error('Auth initialization failed:', error); } finally { setIsLoading(false); } }; initAuth(); }, []); const login = useCallback(async (email: string, password: string) => { const profile = await authService.login({ email, password }); setUser(profile); }, []); const register = useCallback(async (data: any) => { const profile = await authService.register(data); setUser(profile); }, []); const logout = useCallback(async () => { await authService.logout(); setUser(null); }, []); const updateProfile = useCallback(async (updates: Partial) => { const updated = await authService.updateProfile(updates); setUser(updated); }, [updateProfile]); const refreshUser = useCallback(async () => { if (authService.isAuthenticated()) { const profile = await authService.getCurrentUser(); setUser(profile); } }, []); // Set up token refresh interval useEffect(() => { if (!user) return; // Check token expiry every minute const interval = setInterval(async () => { try { await tokenManager.getAccessToken(); // This will refresh if needed } catch (error) { console.error('Token refresh failed:', error); await logout(); } }, 60000); // 1 minute return () => clearInterval(interval); }, [user, logout]); return ( {children} ); };