Improve frontend 5

This commit is contained in:
Urtzi Alfaro
2025-08-31 22:14:05 +02:00
parent c494078441
commit bde52d8ca2
16 changed files with 1989 additions and 2237 deletions

View File

@@ -1,7 +1,6 @@
import React, { useState, useRef, useEffect } from 'react';
import { Button, Input, Card } from '../../ui';
import { useAuth } from '../../../hooks/api/useAuth';
import { UserLogin } from '../../../types/auth.types';
import { useAuthActions, useAuthLoading, useAuthError } from '../../../stores/auth.store';
import { useToast } from '../../../hooks/ui/useToast';
interface LoginFormProps {
@@ -12,7 +11,9 @@ interface LoginFormProps {
autoFocus?: boolean;
}
interface ExtendedUserLogin extends UserLogin {
interface LoginCredentials {
email: string;
password: string;
remember_me: boolean;
}
@@ -23,16 +24,18 @@ export const LoginForm: React.FC<LoginFormProps> = ({
className,
autoFocus = true
}) => {
const [credentials, setCredentials] = useState<ExtendedUserLogin>({
const [credentials, setCredentials] = useState<LoginCredentials>({
email: '',
password: '',
remember_me: false
});
const [errors, setErrors] = useState<Partial<ExtendedUserLogin>>({});
const [errors, setErrors] = useState<Partial<LoginCredentials>>({});
const [showPassword, setShowPassword] = useState(false);
const emailInputRef = useRef<HTMLInputElement>(null);
const { login, isLoading, error } = useAuth();
const { login } = useAuthActions();
const isLoading = useAuthLoading();
const error = useAuthError();
const { showToast } = useToast();
// Auto-focus on email field when component mounts
@@ -43,7 +46,7 @@ export const LoginForm: React.FC<LoginFormProps> = ({
}, [autoFocus]);
const validateForm = (): boolean => {
const newErrors: Partial<ExtendedUserLogin> = {};
const newErrors: Partial<LoginCredentials> = {};
if (!credentials.email.trim()) {
newErrors.email = 'El email es requerido';
@@ -74,43 +77,39 @@ export const LoginForm: React.FC<LoginFormProps> = ({
}
try {
const loginData: UserLogin = {
email: credentials.email,
password: credentials.password,
remember_me: credentials.remember_me
};
const success = await login(loginData);
if (success) {
showToast({
type: 'success',
title: 'Sesión iniciada correctamente',
message: '¡Bienvenido de vuelta a tu panadería!'
});
onSuccess?.();
} else {
showToast({
type: 'error',
title: 'Error al iniciar sesión',
message: error || 'Email o contraseña incorrectos. Verifica tus credenciales.'
});
}
await login(credentials.email, credentials.password);
showToast({
type: 'success',
title: 'Sesión iniciada correctamente',
message: '¡Bienvenido de vuelta a tu panadería!'
});
onSuccess?.();
} catch (err) {
showToast({
type: 'error',
title: 'Error de conexión',
message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
title: 'Error al iniciar sesión',
message: error || 'Email o contraseña incorrectos. Verifica tus credenciales.'
});
}
};
const handleInputChange = (field: keyof ExtendedUserLogin) => (value: string | boolean) => {
const handleInputChange = (field: keyof LoginCredentials) => (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
setCredentials(prev => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }));
}
};
const handleDemoLogin = () => {
setCredentials({
email: 'admin@bakery.com',
password: 'admin12345',
remember_me: false
});
setErrors({});
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !isLoading) {
handleSubmit(e as any);
@@ -235,7 +234,7 @@ export const LoginForm: React.FC<LoginFormProps> = ({
<input
type="checkbox"
checked={credentials.remember_me}
onChange={(e) => handleInputChange('remember_me')(e.target.checked)}
onChange={handleInputChange('remember_me')}
className="rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0 h-4 w-4"
disabled={isLoading}
aria-describedby="remember-me-description"
@@ -295,6 +294,30 @@ export const LoginForm: React.FC<LoginFormProps> = ({
<div id="login-button-description" className="sr-only">
Presiona Enter o haz clic para iniciar sesión con tus credenciales
</div>
{/* Demo Login Section */}
<div className="mt-6">
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-border-primary" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-background-primary text-text-tertiary">Demo</span>
</div>
</div>
<div className="mt-6">
<Button
type="button"
variant="outline"
onClick={handleDemoLogin}
disabled={isLoading}
className="w-full focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2"
>
Usar credenciales de demostración
</Button>
</div>
</div>
</form>
{onRegisterClick && (

View File

@@ -128,7 +128,8 @@ export const PasswordResetForm: React.FC<PasswordResetFormProps> = ({
};
// Handle password change to update strength
const handlePasswordChange = (value: string) => {
const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setPassword(value);
setPasswordStrength(calculatePasswordStrength(value));
clearError('password');
@@ -361,8 +362,8 @@ export const PasswordResetForm: React.FC<PasswordResetFormProps> = ({
label="Correo Electrónico"
placeholder="tu.email@panaderia.com"
value={email}
onChange={(value) => {
setEmail(value);
onChange={(e) => {
setEmail(e.target.value);
clearError('email');
}}
error={errors.email}
@@ -486,8 +487,8 @@ export const PasswordResetForm: React.FC<PasswordResetFormProps> = ({
label="Confirmar Nueva Contraseña"
placeholder="Repite tu nueva contraseña"
value={confirmPassword}
onChange={(value) => {
setConfirmPassword(value);
onChange={(e) => {
setConfirmPassword(e.target.value);
clearError('confirmPassword');
}}
error={errors.confirmPassword}

View File

@@ -1,7 +1,6 @@
import React, { useState, useEffect, useRef } from 'react';
import { Button, Input, Card, Select, Avatar, Modal } from '../../ui';
import { useAuth } from '../../../hooks/api/useAuth';
import { User } from '../../../types/auth.types';
import { useAuthUser } from '../../../stores/auth.store';
import { useToast } from '../../../hooks/ui/useToast';
interface ProfileSettingsProps {
@@ -11,7 +10,8 @@ interface ProfileSettingsProps {
}
interface ProfileFormData {
full_name: string;
first_name: string;
last_name: string;
email: string;
phone: string;
language: string;
@@ -19,16 +19,6 @@ interface ProfileFormData {
avatar_url?: string;
}
interface BakeryFormData {
bakery_name: string;
bakery_type: string;
address: string;
city: string;
postal_code: string;
country: string;
website?: string;
description?: string;
}
interface NotificationSettings {
email_notifications: boolean;
@@ -50,29 +40,23 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
className,
initialTab = 'profile'
}) => {
const { user, updateProfile, isLoading, error } = useAuth();
const user = useAuthUser();
const { showToast } = useToast();
const fileInputRef = useRef<HTMLInputElement>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'profile' | 'security' | 'preferences' | 'notifications'>(initialTab);
// Mock data for profile
const [profileData, setProfileData] = useState<ProfileFormData>({
full_name: '',
email: '',
phone: '',
first_name: 'María',
last_name: 'González Pérez',
email: 'admin@bakery.com',
phone: '+34 612 345 678',
language: 'es',
timezone: 'Europe/Madrid',
avatar_url: ''
});
const [bakeryData, setBakeryData] = useState<BakeryFormData>({
bakery_name: '',
bakery_type: 'traditional',
address: '',
city: '',
postal_code: '',
country: 'España',
website: '',
description: ''
avatar_url: 'https://images.unsplash.com/photo-1494790108755-2616b612b372?w=150&h=150&fit=crop&crop=face'
});
const [notificationSettings, setNotificationSettings] = useState<NotificationSettings>({
@@ -105,17 +89,6 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [previewImage, setPreviewImage] = useState<string | null>(null);
const bakeryTypeOptions = [
{ value: 'traditional', label: 'Panadería Tradicional' },
{ value: 'artisan', label: 'Panadería Artesanal' },
{ value: 'industrial', label: 'Panadería Industrial' },
{ value: 'confectionery', label: 'Pastelería' },
{ value: 'bakery_cafe', label: 'Panadería Cafetería' },
{ value: 'specialty', label: 'Panadería Especializada' },
{ value: 'patisserie', label: 'Pastelería Francesa' },
{ value: 'organic', label: 'Panadería Orgánica' },
{ value: 'gluten_free', label: 'Panadería Sin Gluten' }
];
const languageOptions = [
{ value: 'es', label: 'Español' },
@@ -133,31 +106,25 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
{ value: 'Europe/Rome', label: 'Roma (CET/CEST)' }
];
// Initialize form data with user data
useEffect(() => {
if (user) {
setProfileData({
full_name: user.full_name || '',
email: user.email || '',
phone: user.phone || '',
language: user.language || 'es',
timezone: user.timezone || 'Europe/Madrid',
avatar_url: user.avatar_url || ''
});
// Mock update profile function
const updateProfile = async (data: any): Promise<boolean> => {
setIsLoading(true);
setError(null);
try {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Initialize bakery data (would come from a separate bakery API)
setBakeryData({
bakery_name: (user as any).bakery_name || '',
bakery_type: (user as any).bakery_type || 'traditional',
address: (user as any).address || '',
city: (user as any).city || '',
postal_code: (user as any).postal_code || '',
country: (user as any).country || 'España',
website: (user as any).website || '',
description: (user as any).description || ''
});
// Simulate successful update
console.log('Profile updated:', data);
setIsLoading(false);
return true;
} catch (err) {
setError('Error updating profile');
setIsLoading(false);
return false;
}
}, [user]);
};
// Profile picture upload handler
const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
@@ -227,10 +194,16 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
const validateProfileForm = (): boolean => {
const newErrors: Record<string, string> = {};
if (!profileData.full_name.trim()) {
newErrors.full_name = 'El nombre completo es requerido';
} else if (profileData.full_name.trim().length < 2) {
newErrors.full_name = 'El nombre debe tener al menos 2 caracteres';
if (!profileData.first_name.trim()) {
newErrors.first_name = 'El nombre es requerido';
} else if (profileData.first_name.trim().length < 2) {
newErrors.first_name = 'El nombre debe tener al menos 2 caracteres';
}
if (!profileData.last_name.trim()) {
newErrors.last_name = 'Los apellidos son requeridos';
} else if (profileData.last_name.trim().length < 2) {
newErrors.last_name = 'Los apellidos deben tener al menos 2 caracteres';
}
if (!profileData.email.trim()) {
@@ -242,37 +215,12 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
if (profileData.phone && !/^(\+34|0034|34)?[6-9][0-9]{8}$/.test(profileData.phone.replace(/\s/g, ''))) {
newErrors.phone = 'Por favor, ingrese un teléfono español válido (ej: +34 600 000 000)';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const validateBakeryForm = (): boolean => {
const newErrors: Record<string, string> = {};
if (!bakeryData.bakery_name.trim()) {
newErrors.bakery_name = 'El nombre de la panadería es requerido';
}
if (!bakeryData.address.trim()) {
newErrors.address = 'La dirección es requerida';
}
if (!bakeryData.city.trim()) {
newErrors.city = 'La ciudad es requerida';
}
if (bakeryData.postal_code && !/^[0-5][0-9]{4}$/.test(bakeryData.postal_code)) {
newErrors.postal_code = 'Por favor, ingrese un código postal español válido';
}
if (bakeryData.website && !/^https?:\/\/.+\..+/.test(bakeryData.website)) {
newErrors.website = 'Por favor, ingrese una URL válida (ej: https://mipanaderia.com)';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const validatePasswordForm = (): boolean => {
const newErrors: Record<string, string> = {};
@@ -358,15 +306,25 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
});
};
const handleProfileInputChange = (field: keyof ProfileFormData) => (value: string) => {
const handleProfileInputChange = (field: keyof ProfileFormData) => (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setProfileData(prev => ({ ...prev, [field]: value }));
setHasChanges(true);
setHasChanges(prev => ({ ...prev, profile: true }));
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }));
}
};
const handlePasswordInputChange = (field: keyof PasswordChangeData) => (value: string) => {
const handleSelectChange = (field: keyof ProfileFormData) => (value: string) => {
setProfileData(prev => ({ ...prev, [field]: value }));
setHasChanges(prev => ({ ...prev, profile: true }));
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }));
}
};
const handlePasswordInputChange = (field: keyof PasswordChangeData) => (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setPasswordData(prev => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }));
@@ -386,32 +344,47 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
{ id: 'preferences' as const, label: 'Preferencias', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z' }
];
if (!user) {
return (
<Card className={`p-8 ${className || ''}`}>
<div className="text-center text-text-secondary">
Cargando información del usuario...
</div>
</Card>
);
}
// Mock user data for display
const mockUser = {
first_name: 'María',
last_name: 'González',
email: 'admin@bakery.com',
bakery_name: 'Panadería San Miguel',
avatar_url: 'https://images.unsplash.com/photo-1494790108755-2616b612b372?w=150&h=150&fit=crop&crop=face'
};
return (
<div className={`space-y-6 ${className || ''}`}>
{/* Header */}
<Card className="p-6">
<div className="flex items-center space-x-4">
<Avatar
src={user.avatar_url}
name={`${user.first_name} ${user.last_name}`}
size="lg"
/>
<div>
<h1 className="text-2xl font-bold text-text-primary">
{user.first_name} {user.last_name}
<Card className="p-8">
<div className="flex items-center space-x-6">
<div className="relative">
<Avatar
src={mockUser.avatar_url}
name={`${mockUser.first_name} ${mockUser.last_name}`}
size="xl"
className="w-20 h-20 border-4 border-background-primary shadow-lg"
/>
<div className="absolute -bottom-1 -right-1 w-6 h-6 bg-color-success rounded-full border-2 border-background-primary"></div>
</div>
<div className="flex-1">
<h1 className="text-3xl font-bold text-text-primary mb-2">
{mockUser.first_name} {mockUser.last_name}
</h1>
<p className="text-text-secondary">{user.email}</p>
<p className="text-sm text-text-secondary">{user.bakery_name}</p>
<p className="text-text-secondary text-lg mb-1">{mockUser.email}</p>
<p className="text-sm text-text-tertiary flex items-center">
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
</svg>
Trabajando en {mockUser.bakery_name}
</p>
</div>
<div className="text-right">
<div className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-color-success/10 text-color-success mb-2">
<div className="w-2 h-2 bg-color-success rounded-full mr-2"></div>
En línea
</div>
<p className="text-xs text-text-tertiary">Última vez activo: ahora</p>
</div>
</div>
</Card>
@@ -439,141 +412,170 @@ export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
</nav>
</div>
<div className="p-6">
<div className="p-8">
{activeTab === 'profile' && (
<form onSubmit={handleProfileSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-4">
<h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
Información Personal
</h3>
<Input
label="Nombre"
value={profileData.first_name}
onChange={handleProfileInputChange('first_name')}
error={errors.first_name}
disabled={isLoading}
required
<div className="max-w-4xl mx-auto">
{/* Profile Photo Section */}
<div className="flex items-center space-x-8 mb-8 p-6 bg-background-secondary rounded-lg">
<div className="relative">
<Avatar
src={profileData.avatar_url}
name={`${profileData.first_name} ${profileData.last_name}`}
size="xl"
className="w-24 h-24"
/>
<Input
label="Apellidos"
value={profileData.last_name}
onChange={handleProfileInputChange('last_name')}
error={errors.last_name}
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="absolute -bottom-2 -right-2 bg-color-primary text-white rounded-full p-2 shadow-lg hover:bg-color-primary-dark transition-colors"
disabled={isLoading}
required
/>
<Input
type="email"
label="Email"
value={profileData.email}
onChange={handleProfileInputChange('email')}
error={errors.email}
disabled={isLoading}
required
/>
<Input
type="tel"
label="Teléfono"
value={profileData.phone}
onChange={handleProfileInputChange('phone')}
error={errors.phone}
disabled={isLoading}
placeholder="+34 600 000 000"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</button>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageUpload}
className="hidden"
/>
</div>
<div className="space-y-4">
<h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
Información del Negocio
</h3>
<Input
label="Nombre de la Panadería"
value={profileData.bakery_name}
onChange={handleProfileInputChange('bakery_name')}
error={errors.bakery_name}
disabled={isLoading}
required
/>
<Select
label="Tipo de Panadería"
options={bakeryTypeOptions}
value={profileData.bakery_type}
onChange={handleProfileInputChange('bakery_type')}
disabled={isLoading}
required
/>
<Input
label="Dirección"
value={profileData.address}
onChange={handleProfileInputChange('address')}
error={errors.address}
disabled={isLoading}
/>
<div className="grid grid-cols-2 gap-4">
<Input
label="Ciudad"
value={profileData.city}
onChange={handleProfileInputChange('city')}
error={errors.city}
disabled={isLoading}
/>
<div className="flex-1">
<h2 className="text-2xl font-bold text-text-primary mb-2">
{profileData.first_name} {profileData.last_name}
</h2>
<p className="text-text-secondary text-lg mb-2">{profileData.email}</p>
<p className="text-text-tertiary text-sm">Última actualización: Hace 2 días</p>
</div>
{uploadingImage && (
<div className="text-color-primary">
<svg className="animate-spin h-6 w-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
)}
</div>
<form onSubmit={handleProfileSubmit} className="space-y-8">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* Personal Information */}
<div className="space-y-6">
<h3 className="text-xl font-semibold text-text-primary border-b border-border-primary pb-3">
Información Personal
</h3>
<Input
label="País"
value={profileData.country}
onChange={handleProfileInputChange('country')}
disabled={isLoading}
/>
<div className="space-y-4">
<Input
label="Nombre"
value={profileData.first_name}
onChange={handleProfileInputChange('first_name')}
error={errors.first_name}
disabled={isLoading}
required
size="lg"
/>
<Input
label="Apellidos"
value={profileData.last_name}
onChange={handleProfileInputChange('last_name')}
error={errors.last_name}
disabled={isLoading}
required
size="lg"
/>
<Input
type="email"
label="Correo Electrónico"
value={profileData.email}
onChange={handleProfileInputChange('email')}
error={errors.email}
disabled={isLoading}
required
size="lg"
/>
<Input
type="tel"
label="Teléfono"
value={profileData.phone}
onChange={handleProfileInputChange('phone')}
error={errors.phone}
disabled={isLoading}
placeholder="+34 600 000 000"
size="lg"
/>
</div>
</div>
{/* Preferences */}
<div className="space-y-6">
<h3 className="text-xl font-semibold text-text-primary border-b border-border-primary pb-3">
Preferencias
</h3>
<div className="space-y-4">
<Select
label="Idioma"
options={languageOptions}
value={profileData.language}
onChange={handleSelectChange('language')}
disabled={isLoading}
size="lg"
/>
<Select
label="Zona Horaria"
options={timezoneOptions}
value={profileData.timezone}
onChange={handleSelectChange('timezone')}
disabled={isLoading}
size="lg"
/>
</div>
</div>
</div>
</div>
<div className="flex justify-end space-x-4 pt-6 border-t border-border-primary">
<Button
type="button"
variant="outline"
onClick={() => {
if (user) {
<div className="flex justify-end space-x-4 pt-8 border-t border-border-primary">
<Button
type="button"
variant="outline"
size="lg"
onClick={() => {
setProfileData({
first_name: user.first_name || '',
last_name: user.last_name || '',
email: user.email || '',
phone: user.phone || '',
bakery_name: user.bakery_name || '',
bakery_type: user.bakery_type || 'traditional',
address: user.address || '',
city: user.city || '',
country: user.country || 'España',
avatar_url: user.avatar_url || ''
first_name: 'María',
last_name: 'González Pérez',
email: 'admin@bakery.com',
phone: '+34 612 345 678',
language: 'es',
timezone: 'Europe/Madrid',
avatar_url: 'https://images.unsplash.com/photo-1494790108755-2616b612b372?w=150&h=150&fit=crop&crop=face'
});
setHasChanges(false);
setHasChanges(prev => ({ ...prev, profile: false }));
setErrors({});
}
}}
disabled={!hasChanges || isLoading}
>
Cancelar
</Button>
<Button
type="submit"
variant="primary"
isLoading={isLoading}
loadingText="Guardando..."
disabled={!hasChanges}
>
Guardar Cambios
</Button>
</div>
</form>
}}
disabled={!hasChanges.profile || isLoading}
>
Cancelar
</Button>
<Button
type="submit"
variant="primary"
size="lg"
isLoading={isLoading}
loadingText="Guardando..."
disabled={!hasChanges.profile}
>
Guardar Cambios
</Button>
</div>
</form>
</div>
)}
{activeTab === 'security' && (

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Button, Input, Card, Select } from '../../ui';
import React, { useState } from 'react';
import { Button, Input, Card } from '../../ui';
import { useAuth } from '../../../hooks/api/useAuth';
import { UserRegistration } from '../../../types/auth.types';
import { useToast } from '../../../hooks/ui/useToast';
@@ -8,89 +8,38 @@ interface RegisterFormProps {
onSuccess?: () => void;
onLoginClick?: () => void;
className?: string;
showProgressSteps?: boolean;
}
type RegistrationStep = 'personal' | 'bakery' | 'security' | 'verification';
interface ExtendedUserRegistration {
// Personal Information
interface SimpleUserRegistration {
full_name: string;
email: string;
phone: string;
// Bakery Information
tenant_name: string;
bakery_type: string;
address: string;
city: string;
postal_code: string;
country: string;
// Security
password: string;
confirmPassword: string;
// Terms
acceptTerms: boolean;
acceptPrivacy: boolean;
acceptMarketing: boolean;
}
export const RegisterForm: React.FC<RegisterFormProps> = ({
onSuccess,
onLoginClick,
className,
showProgressSteps = true
className
}) => {
const [currentStep, setCurrentStep] = useState<RegistrationStep>('personal');
const [completedSteps, setCompletedSteps] = useState<Set<RegistrationStep>>(new Set());
const [isEmailVerificationSent, setIsEmailVerificationSent] = useState(false);
const [formData, setFormData] = useState<ExtendedUserRegistration>({
const [formData, setFormData] = useState<SimpleUserRegistration>({
full_name: '',
email: '',
phone: '',
tenant_name: '',
bakery_type: 'traditional',
address: '',
city: '',
postal_code: '',
country: 'España',
password: '',
confirmPassword: '',
acceptTerms: false,
acceptPrivacy: false,
acceptMarketing: false
acceptTerms: false
});
const [errors, setErrors] = useState<Partial<ExtendedUserRegistration>>({});
const [errors, setErrors] = useState<Partial<SimpleUserRegistration>>({});
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const { register, verifyEmail, isLoading, error } = useAuth();
const { register, isLoading, error } = useAuth();
const { showToast } = useToast();
const steps: { id: RegistrationStep; title: string; description: string }[] = [
{ id: 'personal', title: 'Información Personal', description: 'Tus datos básicos' },
{ id: 'bakery', title: 'Tu Panadería', description: 'Detalles del negocio' },
{ id: 'security', title: 'Seguridad', description: 'Contraseña y términos' },
{ id: 'verification', title: 'Verificación', description: 'Confirmar email' }
];
const bakeryTypeOptions = [
{ value: 'traditional', label: 'Panadería Tradicional' },
{ value: 'artisan', label: 'Panadería Artesanal' },
{ value: 'industrial', label: 'Panadería Industrial' },
{ value: 'confectionery', label: 'Pastelería' },
{ value: 'bakery_cafe', label: 'Panadería Cafetería' },
{ value: 'specialty', label: 'Panadería Especializada' },
{ value: 'patisserie', label: 'Pastelería Francesa' },
{ value: 'organic', label: 'Panadería Orgánica' }
];
const validatePersonalStep = (): boolean => {
const newErrors: Partial<ExtendedUserRegistration> = {};
const validateForm = (): boolean => {
const newErrors: Partial<SimpleUserRegistration> = {};
if (!formData.full_name.trim()) {
newErrors.full_name = 'El nombre completo es requerido';
@@ -104,52 +53,10 @@ export const RegisterForm: React.FC<RegisterFormProps> = ({
newErrors.email = 'Por favor, ingrese un email válido';
}
if (!formData.phone.trim()) {
newErrors.phone = 'El teléfono es requerido';
} else if (!/^(\+34|0034|34)?[6-9][0-9]{8}$/.test(formData.phone.replace(/\s/g, ''))) {
newErrors.phone = 'Por favor, ingrese un teléfono español válido (ej: +34 600 000 000)';
}
setErrors(prev => ({ ...prev, ...newErrors }));
return Object.keys(newErrors).length === 0;
};
const validateBakeryStep = (): boolean => {
const newErrors: Partial<ExtendedUserRegistration> = {};
if (!formData.tenant_name.trim()) {
newErrors.tenant_name = 'El nombre de la panadería es requerido';
} else if (formData.tenant_name.trim().length < 2) {
newErrors.tenant_name = 'El nombre debe tener al menos 2 caracteres';
}
if (!formData.address.trim()) {
newErrors.address = 'La dirección es requerida';
}
if (!formData.city.trim()) {
newErrors.city = 'La ciudad es requerida';
}
if (!formData.postal_code.trim()) {
newErrors.postal_code = 'El código postal es requerido';
} else if (!/^[0-5][0-9]{4}$/.test(formData.postal_code)) {
newErrors.postal_code = 'Por favor, ingrese un código postal español válido (ej: 28001)';
}
setErrors(prev => ({ ...prev, ...newErrors }));
return Object.keys(newErrors).length === 0;
};
const validateSecurityStep = (): boolean => {
const newErrors: Partial<ExtendedUserRegistration> = {};
if (!formData.password) {
newErrors.password = 'La contraseña es requerida';
} else if (formData.password.length < 8) {
newErrors.password = 'La contraseña debe tener al menos 8 caracteres';
} else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])?/.test(formData.password)) {
newErrors.password = 'La contraseña debe contener mayúsculas, minúsculas y números';
}
if (!formData.confirmPassword) {
@@ -162,87 +69,41 @@ export const RegisterForm: React.FC<RegisterFormProps> = ({
newErrors.acceptTerms = 'Debes aceptar los términos y condiciones';
}
if (!formData.acceptPrivacy) {
newErrors.acceptPrivacy = 'Debes aceptar la política de privacidad';
}
setErrors(prev => ({ ...prev, ...newErrors }));
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleNextStep = (e?: React.FormEvent) => {
if (e) e.preventDefault();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let isValid = false;
switch (currentStep) {
case 'personal':
isValid = validatePersonalStep();
break;
case 'bakery':
isValid = validateBakeryStep();
break;
case 'security':
isValid = validateSecurityStep();
break;
default:
isValid = true;
if (!validateForm()) {
return;
}
if (isValid) {
setCompletedSteps(prev => new Set([...prev, currentStep]));
const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
const currentIndex = stepOrder.indexOf(currentStep);
if (currentIndex < stepOrder.length - 1) {
setCurrentStep(stepOrder[currentIndex + 1]);
setErrors({}); // Clear errors when moving to next step
}
// If this is the security step, submit the registration
if (currentStep === 'security') {
handleSubmitRegistration();
}
}
};
const handlePreviousStep = () => {
const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
const currentIndex = stepOrder.indexOf(currentStep);
if (currentIndex > 0) {
setCurrentStep(stepOrder[currentIndex - 1]);
setErrors({}); // Clear errors when going back
}
};
const handleSubmitRegistration = async () => {
try {
const registrationData: UserRegistration = {
full_name: formData.full_name,
email: formData.email,
password: formData.password,
tenant_name: formData.tenant_name,
phone: formData.phone
tenant_name: 'Default Bakery', // Default value since we're not collecting it
phone: '' // Optional field
};
const success = await register(registrationData);
if (success) {
setIsEmailVerificationSent(true);
setCurrentStep('verification');
showToast({
type: 'success',
title: 'Cuenta creada exitosamente',
message: 'Revisa tu email para verificar tu cuenta y completar el registro'
message: '¡Bienvenido! Tu cuenta ha sido creada correctamente.'
});
onSuccess?.();
} else {
showToast({
type: 'error',
title: 'Error al crear la cuenta',
message: error || 'No se pudo crear la cuenta. Verifica que el email no esté en uso.'
});
setCurrentStep('personal'); // Go back to first step to fix issues
}
} catch (err) {
showToast({
@@ -250,540 +111,181 @@ export const RegisterForm: React.FC<RegisterFormProps> = ({
title: 'Error de conexión',
message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
});
setCurrentStep('personal');
}
};
const handleInputChange = (field: keyof ExtendedUserRegistration) => (value: string | boolean) => {
const handleInputChange = (field: keyof SimpleUserRegistration) => (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
setFormData(prev => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }));
}
};
const getCurrentStepIndex = () => {
const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
return stepOrder.indexOf(currentStep);
};
const getProgressPercentage = () => {
return ((getCurrentStepIndex()) / (steps.length - 1)) * 100;
};
// Email verification success handler
const handleEmailVerification = async (token: string) => {
try {
const success = await verifyEmail(token);
if (success) {
showToast({
type: 'success',
title: 'Email verificado exitosamente',
message: '¡Tu cuenta ha sido activada! Ya puedes iniciar sesión.'
});
onSuccess?.();
} else {
showToast({
type: 'error',
title: 'Error de verificación',
message: 'El enlace de verificación no es válido o ha expirado'
});
}
} catch (err) {
showToast({
type: 'error',
title: 'Error de conexión',
message: 'No se pudo verificar el email. Intenta más tarde.'
});
}
};
return (
<Card className={`p-8 w-full max-w-4xl ${className || ''}`} role="main">
<Card className={`p-8 w-full max-w-md ${className || ''}`} role="main">
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-text-primary mb-2">
Registra tu Panadería
Crear Cuenta
</h1>
<p className="text-text-secondary text-lg">
Crea tu cuenta y comienza a digitalizar tu negocio
Únete y comienza hoy mismo
</p>
</div>
{/* Progress Indicator */}
{showProgressSteps && (
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
{steps.map((step, index) => (
<div
key={step.id}
className="flex flex-col items-center flex-1"
role="progressbar"
aria-valuenow={getCurrentStepIndex() + 1}
aria-valuemax={steps.length}
aria-label={`Paso ${index + 1} de ${steps.length}: ${step.title}`}
>
<div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold mb-2 transition-all duration-300 ${
completedSteps.has(step.id)
? 'bg-color-success text-white'
: currentStep === step.id
? 'bg-color-primary text-white ring-4 ring-color-primary/20'
: 'bg-background-secondary text-text-secondary'
}`}>
{completedSteps.has(step.id) ? (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
</svg>
) : (
index + 1
)}
</div>
<div className="text-center">
<div className={`text-xs font-medium ${
currentStep === step.id ? 'text-color-primary' : 'text-text-secondary'
}`}>
{step.title}
</div>
<div className="text-xs text-text-secondary mt-1">
{step.description}
</div>
</div>
{index < steps.length - 1 && (
<div className={`absolute top-5 left-1/2 w-full h-0.5 -z-10 ${
completedSteps.has(step.id) ? 'bg-color-success' : 'bg-background-secondary'
}`} style={{ marginLeft: '2.5rem' }} />
)}
</div>
))}
</div>
{/* Progress Bar */}
<div className="w-full bg-background-secondary rounded-full h-2">
<div
className="bg-color-primary h-2 rounded-full transition-all duration-500 ease-in-out"
style={{ width: `${getProgressPercentage()}%` }}
role="progressbar"
aria-label="Progreso del registro"
/>
</div>
</div>
)}
{/* Step Content */}
{currentStep !== 'verification' ? (
<form onSubmit={handleNextStep} className="space-y-8">
{/* Personal Information Step */}
{currentStep === 'personal' && (
<div className="space-y-6">
<div className="text-center mb-6">
<h2 className="text-xl font-semibold text-text-primary mb-2">
Información Personal
</h2>
<p className="text-text-secondary">
Cuéntanos sobre ti para personalizar tu experiencia
</p>
</div>
<div className="grid grid-cols-1 gap-6">
<Input
label="Nombre Completo"
placeholder="Juan Pérez García"
value={formData.full_name}
onChange={handleInputChange('full_name')}
error={errors.full_name}
disabled={isLoading}
required
autoComplete="name"
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
}
/>
<Input
type="email"
label="Correo Electrónico"
placeholder="tu.email@panaderia.com"
value={formData.email}
onChange={handleInputChange('email')}
error={errors.email}
disabled={isLoading}
required
autoComplete="email"
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
</svg>
}
/>
<Input
type="tel"
label="Teléfono"
placeholder="+34 600 000 000"
value={formData.phone}
onChange={handleInputChange('phone')}
error={errors.phone}
disabled={isLoading}
required
autoComplete="tel"
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
</svg>
}
/>
</div>
</div>
)}
{/* Bakery Information Step */}
{currentStep === 'bakery' && (
<div className="space-y-6">
<div className="text-center mb-6">
<h2 className="text-xl font-semibold text-text-primary mb-2">
Información de tu Panadería
</h2>
<p className="text-text-secondary">
Déjanos conocer los detalles de tu negocio
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Input
label="Nombre de la Panadería"
placeholder="Panadería San José"
value={formData.tenant_name}
onChange={handleInputChange('tenant_name')}
error={errors.tenant_name}
disabled={isLoading}
required
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
</svg>
}
/>
<Select
label="Tipo de Panadería"
options={bakeryTypeOptions}
value={formData.bakery_type}
onChange={handleInputChange('bakery_type')}
error={errors.bakery_type}
disabled={isLoading}
required
/>
</div>
<Input
label="Dirección"
placeholder="Calle Principal 123"
value={formData.address}
onChange={handleInputChange('address')}
error={errors.address}
disabled={isLoading}
required
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
}
/>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Input
label="Ciudad"
placeholder="Madrid"
value={formData.city}
onChange={handleInputChange('city')}
error={errors.city}
disabled={isLoading}
required
/>
<Input
label="Código Postal"
placeholder="28001"
value={formData.postal_code}
onChange={handleInputChange('postal_code')}
error={errors.postal_code}
disabled={isLoading}
required
maxLength={5}
/>
<Input
label="País"
value={formData.country}
onChange={handleInputChange('country')}
disabled={true}
required
/>
</div>
</div>
)}
{/* Security Step */}
{currentStep === 'security' && (
<div className="space-y-6">
<div className="text-center mb-6">
<h2 className="text-xl font-semibold text-text-primary mb-2">
Seguridad y Términos
</h2>
<p className="text-text-secondary">
Crea una contraseña segura y acepta nuestros términos
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Input
type={showPassword ? 'text' : 'password'}
label="Contraseña"
placeholder="Contraseña segura"
value={formData.password}
onChange={handleInputChange('password')}
error={errors.password}
disabled={isLoading}
autoComplete="new-password"
required
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
}
rightIcon={
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="text-text-secondary hover:text-text-primary"
aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
>
{showPassword ? (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
</svg>
) : (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
)}
</button>
}
/>
<Input
type={showConfirmPassword ? 'text' : 'password'}
label="Confirmar Contraseña"
placeholder="Repite tu contraseña"
value={formData.confirmPassword}
onChange={handleInputChange('confirmPassword')}
error={errors.confirmPassword}
disabled={isLoading}
autoComplete="new-password"
required
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
}
rightIcon={
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="text-text-secondary hover:text-text-primary"
aria-label={showConfirmPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
>
{showConfirmPassword ? (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
</svg>
) : (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
)}
</button>
}
/>
</div>
<div className="space-y-4 pt-4 border-t border-border-primary">
<div className="flex items-start space-x-3">
<input
type="checkbox"
id="acceptTerms"
checked={formData.acceptTerms}
onChange={(e) => handleInputChange('acceptTerms')(e.target.checked)}
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
disabled={isLoading}
/>
<label htmlFor="acceptTerms" className="text-sm text-text-secondary cursor-pointer">
Acepto los{' '}
<a href="#" className="text-color-primary hover:text-color-primary-dark underline">
términos y condiciones
</a>{' '}
de uso
</label>
</div>
{errors.acceptTerms && (
<p className="text-color-error text-sm ml-7">{errors.acceptTerms}</p>
)}
<div className="flex items-start space-x-3">
<input
type="checkbox"
id="acceptPrivacy"
checked={formData.acceptPrivacy}
onChange={(e) => handleInputChange('acceptPrivacy')(e.target.checked)}
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
disabled={isLoading}
/>
<label htmlFor="acceptPrivacy" className="text-sm text-text-secondary cursor-pointer">
Acepto la{' '}
<a href="#" className="text-color-primary hover:text-color-primary-dark underline">
política de privacidad
</a>
</label>
</div>
{errors.acceptPrivacy && (
<p className="text-color-error text-sm ml-7">{errors.acceptPrivacy}</p>
)}
<div className="flex items-start space-x-3">
<input
type="checkbox"
id="acceptMarketing"
checked={formData.acceptMarketing}
onChange={(e) => handleInputChange('acceptMarketing')(e.target.checked)}
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
disabled={isLoading}
/>
<label htmlFor="acceptMarketing" className="text-sm text-text-secondary cursor-pointer">
Deseo recibir información sobre nuevas funcionalidades y ofertas especiales
<span className="text-text-tertiary"> (opcional)</span>
</label>
</div>
</div>
</div>
)}
{/* Navigation Buttons */}
<div className="flex justify-between pt-6 border-t border-border-primary">
{currentStep !== 'personal' && (
<Button
type="button"
variant="outline"
onClick={handlePreviousStep}
disabled={isLoading}
className="flex items-center space-x-2"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
<span>Anterior</span>
</Button>
)}
<div className="flex-1" />
<Button
type="submit"
variant="primary"
size="lg"
isLoading={isLoading}
loadingText={currentStep === 'security' ? 'Creando cuenta...' : 'Procesando...'}
disabled={isLoading}
className="flex items-center space-x-2 min-w-[140px]"
>
{currentStep === 'security' ? (
<>
<span>Crear Cuenta</span>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</>
) : (
<>
<span>Continuar</span>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</>
)}
</Button>
</div>
{error && (
<div className="bg-color-error/10 border border-color-error/20 text-color-error px-4 py-3 rounded-lg text-sm flex items-start space-x-3" role="alert">
<svg className="w-5 h-5 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
<span>{error}</span>
</div>
)}
</form>
) : (
/* Verification Step */
<div className="text-center space-y-6">
<div className="w-20 h-20 bg-color-success/10 rounded-full flex items-center justify-center mx-auto mb-6">
<svg className="w-10 h-10 text-color-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
<form onSubmit={handleSubmit} className="space-y-6">
<Input
label="Nombre Completo"
placeholder="Juan Pérez García"
value={formData.full_name}
onChange={handleInputChange('full_name')}
error={errors.full_name}
disabled={isLoading}
required
autoComplete="name"
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
</div>
<h2 className="text-2xl font-bold text-text-primary mb-4">
¡Cuenta creada exitosamente!
</h2>
<div className="bg-background-secondary rounded-lg p-6 max-w-md mx-auto">
<p className="text-text-secondary mb-4">
Hemos enviado un enlace de verificación a:
</p>
<p className="text-text-primary font-semibold text-lg mb-4">
{formData.email}
</p>
<p className="text-text-secondary text-sm">
Revisa tu bandeja de entrada (y la carpeta de spam) y haz clic en el enlace para activar tu cuenta.
</p>
</div>
<div className="space-y-4 max-w-md mx-auto">
<Button
variant="outline"
onClick={() => {
setCurrentStep('personal');
setIsEmailVerificationSent(false);
setFormData({
full_name: '',
email: '',
phone: '',
tenant_name: '',
bakery_type: 'traditional',
address: '',
city: '',
postal_code: '',
country: 'España',
password: '',
confirmPassword: '',
acceptTerms: false,
acceptPrivacy: false,
acceptMarketing: false
});
setErrors({});
setCompletedSteps(new Set());
}}
className="w-full"
}
/>
<Input
type="email"
label="Correo Electrónico"
placeholder="tu.email@ejemplo.com"
value={formData.email}
onChange={handleInputChange('email')}
error={errors.email}
disabled={isLoading}
required
autoComplete="email"
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
</svg>
}
/>
<Input
type={showPassword ? 'text' : 'password'}
label="Contraseña"
placeholder="Contraseña segura"
value={formData.password}
onChange={handleInputChange('password')}
error={errors.password}
disabled={isLoading}
autoComplete="new-password"
required
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
}
rightIcon={
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="text-text-secondary hover:text-text-primary"
aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
>
Registrar otra cuenta
</Button>
{showPassword ? (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
</svg>
) : (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
)}
</button>
}
/>
<Input
type={showConfirmPassword ? 'text' : 'password'}
label="Confirmar Contraseña"
placeholder="Repite tu contraseña"
value={formData.confirmPassword}
onChange={handleInputChange('confirmPassword')}
error={errors.confirmPassword}
disabled={isLoading}
autoComplete="new-password"
required
leftIcon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
}
rightIcon={
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="text-text-secondary hover:text-text-primary"
aria-label={showConfirmPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
>
{showConfirmPassword ? (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
</svg>
) : (
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
)}
</button>
}
/>
<div className="space-y-4 pt-4 border-t border-border-primary">
<div className="flex items-start space-x-3">
<input
type="checkbox"
id="acceptTerms"
checked={formData.acceptTerms}
onChange={handleInputChange('acceptTerms')}
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
disabled={isLoading}
/>
<label htmlFor="acceptTerms" className="text-sm text-text-secondary cursor-pointer">
Acepto los{' '}
<a href="#" className="text-color-primary hover:text-color-primary-dark underline">
términos y condiciones
</a>{' '}
de uso
</label>
</div>
{errors.acceptTerms && (
<p className="text-color-error text-sm ml-7">{errors.acceptTerms}</p>
)}
</div>
)}
<Button
type="submit"
variant="primary"
size="lg"
isLoading={isLoading}
loadingText="Creando cuenta..."
disabled={isLoading}
className="w-full"
>
Crear Cuenta
</Button>
{error && (
<div className="bg-color-error/10 border border-color-error/20 text-color-error px-4 py-3 rounded-lg text-sm flex items-start space-x-3" role="alert">
<svg className="w-5 h-5 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
<span>{error}</span>
</div>
)}
</form>
{/* Login Link */}
{onLoginClick && currentStep !== 'verification' && (
{onLoginClick && (
<div className="mt-8 text-center border-t border-border-primary pt-6">
<p className="text-text-secondary mb-4">
¿Ya tienes una cuenta?