'use client'; import { useState, useEffect, FormEvent, type ChangeEvent } from 'react'; import { useRouter, useSearchParams } from 'next/navigation'; import Link from 'next/link'; import { Mail, Lock, Eye, EyeOff, UserPlus, AlertCircle, Flag, User, Check, X, Gamepad2, Loader2, } from 'lucide-react'; import Card from '@/components/ui/Card'; import Button from '@/components/ui/Button'; import Input from '@/components/ui/Input'; import Heading from '@/components/ui/Heading'; import { useAuth } from '@/lib/auth/AuthContext'; interface FormErrors { displayName?: string; email?: string; password?: string; confirmPassword?: string; submit?: string; } interface PasswordStrength { score: number; label: string; color: string; } function checkPasswordStrength(password: string): PasswordStrength { let score = 0; if (password.length >= 8) score++; if (password.length >= 12) score++; if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++; if (/\d/.test(password)) score++; if (/[^a-zA-Z\d]/.test(password)) score++; if (score <= 1) return { score, label: 'Weak', color: 'bg-red-500' }; if (score <= 2) return { score, label: 'Fair', color: 'bg-warning-amber' }; if (score <= 3) return { score, label: 'Good', color: 'bg-primary-blue' }; return { score, label: 'Strong', color: 'bg-performance-green' }; } export default function SignupPage() { const router = useRouter(); const searchParams = useSearchParams(); const { refreshSession } = useAuth(); const returnTo = searchParams.get('returnTo') ?? '/onboarding'; const [loading, setLoading] = useState(false); const [checkingAuth, setCheckingAuth] = useState(true); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); const [errors, setErrors] = useState({}); const [formData, setFormData] = useState({ displayName: '', email: '', password: '', confirmPassword: '', }); // Check if already authenticated useEffect(() => { async function checkAuth() { try { const response = await fetch('/api/auth/session'); const data = await response.json(); if (data.authenticated) { // Already logged in, redirect to dashboard or return URL router.replace(returnTo === '/onboarding' ? '/dashboard' : returnTo); } } catch { // Not authenticated, continue showing signup page } finally { setCheckingAuth(false); } } checkAuth(); }, [router, returnTo]); const passwordStrength = checkPasswordStrength(formData.password); const passwordRequirements = [ { met: formData.password.length >= 8, label: 'At least 8 characters' }, { met: /[a-z]/.test(formData.password) && /[A-Z]/.test(formData.password), label: 'Upper and lowercase letters' }, { met: /\d/.test(formData.password), label: 'At least one number' }, { met: /[^a-zA-Z\d]/.test(formData.password), label: 'At least one special character' }, ]; const validateForm = (): boolean => { const newErrors: FormErrors = {}; if (!formData.displayName.trim()) { newErrors.displayName = 'Display name is required'; } else if (formData.displayName.trim().length < 3) { newErrors.displayName = 'Display name must be at least 3 characters'; } if (!formData.email.trim()) { newErrors.email = 'Email is required'; } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) { newErrors.email = 'Invalid email format'; } if (!formData.password) { newErrors.password = 'Password is required'; } else if (formData.password.length < 8) { newErrors.password = 'Password must be at least 8 characters'; } if (!formData.confirmPassword) { newErrors.confirmPassword = 'Please confirm your password'; } else if (formData.password !== formData.confirmPassword) { newErrors.confirmPassword = 'Passwords do not match'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); if (loading) return; if (!validateForm()) return; setLoading(true); setErrors({}); try { const response = await fetch('/api/auth/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: formData.email, password: formData.password, displayName: formData.displayName, }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Signup failed'); } // Refresh session in context so header updates immediately await refreshSession(); router.push(returnTo); } catch (error) { setErrors({ submit: error instanceof Error ? error.message : 'Signup failed. Please try again.', }); setLoading(false); } }; const handleDemoLogin = async () => { setLoading(true); try { // Redirect to iRacing auth start route router.push(`/auth/iracing/start?returnTo=${encodeURIComponent(returnTo)}`); } catch { setErrors({ submit: 'Demo login failed. Please try again.', }); setLoading(false); } }; // Show loading while checking auth if (checkingAuth) { return (
); } return (
{/* Background Pattern */}
{/* Logo/Header */}
Join GridPilot

Create your account and start racing

{/* Background accent */}
{/* Display Name */}
) => setFormData({ ...formData, displayName: e.target.value })} error={!!errors.displayName} errorMessage={errors.displayName} placeholder="SpeedyRacer42" disabled={loading} className="pl-10" autoComplete="username" />

This is how other drivers will see you

{/* Email */}
) => setFormData({ ...formData, email: e.target.value })} error={!!errors.email} errorMessage={errors.email} placeholder="you@example.com" disabled={loading} className="pl-10" autoComplete="email" />
{/* Password */}
) => setFormData({ ...formData, password: e.target.value })} error={!!errors.password} errorMessage={errors.password} placeholder="••••••••" disabled={loading} className="pl-10 pr-10" autoComplete="new-password" />
{/* Password Strength */} {formData.password && (
{passwordStrength.label}
{passwordRequirements.map((req, index) => (
{req.met ? ( ) : ( )} {req.label}
))}
)}
{/* Confirm Password */}
) => setFormData({ ...formData, confirmPassword: e.target.value })} error={!!errors.confirmPassword} errorMessage={errors.confirmPassword} placeholder="••••••••" disabled={loading} className="pl-10 pr-10" autoComplete="new-password" />
{formData.confirmPassword && formData.password === formData.confirmPassword && (

Passwords match

)}
{/* Error Message */} {errors.submit && (

{errors.submit}

)} {/* Submit Button */} {/* Divider */}
or continue with
{/* Demo Login */} {/* Login Link */}

Already have an account?{' '} Sign in

{/* Footer */}

By creating an account, you agree to our{' '} Terms of Service {' '}and{' '} Privacy Policy

); }