import React, { createContext, useContext, useState, useEffect } from 'react'; import { supabase } from '@/integrations/supabase/client'; import type { User, Session } from '@supabase/supabase-js'; interface Profile { id: string; user_id: string; username: string | null; display_name: string | null; avatar_url: string | null; bio: string | null; is_verified: boolean; reputation: number; total_uploads: number; created_at: string; } interface AuthContextType { user: User | null; profile: Profile | null; session: Session | null; loading: boolean; signUp: (email: string, password: string, metadata?: { username?: string; display_name?: string }) => Promise<{ error: any }>; signIn: (email: string, password: string) => Promise<{ error: any }>; signOut: () => Promise; refreshProfile: () => Promise; } const AuthContext = createContext(undefined); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [user, setUser] = useState(null); const [profile, setProfile] = useState(null); const [session, setSession] = useState(null); const [loading, setLoading] = useState(true); const fetchProfile = async (userId: string) => { try { const { data, error } = await supabase .from('profiles') .select('*') .eq('user_id', userId) .single(); if (!error && data) { setProfile(data as unknown as Profile); } } catch (e) { console.error('Error fetching profile:', e); } }; const refreshProfile = async () => { if (user) { await fetchProfile(user.id); } }; useEffect(() => { const { data: { subscription } } = supabase.auth.onAuthStateChange( async (event, session) => { setSession(session); setUser(session?.user ?? null); if (session?.user) { setTimeout(() => fetchProfile(session.user.id), 0); } else { setProfile(null); } setLoading(false); } ); supabase.auth.getSession().then(({ data: { session } }) => { setSession(session); setUser(session?.user ?? null); if (session?.user) { fetchProfile(session.user.id); } setLoading(false); }); return () => subscription.unsubscribe(); }, []); const signUp = async (email: string, password: string, metadata?: { username?: string; display_name?: string }) => { const { error } = await supabase.auth.signUp({ email, password, options: { data: { username: metadata?.username, display_name: metadata?.display_name, }, emailRedirectTo: window.location.origin, }, }); return { error }; }; const signIn = async (email: string, password: string) => { const { error } = await supabase.auth.signInWithPassword({ email, password }); return { error }; }; const signOut = async () => { await supabase.auth.signOut(); setUser(null); setProfile(null); setSession(null); }; return ( {children} ); }; export const useAuth = () => { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; };