'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' export default function JoinExam() { const [examCode, setExamCode] = useState('') const [studentName, setStudentName] = useState('') const [loading, setLoading] = useState(false) const [error, setError] = useState('') const router = useRouter() const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() // ✅ Prevent form from reloading page setError('') if (!examCode.trim()) { setError('Please enter the exam code') return } if (!studentName.trim()) { setError('Please enter your name') return } setLoading(true) try { const token = localStorage.getItem("openlearnx_jwt_token") const storedUserRaw = localStorage.getItem("openlearnx_user") const storedUser = storedUserRaw ? JSON.parse(storedUserRaw) : null // ✅ CORRECT FIELD NAMES - Must match backend expectations const payload = { exam_code: examCode.trim().toUpperCase(), // Backend expects exam_code student_name: studentName.trim(), // Backend expects student_name wallet_address: storedUser?.wallet_address, user_id: storedUser?.id } console.log('🚀 Sending payload:', payload) const response = await fetch('http://127.0.0.1:5000/api/exam/join-exam', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(payload) // ✅ MUST stringify the payload }) console.log('📡 Response status:', response.status) const data = await response.json() console.log('📦 Response data:', data) if (data.success) { // Store session data localStorage.setItem('exam_session', JSON.stringify({ exam_code: examCode.toUpperCase(), student_name: studentName, exam_info: data.exam_info, joined_at: new Date().toISOString() })) alert(`✅ Successfully joined: ${data.exam_info.title} 👤 Joined as: ${studentName} 📊 You are participant #${data.exam_info.participants_count} Wait for the host to start the exam!`) // Redirect to exam interface router.push('/coding/exam') } else { setError(data.error || 'Failed to join exam') } } catch (error) { console.error('❌ Error:', error) setError('Network error: Could not connect to backend server') } finally { setLoading(false) } } return (

Join Coding Exam

Enter the exam code provided by your instructor

{/* Form with proper onSubmit handler */}
setExamCode(e.target.value.toUpperCase())} placeholder="Enter 6-character code" maxLength={6} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-center text-lg font-mono tracking-widest uppercase" required />
setStudentName(e.target.value)} placeholder="Enter your full name" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required />
{/* Error Display */} {error && (
❌ {error}
)} {/* Debug Info */}

Debug Info:

Code: "{examCode}"

Name: "{studentName}"

✅ Sends: exam_code + student_name

) }