import { useEffect, useState } from 'react'; import { useSearchParams, useNavigate, useLocation } from 'react-router-dom'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { supabase } from '@/lib/supabase'; import { CheckCircle, XCircle, Loader2, ArrowLeft, Mail, RefreshCw } from 'lucide-react'; import { useTranslation } from 'react-i18next'; export default function EmailVerification() { const [searchParams] = useSearchParams(); const location = useLocation(); const navigate = useNavigate(); const [verifying, setVerifying] = useState(false); const [verified, setVerified] = useState(false); const [error, setError] = useState(''); const [resending, setResending] = useState(false); const [resent, setResent] = useState(false); const { t } = useTranslation(); // Get email from navigation state (after sign up) const email = location.state?.email; const token = searchParams.get('token'); const type = searchParams.get('type'); useEffect(() => { // Handle Supabase email confirmation callback if (type === 'signup' || type === 'email_change') { // Supabase handles this automatically via the URL hash // Check if we have an active session supabase.auth.getSession().then(({ data: { session } }) => { if (session) { setVerified(true); } }); } else if (token) { verifyEmail(token); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [token, type]); const verifyEmail = async (verifyToken: string) => { setVerifying(true); try { const { error } = await supabase.functions.invoke('email-verification', { body: { action: 'verify', token: verifyToken } }); if (error) throw error; setVerified(true); } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : t('emailVerify.failedToVerify'); setError(errorMessage); } finally { setVerifying(false); } }; const handleResendEmail = async () => { if (!email) return; setResending(true); setError(''); try { const { error } = await supabase.auth.resend({ type: 'signup', email: email, }); if (error) throw error; setResent(true); setTimeout(() => setResent(false), 5000); } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : 'Failed to resend email'; setError(errorMessage); } finally { setResending(false); } }; // Show "check your email" screen after sign up if (email && !token && !type) { return (
{email}
{t('emailVerify.checkInbox')}
{t('emailVerify.checkSpam')}
{error}
)} {resent && ({t('emailVerify.emailSent')}
)}{t('emailVerify.pleaseWait')}
{t('emailVerify.successDesc')}
{error}
{t('emailVerify.noTokenDesc')}