'use client'; import { createContext, useContext, useEffect, useState } from 'react'; import { User, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut, onAuthStateChanged, GoogleAuthProvider, signInWithPopup, sendPasswordResetEmail, } from 'firebase/auth'; import { auth } from '../lib/firebase'; interface AuthContextType { user: User | null; loading: boolean; signIn: (email: string, password: string) => Promise; signUp: (email: string, password: string) => Promise; signInWithGoogle: () => Promise; logout: () => Promise; resetPassword: (email: string) => Promise; } const AuthContext = createContext({} as AuthContextType); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { setUser(user); setLoading(false); }); return () => unsubscribe(); }, []); const signIn = async (email: string, password: string) => { try { await signInWithEmailAndPassword(auth, email, password); } catch (error) { throw error; } }; const signUp = async (email: string, password: string) => { try { await createUserWithEmailAndPassword(auth, email, password); } catch (error) { throw error; } }; const signInWithGoogle = async () => { try { const provider = new GoogleAuthProvider(); await signInWithPopup(auth, provider); } catch (error) { throw error; } }; const logout = async () => { try { await signOut(auth); } catch (error) { throw error; } }; const resetPassword = async (email: string) => { try { await sendPasswordResetEmail(auth, email); } catch (error) { throw error; } }; const value = { user, loading, signIn, signUp, signInWithGoogle, logout, resetPassword, }; return ( {!loading && children} ); } export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };