import React, { createContext, useContext, useState, useEffect } from 'react'; import { User, UserRole } from '../types'; import { authApi, clearSession, getSession, saveSession } from '../services/api'; interface AuthContextType { user: User | null; login: (email: string, password: string) => Promise; register: (name: string, email: string, password: string) => Promise; logout: () => void; isLoading: boolean; } const AuthContext = createContext(undefined); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const restoreSession = async () => { const session = getSession(); if (!session) { setIsLoading(false); return; } try { const { user: apiUser } = await authApi.me(); const restoredUser = toFrontendUser(apiUser); saveSession({ ...session, user: apiUser }); setUser(restoredUser); } catch { clearSession(); } finally { setIsLoading(false); } }; void restoreSession(); }, []); const login = async (email: string, password: string): Promise => { try { const session = await authApi.login(email, password); const signedInUser = toFrontendUser(session.user); saveSession(session); setUser(signedInUser); return signedInUser; } catch { return null; } }; const register = async (name: string, email: string, password: string): Promise => { try { const session = await authApi.register(name, email, password); const signedInUser = toFrontendUser(session.user); saveSession(session); setUser(signedInUser); return signedInUser; } catch { return null; } }; const logout = () => { setUser(null); clearSession(); }; return ( {children} ); }; const toFrontendUser = (user: { email: string; name: string; role: string }): User => ({ email: user.email, name: user.name, role: user.role === 'student' ? 'student' : 'professor', }); export const useAuth = () => { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };