import React, { createContext, useContext, useEffect, useState } from 'react' import { auth } from '@/lib/appwrite' import type { Models } from 'appwrite' interface AuthContextType { user: Models.User | null loading: boolean login: (email: string, password: string) => Promise register: (email: string, password: string, name?: string) => Promise logout: () => Promise refreshUser: () => Promise } const AuthContext = createContext(undefined) export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState | null>(null) const [loading, setLoading] = useState(true) const refreshUser = async () => { try { const currentUser = await auth.getCurrentUser() setUser(currentUser) } catch { setUser(null) } } useEffect(() => { const init = async () => { await refreshUser() setLoading(false) } init() }, []) const login = async (email: string, password: string) => { await auth.login(email, password) await refreshUser() } const register = async (email: string, password: string, name?: string) => { await auth.register(email, password, name) await refreshUser() } const logout = async () => { await auth.logout() setUser(null) } return ( {children} ) } export function useAuth() { const context = useContext(AuthContext) if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider') } return context }