import { createContext, useContext, useState, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import { Sonner, toast } from 'sonner'; import * as authApi from '@/lib/api/auth'; // Create auth context const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const router = useRouter(); // Check if user is logged in on initial load useEffect(() => { const checkAuth = async () => { try { const currentUser = authApi.getCurrentUser(); if (currentUser) { setUser(currentUser); } } catch (error) { console.error('Authentication check failed:', error); } finally { setLoading(false); } }; checkAuth(); }, []); // Login user const login = async (credentials) => { try { setLoading(true); const data = await authApi.login(credentials); setUser(data.user); toast.success('Login successful!'); // Redirect based on role if (data.user.role === 'admin') { router.push('/admin'); } else if (data.user.role === 'staff') { router.push('/staff'); } else { router.push('/'); } return data; } catch (error) { toast.error(error.message || 'Login failed'); throw error; } finally { setLoading(false); } }; // Register user const register = async (userData) => { try { setLoading(true); const data = await authApi.register(userData); setUser(data.user); toast.success('Registration successful!'); router.push('/'); return data; } catch (error) { toast.error(error.message || 'Registration failed'); throw error; } finally { setLoading(false); } }; // Logout user const logout = () => { authApi.logout(); setUser(null); router.push('/login'); toast.success('Logged out successfully'); }; // Get user profile const getProfile = async () => { try { setLoading(true); const data = await authApi.getProfile(); setUser(data.user); return data.user; } catch (error) { console.error('Failed to get user profile:', error); throw error; } finally { setLoading(false); } }; return ( {children} ); }; // Custom hook to use auth context export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };