import React, { createContext, useContext, useState, useEffect } from 'react'; const AuthContext = createContext(null); const DEMO_USER = { id: 'demo123', email: 'demo@container.mom', name: 'Demo User', isDemo: true }; export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { // Check if user is logged in on mount checkAuth(); }, []); const checkAuth = async () => { try { const response = await fetch('/api/auth/me'); if (response.ok) { const userData = await response.json(); setUser(userData); } } catch (error) { console.error('Auth check failed:', error); } finally { setLoading(false); } }; const login = async (email, password) => { // Special case for demo user if (email === DEMO_USER.email && password === 'demo') { setUser(DEMO_USER); return DEMO_USER; } // Regular login logic const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); if (!response.ok) { throw new Error('Login failed'); } const userData = await response.json(); setUser(userData); return userData; }; const signup = async (email, password, name) => { const response = await fetch('/api/auth/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password, name }) }); if (!response.ok) { throw new Error('Signup failed'); } const userData = await response.json(); setUser(userData); return userData; }; const logout = async () => { await fetch('/api/auth/logout', { method: 'POST' }); setUser(null); }; const updateProfile = async (updates) => { const response = await fetch('/api/auth/profile', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updates) }); if (!response.ok) { throw new Error('Profile update failed'); } const updatedUser = await response.json(); setUser(updatedUser); return updatedUser; }; return ( {children} ); }; export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };