'use client'; import { useState, useRef, useMemo } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; import Image from 'next/image'; import { useTranslation } from 'react-i18next'; import { User, Mail, Phone, Lock, Eye, EyeOff, MessageCircle, Camera, X, CheckCircle, XCircle, ArrowLeft, Building, Loader2, Shield, KeyRound, FileText } from 'lucide-react'; import toast, { Toaster } from 'react-hot-toast'; import { addOwner, loginWithEmail, sendEmailOTP, verifyEmail } from '../../utils/api'; import AuthService from '../../services/AuthService'; import { OwnerType, OwnerTypeLabels } from '../../enums'; export default function OwnerRegisterPage() { const router = useRouter(); const { t } = useTranslation(); const [step, setStep] = useState(1); const [showOtpModal, setShowOtpModal] = useState(false); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); const [isLoading, setIsLoading] = useState(false); const [formData, setFormData] = useState({ firstName: '', lastName: '', email: '', phone: '', whatsapp: '', phone2: '', nationalNumber: '', password: '', confirmPassword: '', ownerType: OwnerType.PERSON, agreeTerms: false }); const [idImages, setIdImages] = useState({ front: null, back: null, license: null }); const [idImagePreviews, setIdImagePreviews] = useState({ front: '', back: '', license: '' }); const [otpCode, setOtpCode] = useState(''); const [errors, setErrors] = useState({}); const fileInputFrontRef = useRef(null); const fileInputBackRef = useRef(null); const fileInputLicenseRef = useRef(null); const isCompany = Number(formData.ownerType) === OwnerType.REAL_ESTATE_AGENCY; const handleImageUpload = (side, file) => { if (!file) return; if (!file.type.startsWith('image/')) { toast.error(t('register.selectValidImage')); return; } if (file.size > 5 * 1024 * 1024) { toast.error(t('register.imageSizeLimit')); return; } const reader = new FileReader(); reader.onloadend = () => { setIdImagePreviews(prev => ({ ...prev, [side]: reader.result })); }; reader.readAsDataURL(file); setIdImages(prev => ({ ...prev, [side]: file })); toast.success(t('register.imageUploadSuccess'), { style: { background: '#dcfce7', color: '#166534' } }); }; const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); const validatePhone = (phone) => /^(09|05)[0-9]{8}$/.test(phone); const validateStep1 = () => { const newErrors = {}; if (!formData.firstName) newErrors.firstName = t('register.firstNameRequired'); if (!formData.lastName) newErrors.lastName = t('register.lastNameRequired'); if (!formData.email) newErrors.email = t('register.emailRequired'); else if (!validateEmail(formData.email)) newErrors.email = t('register.emailInvalid'); if (!formData.phone) newErrors.phone = t('register.phoneRequired'); else if (!validatePhone(formData.phone)) newErrors.phone = t('register.phoneInvalid') + ` (${t('register.phoneMustStartWith')} 09/05)`; if (!formData.whatsapp) newErrors.whatsapp = t('register.whatsappRequired'); else if (!validatePhone(formData.whatsapp)) newErrors.whatsapp = t('register.phoneInvalid') + ` (${t('register.phoneMustStartWith')} 09/05)`; if (!formData.password) newErrors.password = t('register.passwordRequired'); else if (formData.password.length < 6) newErrors.password = t('validation.passwordMinLength'); if (formData.password !== formData.confirmPassword) newErrors.confirmPassword = t('validation.passwordsMatch'); setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const validateStep2 = () => { const newErrors = {}; if (!idImages.front) newErrors.front = t('register.frontIdRequired'); if (!idImages.back) newErrors.back = t('register.backIdRequired'); setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleNextStep = () => { if (validateStep1()) { setStep(2); window.scrollTo({ top: 0, behavior: 'smooth' }); } else { toast.error(t('validation.correctErrors')); } }; const handleSubmit = async (e) => { e.preventDefault(); if (!validateStep2()) { toast.error(t('register.completeRequiredImages')); return; } if (!formData.agreeTerms) { toast.error(t('validation.agreeToTerms')); return; } setIsLoading(true); const payload = { firstName: formData.firstName, lastName: formData.lastName, email: formData.email, phoneNumber: formData.phone || '', whatsAppNumber: formData.whatsapp, phone: formData.phone2, nationalNumber: formData.nationalNumber, password: formData.password, ownerType: formData.ownerType, }; try { const licenseImage = isCompany ? idImages.license : null; const res = await addOwner(payload, idImages.front, idImages.back, licenseImage); if (res.status === 200 || res.ok) { const tempToken = res.data; if (tempToken) AuthService.addToken(tempToken); toast.success(res.message || t('register.accountCreated'), { duration: 4000 }); const loginRes = await loginWithEmail(formData.email, formData.password); if (loginRes.status === 206) { const otpToken = loginRes.data; if (otpToken) AuthService.addToken(otpToken); toast(loginRes.message || t('register.otpSentEmail'), { icon: '📧' }); setShowOtpModal(true); } else if (loginRes.status === 200) { const loginToken = loginRes.data; if (loginToken) AuthService.addToken(loginToken); toast.success(loginRes.message || t('register.loginSuccess')); router.push('/'); } } else { toast.error(res.message || res.data?.message || t('register.accountCreationFailed')); } } catch (err) { toast.error(err.message || t('register.registrationError')); } finally { setIsLoading(false); } }; const handleVerifyOTP = async () => { if (!otpCode || otpCode.length < 4) { toast.error(t('register.otpRequired')); return; } setIsLoading(true); try { const res = await verifyEmail(otpCode); if (res.status === 200) { AuthService.deleteToken(); toast.success(res.message || t('register.emailVerified')); setShowOtpModal(false); setTimeout(() => router.push('/login'), 1500); } else { toast.error(res.message || res.data?.message || t('accountVerification.otpInvalid')); } } catch (err) { toast.error(err.message || t('register.verificationError')); } finally { setIsLoading(false); } }; const handleResendOTP = async () => { setIsLoading(true); try { await sendEmailOTP(); toast.success(t('register.newOtpSent')); } catch (err) { toast.error(t('register.resendOtpFailed')); } finally { setIsLoading(false); } }; const fadeInUp = { initial: { opacity: 0, y: 20 }, animate: { opacity: 1, y: 0 }, transition: { duration: 0.5 } }; const staggerContainer = { animate: { transition: { staggerChildren: 0.1 } } }; const backgroundElements = useMemo(() => { const circles = [ { style: { top: '20%', right: '20%', width: '256px', height: '256px' }, className: 'bg-amber-500/5' }, { style: { bottom: '20%', left: '20%', width: '320px', height: '320px' }, className: 'bg-blue-500/5' }, { style: { top: '50%', left: '50%', width: '384px', height: '384px', transform: 'translate(-50%, -50%)' }, className: 'bg-purple-500/5' }, ]; const dots = Array.from({ length: 10 }).map((_, i) => ({ left: `${5 + i * 10}%`, top: `${10 + (i * 7) % 80}%`, size: `${80 + (i % 5) * 15}px` })); return ( <> {circles.map((circle, i) => (
))} {dots.map((dot, i) => (
))} ); }, []); return (
{backgroundElements}
{t('forgotPassword.backToLogin')} {t('register.stepOf2', { step: step })}
{[1, 2].map((s) => ( = s ? 'bg-amber-500' : 'bg-gray-700'}`} animate={{ scaleX: step >= s ? 1 : 0.5 }} /> ))}

{step === 1 ? t('register.owner.step1Title') : t('register.owner.step1bTitle')}

{step === 1 ? t('register.owner.step1Desc') : t('register.owner.step1bDesc')}

{ e.preventDefault(); handleNextStep(); } : handleSubmit} className="space-y-6"> {step === 1 && ( <>
{ setFormData({...formData, firstName: e.target.value}); setErrors({...errors, firstName: null}); }} className={`w-full pr-12 pl-4 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.firstName ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.firstName')} />
{errors.firstName &&

{errors.firstName}

}
{ setFormData({...formData, lastName: e.target.value}); setErrors({...errors, lastName: null}); }} className={`w-full px-4 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.lastName ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.lastName')} /> {errors.lastName &&

{errors.lastName}

}
{ setFormData({...formData, email: e.target.value}); setErrors({...errors, email: null}); }} className={`w-full pr-12 pl-4 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.email ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.emailPlaceholder')} />
{errors.email &&

{errors.email}

}
{ setFormData({...formData, phone: e.target.value}); setErrors({...errors, phone: null}); }} className="w-full pr-12 pl-4 py-3 bg-white/5 border border-gray-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all" placeholder={t('register.phoneOptionalPlaceholder')} />
{errors.phone &&

{errors.phone}

}
{ setFormData({...formData, whatsapp: e.target.value}); setErrors({...errors, whatsapp: null}); }} className={`w-full pr-12 pl-4 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.whatsapp ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.whatsappPlaceholder')} />
{errors.whatsapp &&

{errors.whatsapp}

}
{ setFormData({...formData, phone2: e.target.value}); setErrors({...errors, phone2: null}); }} className={`w-full pr-12 pl-4 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.phone2 ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.phoneSecondaryPlaceholder')} maxLength={7} />
{errors.phone2 &&

{errors.phone2}

}
{ setFormData({...formData, nationalNumber: e.target.value}); setErrors({...errors, nationalNumber: null}); }} className={`w-full pr-12 pl-4 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.nationalNumber ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.nationalNumberPlaceholder')} />
{errors.nationalNumber &&

{errors.nationalNumber}

}
{isCompany && (
{t('register.owner.licenseHint')}
fileInputLicenseRef.current?.click()} className={`relative border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all ${idImagePreviews.license ? 'border-green-500 bg-green-500/10' : 'border-gray-700 hover:border-amber-500 hover:bg-white/5'}`}> handleImageUpload('license', e.target.files?.[0])} className="hidden" /> {idImagePreviews.license ? (
{t('register.uploadLicenseAlt')}
) : (<>

{t('register.owner.clickUploadLicense')}

JPEG, PNG, JPG • {t('register.upTo5MB')}

)}
)}
{ setFormData({...formData, password: e.target.value}); setErrors({...errors, password: null}); }} className={`w-full pr-12 pl-12 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.password ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.passwordPlaceholder')} />
{errors.password &&

{errors.password}

}
{ setFormData({...formData, confirmPassword: e.target.value}); setErrors({...errors, confirmPassword: null}); }} className={`w-full pr-12 pl-12 py-3 bg-white/5 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white placeholder-gray-500 transition-all ${errors.confirmPassword ? 'border-red-500' : 'border-gray-700'}`} placeholder={t('register.confirmPasswordPlaceholder')} /> {formData.confirmPassword && (
{formData.password === formData.confirmPassword ? : }
)}
{errors.confirmPassword &&

{errors.confirmPassword}

}
)} {step === 2 && ( <>
fileInputFrontRef.current?.click()} className={`relative border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all ${idImagePreviews.front ? 'border-green-500 bg-green-500/10' : errors.front ? 'border-red-500 bg-red-500/10' : 'border-gray-700 hover:border-amber-500 hover:bg-white/5'}`}> handleImageUpload('front', e.target.files?.[0])} className="hidden" /> {idImagePreviews.front ? (
{t('register.uploadFrontAlt')}
) : (<>

{t('register.owner.clickUploadImage')}

JPEG, PNG, JPG • {t('register.upTo5MB')}

)}
{errors.front &&

{errors.front}

}
fileInputBackRef.current?.click()} className={`relative border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all ${idImagePreviews.back ? 'border-green-500 bg-green-500/10' : errors.back ? 'border-red-500 bg-red-500/10' : 'border-gray-700 hover:border-amber-500 hover:bg-white/5'}`}> handleImageUpload('back', e.target.files?.[0])} className="hidden" /> {idImagePreviews.back ? (
{t('register.uploadBackAlt')}
) : (<>

{t('register.owner.clickUploadImage')}

JPEG, PNG, JPG • {t('register.upTo5MB')}

)}
{errors.back &&

{errors.back}

}
setFormData({...formData, agreeTerms: e.target.checked})} className="w-4 h-4 rounded border-gray-600 bg-white/5 text-amber-500 focus:ring-amber-500" required /> )} {step === 1 ? ( <> ) : ( <> )}
{showOtpModal && (

{t('register.otpTitle')}

{t('register.otpSentTo')}

{formData.email}

setOtpCode(e.target.value)} className="w-full pr-12 pl-4 py-3 bg-white/5 border border-gray-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 text-white text-center tracking-[0.5em] text-xl" placeholder="------" />
)}
); }