'use client';
import { useEffect, useState } from 'react';
import { User } from 'firebase/auth';
import { onAuthStateChange, signInWithGoogle, signOutUser } from '../lib/firebase';
interface UseAuthReturn {
user: User | null;
loading: boolean;
signIn: () => Promise<User | null>;
signOut: () => Promise<void>;
isAuthenticated: boolean;
authError: string | null;
}
export const useAuth = (): UseAuthReturn => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [authError, setAuthError] = useState<string | null>(null);
useEffect(() => {
console.log('🔧 Setting up auth state listener...');
let unsubscribe: (() => void) | null = null;
try {
unsubscribe = onAuthStateChange((user: User | null) => {
setUser(user);
setLoading(false);
setAuthError(null);
});
} catch (error) {
const e = error as Error;
console.error('❌ Firebase auth initialization failed:', e.message);
setAuthError(e.message);
setLoading(false);
setUser(null);
}
return () => {
console.log('🧹 Cleaning up auth state listener...');
try {
if (unsubscribe) {
unsubscribe();
}
} catch (error) {
console.error('❌ Error cleaning up auth listener:', (error as Error).message);
}
};
}, []);
const signIn = async (): Promise<User | null> => {
try {
setLoading(true);
setAuthError(null);
const user = await signInWithGoogle();
return user;
} catch (error) {
const e = error as Error;
console.error('❌ Sign in failed:', e);
setAuthError(e.message || 'Sign in failed');
return null;
} finally {
setLoading(false);
}
};
const signOut = async (): Promise<void> => {
try {
setLoading(true);
setAuthError(null);
await signOutUser();
} catch (error) {
const e = error as Error;
console.error('❌ Sign out failed:', e);
setAuthError(e.message || 'Sign out failed');
} finally {
setLoading(false);
}
};
return {
user,
loading,
signIn,
signOut,
isAuthenticated: !!user,
authError,
};
};