'use client'; import { useState } from 'react'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { Loader2, CheckCircle2 } from 'lucide-react'; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { useAuthStore } from '@/store/useAuthStore'; import { api, apiEndpoints, ApiError } from '@/lib/api'; import { registerSchema, type RegisterFormData } from '@/lib/validators'; import { useToast } from '@/hooks/use-toast'; export default function RegisterPage() { const router = useRouter(); const { toast } = useToast(); const { login } = useAuthStore(); const [isLoading, setIsLoading] = useState(false); const { register, handleSubmit, watch, setError, formState: { errors }, } = useForm({ resolver: zodResolver(registerSchema), }); const password = watch('password', ''); const getPasswordStrength = () => { if (!password) return { level: 0, label: '', color: '' }; let strength = 0; if (password.length >= 8) strength++; if (/[a-z]/.test(password)) strength++; if (/[A-Z]/.test(password)) strength++; if (/\d/.test(password)) strength++; if (/[^a-zA-Z\d]/.test(password)) strength++; const levels = [ { level: 1, label: 'Muy débil', color: 'bg-red-500' }, { level: 2, label: 'Débil', color: 'bg-orange-500' }, { level: 3, label: 'Aceptable', color: 'bg-yellow-500' }, { level: 4, label: 'Fuerte', color: 'bg-green-500' }, { level: 5, label: 'Muy fuerte', color: 'bg-green-600' }, ]; return levels[strength - 1] ?? levels[0]; }; const passwordStrength = getPasswordStrength(); const onSubmit = async (data: RegisterFormData) => { setIsLoading(true); try { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { confirmPassword: _confirmPassword, ...registerData } = data; const response = await api.post<{ user: { id: string; email: string; username: string; createdAt: string; lastLoginAt: string; }; token: string; refreshToken: string; }>(apiEndpoints.auth.register, registerData); login(response.user, response.token, response.refreshToken); toast({ title: '¡Cuenta creada!', description: 'Bienvenido a Math Platform.', }); router.push('/dashboard'); } catch (error) { // Handle field-specific validation errors from backend if (error instanceof ApiError && error.response) { const response = error.response as { error?: { details?: Record } }; if (response.error?.details) { // Set field-specific errors using react-hook-form's setError Object.entries(response.error.details).forEach(([field, message]) => { setError(field as keyof RegisterFormData, { type: 'server', message: message, }); }); } else { toast({ title: 'Error al crear cuenta', description: error.message, variant: 'destructive', }); } } else { toast({ title: 'Error al crear cuenta', description: error instanceof Error ? error.message : 'No se pudo crear la cuenta', variant: 'destructive', }); } } finally { setIsLoading(false); } }; const onSubmitHandler = (e: React.FormEvent) => { e.preventDefault(); void handleSubmit(onSubmit)(e); }; return ( Crear cuenta Regístrate para comenzar a aprender Álgebra Lineal
{errors.username && (

{errors.username.message}

)}

3-20 caracteres, debe empezar con letra. Solo letras, números y guiones bajos

{errors.email && (

{errors.email.message}

)}
{errors.password && (

{errors.password.message}

)} {password && passwordStrength && (

Fortaleza: {passwordStrength.label}

)}
{errors.confirmPassword && (

{errors.confirmPassword.message}

)} {password && watch('confirmPassword') && !errors.confirmPassword && (

Las contraseñas coinciden

)}

¿Ya tienes cuenta?{' '} Inicia sesión

); }