import React, { createContext, useContext, useState, useEffect } from 'react';
interface User {
id: string;
email: string;
name: string;
type: 'mentor' | 'mentee';
profileComplete: boolean;
}
interface AuthContextType {
user: User | null;
login: (email: string, password: string, type: 'mentor' | 'mentee') => Promise<void>;
register: (email: string, password: string, name: string, type: 'mentor' | 'mentee') => Promise<void>;
logout: () => void;
loading: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Check for stored user session
const storedUser = localStorage.getItem('user');
if (storedUser) {
setUser(JSON.parse(storedUser));
}
setLoading(false);
}, []);
const login = async (email: string, password: string, type: 'mentor' | 'mentee') => {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000));
const mockUser: User = {
id: Math.random().toString(36).substr(2, 9),
email,
name: email.split('@')[0],
type,
profileComplete: false
};
setUser(mockUser);
localStorage.setItem('user', JSON.stringify(mockUser));
};
const register = async (email: string, password: string, name: string, type: 'mentor' | 'mentee') => {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000));
const mockUser: User = {
id: Math.random().toString(36).substr(2, 9),
email,
name,
type,
profileComplete: false
};
setUser(mockUser);
localStorage.setItem('user', JSON.stringify(mockUser));
};
const logout = () => {
setUser(null);
localStorage.removeItem('user');
};
const value = {
user,
login,
register,
logout,
loading
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};