'use client'; import { useEffect, useCallback, useRef, useState } from 'react'; import Script from 'next/script'; import { createClient } from '@/lib/supabase/client'; // Add type declarations for Google One Tap declare global { interface Window { handleGoogleSignIn?: (response: GoogleSignInResponse) => void; google: { accounts: { id: { initialize: (config: GoogleInitializeConfig) => void; renderButton: (element: HTMLElement, options: GoogleButtonOptions) => void; prompt: (callback?: (notification: GoogleNotification) => void) => void; cancel: () => void; }; }; }; } } // Define types for Google Sign-In interface GoogleSignInResponse { credential: string; clientId?: string; select_by?: string; } interface GoogleInitializeConfig { client_id: string | undefined; callback: ((response: GoogleSignInResponse) => void) | undefined; nonce?: string; use_fedcm?: boolean; context?: string; itp_support?: boolean; } interface GoogleButtonOptions { type?: string; theme?: string; size?: string; text?: string; shape?: string; logoAlignment?: string; width?: number; } interface GoogleNotification { isNotDisplayed: () => boolean; getNotDisplayedReason: () => string; isSkippedMoment: () => boolean; getSkippedReason: () => string; isDismissedMoment: () => boolean; getDismissedReason: () => string; } interface GoogleSignInProps { returnUrl?: string; } export default function GoogleSignIn({ returnUrl }: GoogleSignInProps) { const googleClientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID; const [isLoading, setIsLoading] = useState(false); const handleGoogleSignIn = useCallback(async (response: GoogleSignInResponse) => { try { setIsLoading(true); const supabase = createClient(); const { error } = await supabase.auth.signInWithIdToken({ provider: 'google', token: response.credential, }); if (error) throw error; // Add a small delay before redirecting to ensure localStorage is properly saved setTimeout(() => { window.location.href = returnUrl || "/dashboard"; }, 100); } catch (error) { console.error('Error signing in with Google:', error); setIsLoading(false); } }, [returnUrl]); useEffect(() => { // Assign the callback to window object so it can be called from the Google button window.handleGoogleSignIn = handleGoogleSignIn; if (window.google && googleClientId) { window.google.accounts.id.initialize({ client_id: googleClientId, callback: handleGoogleSignIn, use_fedcm: true, context: 'signin', itp_support: true }); } return () => { // Cleanup delete window.handleGoogleSignIn; if (window.google) { window.google.accounts.id.cancel(); } }; }, [googleClientId, handleGoogleSignIn]); if (!googleClientId) { return ( ); } return ( <> {/* Google One Tap container */}
{/* Google Sign-In button container styled to match site design */}