import React, { createContext, useContext, useEffect, useState } from 'react'; type UserRole = 'COACH' | 'CLIENT'; interface User { id: string; // Changed to string name: string; role: UserRole; coach_id?: string | null; coach?: { id: string; name: string; } | null; } interface AuthContextType { user: User | null; login: (userId: string) => Promise; // Changed to string logout: () => void; isLoading: boolean; } const AuthContext = createContext({ user: null, login: async () => null, logout: () => {}, isLoading: true, }); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { // Check sessionStorage on mount const storedUser = sessionStorage.getItem('straps_user'); if (storedUser) { setUser(JSON.parse(storedUser)); } setIsLoading(false); }, []); const login = async (id: string): Promise => { setIsLoading(true); try { const res = await fetch(`/api/users/${id}`); if (res.ok) { const userData = await res.json(); setUser(userData); sessionStorage.setItem('straps_user', JSON.stringify(userData)); // Store full object in Session return userData; } return null; } catch (error) { console.error("Login failed", error); return null; } finally { setIsLoading(false); } }; const logout = () => { setUser(null); sessionStorage.removeItem('straps_user'); }; return ( {children} ); } export const useAuth = () => useContext(AuthContext);