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 (
Start generating intelligent question papers today.
I identify mostly as a...
Already have an account?{' '}