'use client'; import { useEffect, useState, Suspense, useRef } from 'react'; import { useRouter, useSearchParams } from 'next/navigation'; import { useLanguage } from '@/context/LanguageContext'; import { useAuth } from '@/context/AuthContext'; import Card from '@/components/ui/Card'; import Button from '@/components/ui/Button'; import { safeInternalPath } from '@/lib/safeRedirect'; import { redirectAfterAuth } from '@/lib/authRedirect'; import toast from 'react-hot-toast'; function MagicLinkContent() { const router = useRouter(); const searchParams = useSearchParams(); const { locale: language } = useLanguage(); const { loginWithMagicLink } = useAuth(); const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading'); const [error, setError] = useState(''); const verificationAttempted = useRef(false); const token = searchParams.get('token'); const callbackURL = safeInternalPath(searchParams.get('callbackURL'), '/dashboard'); useEffect(() => { // Prevent duplicate verification attempts (React StrictMode double-invokes effects) if (verificationAttempted.current) return; if (token) { verificationAttempted.current = true; verifyToken(); } else { setStatus('error'); setError(language === 'es' ? 'Token no encontrado' : 'Token not found'); } }, [token]); const verifyToken = async () => { try { const user = await loginWithMagicLink(token!); setStatus('success'); toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome!'); // Unclaimed accounts must finish the claim (set a password) before the // rest of the API will accept their session. const destination = user && (user.isClaimed === false || user.accountStatus === 'unclaimed') ? '/auth/claim-account' : callbackURL; setTimeout(() => { redirectAfterAuth(destination); }, 1500); } catch (err: any) { setStatus('error'); setError(err.message || (language === 'es' ? 'Enlace inválido o expirado' : 'Invalid or expired link')); } }; return (
{status === 'loading' && ( <>

{language === 'es' ? 'Verificando...' : 'Verifying...'}

{language === 'es' ? 'Por favor espera' : 'Please wait'}

)} {status === 'success' && ( <>

{language === 'es' ? '¡Inicio de sesión exitoso!' : 'Login successful!'}

{language === 'es' ? 'Redirigiendo...' : 'Redirecting...'}

)} {status === 'error' && ( <>

{language === 'es' ? 'Error de Verificación' : 'Verification Error'}

{error}

)}
); } function LoadingFallback() { return (
); } export default function MagicLinkPage() { return ( }> ); }