import { useState, useCallback, useEffect, useId } from 'react'; import { Trans, useTranslation } from 'react-i18next'; import { CloseIcon } from './icons/CloseIcon'; import { GoogleIcon } from './icons/GoogleIcon'; import { trackEvent } from '../../lib/analytics'; import { useModalA11y } from '../../hooks/useModalA11y'; type View = 'login' | 'register' | 'forgot'; export default function AuthModal({ onClose, onAuthenticated, onLogin, onRegister, onOAuthLogin, onForgotPassword, loading, error, onClearError, initialTab = 'login', }: { onClose: () => void; onAuthenticated?: () => void; onLogin: (email: string, password: string) => Promise; onRegister: (email: string, password: string) => Promise; onOAuthLogin: (provider: string) => Promise; onForgotPassword: (email: string) => Promise; loading: boolean; error: string | null; onClearError: () => void; initialTab?: 'login' | 'register'; }) { const { t } = useTranslation(); const [view, setView] = useState(initialTab); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [resetSent, setResetSent] = useState(false); const dialogRef = useModalA11y(); const fieldId = useId(); const emailInputId = `${fieldId}-email`; const passwordInputId = `${fieldId}-password`; useEffect(() => { trackEvent('Auth Modal Open', { tab: initialTab }); }, []); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); }; document.addEventListener('keydown', handleKeyDown); return () => document.removeEventListener('keydown', handleKeyDown); }, [onClose]); const switchView = useCallback( (newView: View) => { setView(newView); setResetSent(false); onClearError(); }, [onClearError] ); const handleSubmit = useCallback( async (e: React.FormEvent) => { e.preventDefault(); try { if (view === 'login') { await onLogin(email, password); onAuthenticated?.(); onClose(); } else if (view === 'register') { await onRegister(email, password); onAuthenticated?.(); onClose(); } else { await onForgotPassword(email); setResetSent(true); } } catch { // Error is handled by the hook } }, [view, email, password, onLogin, onRegister, onForgotPassword, onAuthenticated, onClose] ); const handleOAuth = useCallback( async (provider: string) => { try { await onOAuthLogin(provider); onAuthenticated?.(); onClose(); } catch { // Error is handled by the hook } }, [onOAuthLogin, onAuthenticated, onClose] ); const title = view === 'login' ? t('auth.logIn') : view === 'register' ? t('auth.createAccount') : t('auth.resetPassword'); return (
{ if (e.target === e.currentTarget) onClose(); }} role="presentation" >