import { useEffect } from 'react'; import { useNavigate } from 'react-router'; import { useAuthStore } from '../stores/authStore'; import { api } from '../services/api'; export function useAuth() { const { user, isAuthenticated, isLoading, setUser, setLoading, logout: storeLogout } = useAuthStore(); useEffect(() => { checkAuth(); }, []); async function checkAuth() { try { setLoading(true); const data = await api.get<{ user: any }>('/auth/me'); setUser(data.user); } catch { setUser(null); } } async function logout() { try { await api.post('/auth/logout'); } catch { // Ignore logout API errors } storeLogout(); } async function refreshToken() { try { await api.post('/auth/refresh'); await checkAuth(); } catch { storeLogout(); } } return { user, isAuthenticated, isLoading, checkAuth, logout, refreshToken }; } export function useRequireAuth() { const navigate = useNavigate(); const { isAuthenticated, isLoading } = useAuthStore(); useEffect(() => { if (!isLoading && !isAuthenticated) { navigate('/login'); } }, [isAuthenticated, isLoading, navigate]); return { isAuthenticated, isLoading }; }