'use client'; import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { useRouter } from 'next/navigation'; import { authService, AuthUser, getErrorMessage } from '@/services'; interface AuthContextType { user: AuthUser | null; isLoading: boolean; isAuthenticated: boolean; login: (email: string, password: string) => Promise; logout: () => Promise; error: string | null; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const router = useRouter(); const checkAuth = useCallback(() => { try { const storedUser = authService.getStoredUser(); if (storedUser && storedUser.role === 'ADMIN') { setUser(storedUser); } else if (storedUser) { // Not admin, clear storage authService.clearAuth(); } } catch { // Invalid stored data authService.clearAuth(); } finally { setIsLoading(false); } }, []); useEffect(() => { checkAuth(); }, [checkAuth]); const login = async (email: string, password: string) => { setError(null); try { const response = await authService.login({ email, password }); setUser(response.user); router.push('/dashboard'); } catch (err) { const errorMessage = getErrorMessage(err); setError(errorMessage); throw new Error(errorMessage); } }; const logout = async () => { try { await authService.logout(); } finally { setUser(null); router.push('/login'); } }; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; }