import { useState, useEffect, useRef } from "react"; import { useParams, useNavigate } from "react-router-dom"; import "./RegisterPage.css"; interface RegistrationData { username: string; age: string; password: string; confirmPassword: string; } export function RegisterPage() { const { sessionId } = useParams<{ sessionId: string }>(); const navigate = useNavigate(); const [ws, setWs] = useState(null); const [connected, setConnected] = useState(false); const [sessionValid, setSessionValid] = useState(null); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); const [formData, setFormData] = useState({ username: "", age: "", password: "", confirmPassword: "", }); const [errors, setErrors] = useState>({}); const [successMessage, setSuccessMessage] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const wsRef = useRef(null); useEffect(() => { if (!sessionId) { setSessionValid(false); setLoading(false); return; } const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; const wsUrl = `${protocol}//${window.location.host}/ws`; const websocket = new WebSocket(wsUrl); wsRef.current = websocket; websocket.onopen = () => { console.log("[WebSocket] Connected"); setConnected(true); websocket.send(JSON.stringify({ type: "user_connect", sessionId: sessionId, })); }; websocket.onmessage = (event) => { try { const message = JSON.parse(event.data); handleWebSocketMessage(message); } catch (error) { console.error("[WebSocket] Error parsing message:", error); } }; websocket.onerror = (error) => { console.error("[WebSocket] Error:", error); setErrorMessage("Connection error. Please try again."); setLoading(false); }; websocket.onclose = () => { console.log("[WebSocket] Disconnected"); setConnected(false); }; setWs(websocket); return () => { websocket.close(); }; }, [sessionId]); const handleWebSocketMessage = (message: any) => { switch (message.type) { case "connected": console.log("[WebSocket]", message.message); break; case "session_valid": setSessionValid(true); setLoading(false); break; case "session_invalid": setSessionValid(false); setLoading(false); setErrorMessage(message.message || "Session not found or expired"); break; case "registration_result": setSubmitting(false); if (message.success) { setSuccessMessage(message.message); setErrorMessage(""); setTimeout(() => { window.close(); }, 3000); } else { setErrorMessage(message.message); setSuccessMessage(""); } break; } }; const validateForm = (): boolean => { const newErrors: Partial = {}; if (!formData.username.trim()) { newErrors.username = "Username is required"; } else if (formData.username.trim().length < 3) { newErrors.username = "Username must be at least 3 characters"; } const ageNum = parseInt(formData.age); if (!formData.age) { newErrors.age = "Age is required"; } else if (isNaN(ageNum) || ageNum < 13 || ageNum > 100) { newErrors.age = "Age must be between 13 and 100"; } if (!formData.password) { newErrors.password = "Password is required"; } else if (formData.password.length < 6 || formData.password.length > 20) { newErrors.password = "Password must be 6-20 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 = (e: React.FormEvent) => { e.preventDefault(); if (!validateForm()) return; if (!ws || ws.readyState !== WebSocket.OPEN) { setErrorMessage("Connection lost. Please refresh the page."); return; } setSubmitting(true); setErrorMessage(""); setSuccessMessage(""); const submitData = { username: formData.username.trim(), age: parseInt(formData.age), password: formData.password, confirmPassword: formData.confirmPassword, }; ws.send(JSON.stringify({ type: "registration_submit", sessionId: sessionId, data: submitData, })); }; const handleInputChange = (field: keyof RegistrationData, value: string) => { setFormData(prev => ({ ...prev, [field]: value })); if (errors[field]) { setErrors(prev => ({ ...prev, [field]: "" })); } }; if (loading) { return (

Validating session...

); } if (sessionValid === false) { return (

Invalid Session

{errorMessage || "This registration link is invalid or has expired."}

); } if (successMessage) { return (

Registration Successful!

{successMessage}

Your account has been activated automatically.

); } return (

🎉 Account Registration

Join Yuki Botz and unlock amazing features!

{!connected && (
Reconnecting...
)}
handleInputChange("username", e.target.value)} placeholder="Enter your username" className={errors.username ? "error" : ""} disabled={submitting} /> {errors.username && {errors.username}}
handleInputChange("age", e.target.value)} placeholder="Enter your age" className={errors.age ? "error" : ""} disabled={submitting} min="13" max="100" /> {errors.age && {errors.age}}

🔑 Password

🎁 Get bonus rewards with your account!
💎 +100 Limit
🪙 +10,000 Money
⭐ +50 EXP
🎮 RPG Access
handleInputChange("password", e.target.value)} placeholder="6-20 characters" className={errors.password ? "error" : ""} disabled={submitting} /> {errors.password && {errors.password}}
handleInputChange("confirmPassword", e.target.value)} placeholder="Re-enter password" className={errors.confirmPassword ? "error" : ""} disabled={submitting} /> {errors.confirmPassword && {errors.confirmPassword}}
{errorMessage && (
⚠️ {errorMessage}
)}
); }