import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'; import { AuthService, type UserSession } from '../services/auth.service'; import { ChatService } from '../services/chat.service'; interface AuthContextType { user: UserSession | null; loading: boolean; unreadCount: number; login: (user: UserSession) => void; logout: () => void; refreshSession: () => Promise; fetchUnreadCount: () => Promise; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [unreadCount, setUnreadCount] = useState(0); const fetchUnreadCount = async () => { const currentUser = AuthService.getCurrentUser(); if (currentUser) { try { const count = await ChatService.getUnreadCount(currentUser.id); setUnreadCount(count); } catch { setUnreadCount(0); } } }; // Verificar sesión al cargar la app (Solo una vez) useEffect(() => { const initAuth = async () => { try { const sessionUser = await AuthService.checkSession(); if (sessionUser) { setUser(sessionUser); await fetchUnreadCount(); // <--- 5. LLAMAR AL CARGAR LA APP } else { setUser(null); setUnreadCount(0); } } catch (error) { setUser(null); setUnreadCount(0); } finally { setLoading(false); } }; initAuth(); }, []); const login = (userData: UserSession) => { setUser(userData); localStorage.setItem('userProfile', JSON.stringify(userData)); fetchUnreadCount(); }; const logout = () => { AuthService.logout(); setUser(null); setUnreadCount(0); localStorage.removeItem('userProfile'); }; const refreshSession = async () => { const sessionUser = await AuthService.checkSession(); setUser(sessionUser); if (sessionUser) { await fetchUnreadCount(); } }; return ( {children} ); } // Hook personalizado para usar el contexto fácilmente export function useAuth() { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }