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 (

Join ExamCraft.AI

Start generating intelligent question papers today.

{/* Progress Bar */}
{[1, 2, 3].map(item => (
= item ? "bg-gradient-to-r from-[#8B5CF6] to-[#4F7CFF]" : "bg-slate-200 dark:bg-slate-800" )} /> ))}
{step === 1 && ( updateForm('name', e.target.value)} error={errors.name} isValid={formData.name.length > 2} icon={User} placeholder="Prof. Jane Doe" autoFocus />
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') && ( Edu Verified )}
)} {step === 2 && ( updateForm('institution', e.target.value)} error={errors.institution} isValid={formData.institution.length > 2} icon={Building2} placeholder="Oxford Academy" autoFocus /> updateForm('password', e.target.value)} error={errors.password} isValid={pwdStrengthCount === 3} icon={Lock} placeholder="••••••••" /> {/* Password Strength Meter */} {formData.password.length > 0 && (
{[1, 2, 3].map((s) => (
= s ? pwdStrengthColor : "bg-slate-200 dark:bg-slate-700")} /> ))}
Strength: {pwdStrengthLabel}
8+ Characters
1 Number
1 Special Ch.
)} updateForm('confirmPassword', e.target.value)} error={errors.confirmPassword} isValid={formData.password === formData.confirmPassword && formData.confirmPassword.length > 0} icon={Lock} placeholder="••••••••" />
)} {step === 3 && (

I identify mostly as a...

{roles.map(role => (
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" )} >
{role.label} {formData.role === role.id && ( )}
))}
{isLoading ? ( ) : isSuccess ? ( ) : ( Create Account )}
)}
{/* Switch to Login */}

Already have an account?{' '}

); };