File size: 6,975 Bytes
5da4770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
'use client';

import { useEffect, useCallback, useState } from 'react';
import Script from 'next/script';
import { createClient } from '@/lib/supabase/client';
import { useAuthMethodTracking } from '@/lib/stores/auth-tracking';
import { FcGoogle } from "react-icons/fc";
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';

declare global {
  interface Window {
    handleGoogleSignIn?: (response: GoogleSignInResponse) => void;
    google: {
      accounts: {
        id: {
          initialize: (config: GoogleInitializeConfig) => void;
          prompt: (
            callback?: (notification: GoogleNotification) => void,
          ) => void;
          cancel: () => void;
        };
      };
    };
  }
}

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 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 [isGoogleLoaded, setIsGoogleLoaded] = useState(false);

  const { wasLastMethod, markAsUsed } = useAuthMethodTracking('google');

  const handleGoogleSignIn = useCallback(
    async (response: GoogleSignInResponse) => {
      try {
        setIsLoading(true);
        const supabase = createClient();

        console.log('Starting Google sign in process');
        markAsUsed();

        const { error } = await supabase.auth.signInWithIdToken({
          provider: 'google',
          token: response.credential,
        });

        if (error) throw error;

        console.log(
          'Google sign in successful, preparing redirect to:',
          returnUrl || '/dashboard',
        );

        setTimeout(() => {
          console.log('Executing redirect now to:', returnUrl || '/dashboard');
          window.location.href = returnUrl || '/dashboard';
        }, 500);
      } catch (error) {
        console.error('Error signing in with Google:', error);
        setIsLoading(false);
        toast.error('Google sign-in failed. Please try again.');
      }
    },
    [returnUrl, markAsUsed],
  );

  const handleCustomGoogleSignIn = useCallback(() => {
    if (isLoading) return;

    if (!window.google || !googleClientId || !isGoogleLoaded) {
      console.error('Google sign-in not properly initialized');
      toast.error('Google sign-in not ready. Please try again.');
      return;
    }

    try {
      setIsLoading(true);
      
      const timeoutId = setTimeout(() => {
        console.log('Google sign-in timeout - resetting loading state');
        setIsLoading(false);
        toast.error('Google sign-in popup failed to load. Please try again.');
      }, 5000);

      window.google.accounts.id.prompt((notification) => {
        clearTimeout(timeoutId);
        
        if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
          console.log('Google sign-in was not displayed or skipped:', 
            notification.isNotDisplayed() ? notification.getNotDisplayedReason() : notification.getSkippedReason()
          );
          setIsLoading(false);
        } else if (notification.isDismissedMoment()) {
          console.log('Google sign-in was dismissed:', notification.getDismissedReason());
          setIsLoading(false);
        }
      });
    } catch (error) {
      console.error('Error showing Google sign-in prompt:', error);
      setIsLoading(false);
      toast.error('Failed to start Google sign-in. Please try again.');
    }
  }, [googleClientId, isGoogleLoaded, isLoading]);

  useEffect(() => {
    window.handleGoogleSignIn = handleGoogleSignIn;

    if (window.google && googleClientId && !isGoogleLoaded) {
      window.google.accounts.id.initialize({
        client_id: googleClientId,
        callback: handleGoogleSignIn,
        use_fedcm: true,
        context: 'signin',
        itp_support: true,
      });
      setIsGoogleLoaded(true);
    }

    return () => {
      delete window.handleGoogleSignIn;
    };
  }, [googleClientId, handleGoogleSignIn, isGoogleLoaded]);

  if (!googleClientId) {
    return (
      <button
        disabled
        className="w-full h-12 flex items-center justify-center gap-2 text-sm font-medium tracking-wide rounded-full bg-background border border-border opacity-60 cursor-not-allowed"
      >
        <FcGoogle className="w-4 h-4 mr-2" />
        Google Sign-In Not Configured
      </button>
    );
  }

  return (
    <>
      <div
        id="g_id_onload"
        data-client_id={googleClientId}
        data-context="signin"
        data-ux_mode="popup"
        data-auto_prompt="false"
        data-itp_support="true"
        data-callback="handleGoogleSignIn"
        style={{ display: 'none' }}
      />
      <div className="relative">
        <button
          onClick={handleCustomGoogleSignIn}
          disabled={isLoading || !isGoogleLoaded}
          className="w-full h-12 flex items-center justify-center text-sm font-medium tracking-wide rounded-full bg-background text-foreground border border-border hover:bg-accent/30 transition-all duration-200 disabled:opacity-60 disabled:cursor-not-allowed font-sans"
          aria-label={
            isLoading ? 'Signing in with Google...' : 'Sign in with Google'
          }
          type="button"
        >
          {isLoading ? (
            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
          ) : (
            <FcGoogle className="w-4 h-4 mr-2" />
          )}
          <span className="font-medium">
            {isLoading ? 'Signing in...' : 'Continue with Google'}
          </span>
        </button>
        
        {wasLastMethod && (
          <div className="absolute -top-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-background shadow-sm">
            <div className="w-full h-full bg-green-500 rounded-full animate-pulse" />
          </div>
        )}
      </div>

      <Script
        src="https://accounts.google.com/gsi/client"
        strategy="afterInteractive"
        onLoad={() => {
          if (window.google && googleClientId && !isGoogleLoaded) {
            window.google.accounts.id.initialize({
              client_id: googleClientId,
              callback: handleGoogleSignIn,
              use_fedcm: true,
              context: 'signin',
              itp_support: true,
            });
            setIsGoogleLoaded(true);
          }
        }}
      />
    </>
  );
}