Spaces:
Sleeping
Sleeping
File size: 19,363 Bytes
5463318 38ee1b6 5463318 38ee1b6 5463318 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { User, Mail, Lock, Building2, Check, CheckCircle2, Loader2, ArrowRight, ArrowLeft, GraduationCap, School, Users } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { AuthInput } from './AuthInput';
import { useToast } from '../ui/Toast';
import { useAuthToggle } from './AuthToggleContext';
import { cn } from '../../../src/utils/cn';
import { supabase } from '../../../src/utils/supabaseClient';
import { API_BASE_URL } from '../../../src/utils/api';
import bcrypt from 'bcryptjs';
const roles = [
{ id: 'school', label: 'School Teacher', icon: School, color: 'from-blue-500 to-cyan-500' },
{ id: 'college', label: 'College Professor', icon: GraduationCap, color: 'from-violet-500 to-purple-500' },
{ id: 'coach', label: 'Coaching Instructor', icon: Users, color: 'from-emerald-500 to-teal-500' }
];
export const SignupForm = () => {
const [step, setStep] = useState(1);
const [formData, setFormData] = useState({
name: '', email: '', password: '', confirmPassword: '', institution: '', role: ''
});
const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [errors, setErrors] = useState({});
const navigate = useNavigate();
const { addToast } = useToast();
const { toggleMode } = useAuthToggle();
const updateForm = (field, value) => {
setFormData(prev => ({ ...prev, [field]: value }));
if (errors[field]) setErrors(prev => { const newErr = { ...prev }; delete newErr[field]; return newErr; });
};
// Password validation logic
const pwdState = {
length: formData.password.length >= 8,
number: /\d/.test(formData.password),
special: /[!@#$%^&*(),.?":{}|<>]/.test(formData.password),
};
const pwdStrengthCount = Object.values(pwdState).filter(Boolean).length;
const pwdStrengthLabel = pwdStrengthCount === 0 ? '' : pwdStrengthCount === 1 ? 'Weak' : pwdStrengthCount === 2 ? 'Medium' : 'Strong';
const pwdStrengthColor = pwdStrengthCount <= 1 ? 'bg-red-500' : pwdStrengthCount === 2 ? 'bg-amber-500' : 'bg-emerald-500 text-emerald-500 drop-shadow-[0_0_8px_rgba(16,185,129,0.8)]';
const handleNext = () => {
let currentErrors = {};
if (step === 1) {
if (!formData.name) currentErrors.name = 'Name is required';
if (!formData.email) currentErrors.email = 'Email is required';
else if (!/\S+@\S+\.\S+/.test(formData.email)) currentErrors.email = 'Valid email required';
if (Object.keys(currentErrors).length > 0) return setErrors(currentErrors);
setStep(2);
} else if (step === 2) {
if (pwdStrengthCount < 3) currentErrors.password = 'Password does not meet requirements';
if (formData.password !== formData.confirmPassword) currentErrors.confirmPassword = 'Passwords must match';
if (!formData.institution) currentErrors.institution = 'Institution is required';
if (Object.keys(currentErrors).length > 0) return setErrors(currentErrors);
setStep(3);
}
};
const handleBack = () => setStep(step - 1);
const handleSubmit = async (e) => {
if (e) e.preventDefault();
setIsLoading(true);
try {
const { data, error } = await supabase.auth.signUp({
email: formData.email,
password: formData.password,
options: {
data: {
full_name: formData.name,
work_email: formData.email,
institution_name: formData.institution,
role: formData.role,
avatar_url: `https://ui-avatars.com/api/?name=${encodeURIComponent(formData.name)}&background=random`
}
}
});
if (error) throw error;
// Hash password securely with bcrypt
if (data?.user) {
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(formData.password, salt);
// Update the user's profile with the encrypted password immediately via backend API
try {
const response = await fetch(`${API_BASE_URL}/api/profile`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.session.access_token}`
},
body: JSON.stringify({ password: hashedPassword })
});
if (!response.ok) {
const errorData = await response.json();
console.error("Failed to sync encrypted password to profile:", errorData);
}
} catch (err) {
console.error("Failed to sync encrypted password to profile network error:", err);
}
}
setIsSuccess(true);
setTimeout(() => {
navigate('/app');
addToast({
title: 'Welcome to ExamCraft.AI!',
description: 'Your educator account is ready.',
variant: 'success'
});
}, 600);
} catch (error) {
addToast({
title: 'Registration Failed',
description: error.message || 'Something went wrong.',
variant: 'destructive',
});
// Revert step back to 1 if it totally fails
setStep(1);
} finally {
setIsLoading(false);
}
};
// Keyboard navigation (Enter to submit/next)
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
if (step < 3) handleNext();
else handleSubmit();
}
};
const slideVariants = {
enter: (direction) => ({ x: direction > 0 ? 50 : -50, opacity: 0 }),
center: { x: 0, opacity: 1 },
exit: (direction) => ({ x: direction < 0 ? 50 : -50, opacity: 0 })
};
return (
<div className="w-full h-full flex flex-col justify-center max-w-sm mx-auto" onKeyDown={handleKeyDown}>
<motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="mb-6">
<h2 className="text-3xl font-extrabold mb-1 text-slate-900 dark:text-white tracking-tight">
Join ExamCraft.AI
</h2>
<p className="text-slate-500 dark:text-slate-400 text-sm font-medium">Start generating intelligent question papers today.</p>
</motion.div>
{/* Progress Bar */}
<div className="flex items-center gap-2 mb-8">
{[1, 2, 3].map(item => (
<div key={item} className={cn(
"h-1.5 flex-1 rounded-full transition-all duration-300",
step >= item ? "bg-gradient-to-r from-[#8B5CF6] to-[#4F7CFF]" : "bg-slate-200 dark:bg-slate-800"
)} />
))}
</div>
<div className="relative overflow-visible h-auto min-h-[300px]">
<AnimatePresence mode="popLayout" custom={step}>
{step === 1 && (
<motion.div key="step1" custom={1} variants={slideVariants} initial="enter" animate="center" exit="exit" transition={{ duration: 0.3 }} className="space-y-4">
<AuthInput
label="Full Name" type="text" value={formData.name} onChange={e => updateForm('name', e.target.value)}
error={errors.name} isValid={formData.name.length > 2} icon={User} placeholder="Prof. Jane Doe" autoFocus
/>
<div className="relative">
<AuthInput
label="Work Email" type="email" value={formData.email} onChange={e => updateForm('email', e.target.value)}
error={errors.email} isValid={/\S+@\S+\.\S+/.test(formData.email)} icon={Mail} placeholder="jane@university.edu"
/>
{formData.email.endsWith('.edu') && (
<motion.div initial={{ scale: 0 }} animate={{ scale: 1 }} className="absolute right-12 top-11 bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300 text-[10px] font-bold px-1.5 py-0.5 rounded uppercase tracking-widest hidden sm:block pointer-events-none">
Edu Verified
</motion.div>
)}
</div>
<button type="button" onClick={handleNext} className="w-full rounded-xl bg-slate-900 dark:bg-white text-white dark:text-slate-900 font-bold py-3.5 hover:shadow-lg transition-all flex items-center justify-center gap-2 mt-4 hover:bg-slate-800 dark:hover:bg-slate-100">
Continue <ArrowRight size={18} />
</button>
</motion.div>
)}
{step === 2 && (
<motion.div key="step2" custom={1} variants={slideVariants} initial="enter" animate="center" exit="exit" transition={{ duration: 0.3 }} className="space-y-4">
<AuthInput label="Institution Name" type="text" value={formData.institution} onChange={e => updateForm('institution', e.target.value)} error={errors.institution} isValid={formData.institution.length > 2} icon={Building2} placeholder="Oxford Academy" autoFocus />
<AuthInput label="Create Password" type="password" value={formData.password} onChange={e => updateForm('password', e.target.value)} error={errors.password} isValid={pwdStrengthCount === 3} icon={Lock} placeholder="••••••••" />
{/* Password Strength Meter */}
{formData.password.length > 0 && (
<motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} className="px-1 -mt-2 mb-4">
<div className="flex gap-1 mb-1.5">
{[1, 2, 3].map((s) => (
<div key={s} className={cn("h-1 flex-1 rounded-full transition-colors", pwdStrengthCount >= s ? pwdStrengthColor : "bg-slate-200 dark:bg-slate-700")} />
))}
</div>
<div className="flex justify-between items-center text-[10px] font-medium text-slate-500 mt-1 mb-2">
<span>Strength: <span className={cn(pwdStrengthCount === 3 ? "text-emerald-500" : "")}>{pwdStrengthLabel}</span></span>
</div>
<div className="grid grid-cols-2 text-[10px] gap-1 text-slate-500">
<div className={cn("flex items-center gap-1 transition-colors", pwdState.length && "text-emerald-500")}>
<Check size={10} /> 8+ Characters
</div>
<div className={cn("flex items-center gap-1 transition-colors", pwdState.number && "text-emerald-500")}>
<Check size={10} /> 1 Number
</div>
<div className={cn("flex items-center gap-1 transition-colors", pwdState.special && "text-emerald-500")}>
<Check size={10} /> 1 Special Ch.
</div>
</div>
</motion.div>
)}
<AuthInput label="Confirm Password" type="password" value={formData.confirmPassword} onChange={e => updateForm('confirmPassword', e.target.value)} error={errors.confirmPassword} isValid={formData.password === formData.confirmPassword && formData.confirmPassword.length > 0} icon={Lock} placeholder="••••••••" />
<div className="flex gap-3 pt-2">
<button type="button" onClick={handleBack} className="w-1/3 rounded-xl border border-slate-200 dark:border-white/10 text-slate-600 dark:text-slate-300 font-semibold py-3.5 hover:bg-slate-50 dark:hover:bg-white/5 transition-all flex items-center justify-center">
<ArrowLeft size={18} />
</button>
<button type="button" onClick={handleNext} className="w-2/3 rounded-xl bg-slate-900 dark:bg-white text-white dark:text-slate-900 font-bold py-3.5 hover:shadow-lg transition-all flex items-center justify-center gap-2 hover:bg-slate-800 dark:hover:bg-slate-100">
Continue <ArrowRight size={18} />
</button>
</div>
</motion.div>
)}
{step === 3 && (
<motion.div key="step3" custom={1} variants={slideVariants} initial="enter" animate="center" exit="exit" transition={{ duration: 0.3 }}>
<p className="text-sm font-semibold text-slate-700 dark:text-white mb-4">I identify mostly as a...</p>
<div className="space-y-3 mb-6">
{roles.map(role => (
<div
key={role.id}
onClick={() => updateForm('role', role.id)}
className={cn(
"relative flex items-center gap-4 p-4 rounded-xl border cursor-pointer transition-all duration-300 group overflow-hidden",
formData.role === role.id
? "border-[#4F7CFF] bg-[#4F7CFF]/5 shadow-[0_4px_20px_rgba(79,124,255,0.15)]"
: "border-slate-200 dark:border-white/10 hover:border-slate-300 dark:hover:border-white/20 bg-white dark:bg-[#111827]/80 hover:bg-slate-50 dark:hover:bg-white/5"
)}
>
<div className={cn("w-10 h-10 rounded-lg flex items-center justify-center bg-gradient-to-br text-white shadow-sm", role.color)}>
<role.icon size={20} />
</div>
<span className={cn("font-medium transition-colors", formData.role === role.id ? "text-[#4F7CFF]" : "text-slate-700 dark:text-slate-200 group-hover:text-slate-900 dark:group-hover:text-white")}>
{role.label}
</span>
{formData.role === role.id && (
<motion.div layoutId="role-check" className="absolute right-4 text-[#4F7CFF]">
<CheckCircle2 className="w-5 h-5" />
</motion.div>
)}
</div>
))}
</div>
<div className="flex gap-3">
<button type="button" onClick={handleBack} className="w-14 rounded-xl border border-slate-200 dark:border-white/10 text-slate-600 dark:text-slate-300 font-semibold py-3.5 hover:bg-slate-50 dark:hover:bg-white/5 transition-all flex items-center justify-center shrink-0">
<ArrowLeft size={18} />
</button>
<motion.button
type="button"
onClick={handleSubmit}
disabled={isLoading || isSuccess}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
className="group relative flex-1 rounded-xl bg-gradient-to-r from-[#8B5CF6] to-[#4F7CFF] text-white font-bold py-3.5 hover:shadow-[0_0_20px_rgba(79,124,255,0.4)] transition-all duration-300 disabled:opacity-80 flex items-center justify-center overflow-hidden"
>
<AnimatePresence mode="wait">
{isLoading ? (
<motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
<Loader2 className="w-5 h-5 animate-spin" />
</motion.div>
) : isSuccess ? (
<motion.div key="success" initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: 'spring', stiffness: 300, damping: 20 }}>
<Check className="w-6 h-6 text-white" strokeWidth={3} />
</motion.div>
) : (
<motion.span key="text" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
Create Account
</motion.span>
)}
</AnimatePresence>
<div className="absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/20 to-transparent group-hover:animate-[shimmer_1.5s_infinite] pointer-events-none" />
</motion.button>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
{/* Switch to Login */}
<div className="mt-8 text-center">
<p className="text-sm text-slate-500">
Already have an account?{' '}
<button onClick={toggleMode} type="button" className="font-semibold text-[#4F7CFF] hover:underline">
Sign in
</button>
</p>
</div>
</div>
);
};
|