import { useEffect, useRef, useCallback, useState } from 'react'; import { useTranslation } from 'react-i18next'; interface LoginPageProps { onGoogleLogin: (credential: string) => Promise; onDevLogin: () => void; } const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID; const IS_DEV = import.meta.env.DEV; function useGoogleIdentity(onCredential: (credential: string) => void) { const btnRef = useRef(null); const callbackRef = useRef(onCredential); callbackRef.current = onCredential; useEffect(() => { if (!GOOGLE_CLIENT_ID) return; const scriptId = 'google-gsi-script'; let script = document.getElementById(scriptId) as HTMLScriptElement | null; const initGoogle = () => { const google = (window as unknown as Record).google as { accounts: { id: { initialize: (config: { client_id: string; callback: (response: { credential: string }) => void; }) => void; renderButton: ( el: HTMLElement, config: { theme: string; size: string; width: number; text: string; }, ) => void; }; }; } | undefined; if (!google?.accounts?.id || !btnRef.current) return; google.accounts.id.initialize({ client_id: GOOGLE_CLIENT_ID, callback: (response: { credential: string }) => { callbackRef.current(response.credential); }, }); google.accounts.id.renderButton(btnRef.current, { theme: 'outline', size: 'large', width: 300, text: 'signin_with', }); }; if (!script) { script = document.createElement('script'); script.id = scriptId; script.src = 'https://accounts.google.com/gsi/client'; script.async = true; script.defer = true; script.onload = initGoogle; document.head.appendChild(script); } else { initGoogle(); } }, []); return btnRef; } const LoginPage = ({ onGoogleLogin, onDevLogin }: LoginPageProps) => { const { t } = useTranslation(); const [error, setError] = useState(null); const handleGoogleCredential = useCallback( (credential: string) => { setError(null); onGoogleLogin(credential).catch(() => { setError(t('auth.loginFailed')); }); }, [onGoogleLogin, t], ); const googleBtnRef = useGoogleIdentity(handleGoogleCredential); return (
{/* Title */}
🛡️

{t('auth.title')}

{t('auth.subtitle')}

{/* Error */} {error && (
{error}
)} {/* Google Login Button */} {GOOGLE_CLIENT_ID && ( <>

{t('auth.domainNotice')}

)} {/* Dev Login */} {IS_DEV && ( <>
{t('auth.devNotice')}
)}
); }; export default LoginPage;