'use client' import React, { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Play, Lock, Shield, AlertTriangle, Users, Trophy, Clock } from 'lucide-react' type UserRole = 'selector' | 'host' | 'participant' type ExamStatus = 'waiting' | 'active' | 'completed' interface Participant { name: string score: number completed: boolean submitted_at?: string } export default function CodingExamPlatform() { const [userRole, setUserRole] = useState('selector') const [examId, setExamId] = useState('') const [participantName, setParticipantName] = useState('') const [examInfo, setExamInfo] = useState(null) const [systemChecked, setSystemChecked] = useState(false) const [isSecureMode, setIsSecureMode] = useState(false) const [leaderboard, setLeaderboard] = useState([]) const [timeRemaining, setTimeRemaining] = useState(0) // Coding states const [code, setCode] = useState('') const [output, setOutput] = useState('') const [isExecuting, setIsExecuting] = useState(false) const router = useRouter() // System Requirements Check const checkSystemRequirements = () => { const checks = { fullscreenSupported: document.fullscreenEnabled, webGLSupported: !!document.createElement('canvas').getContext('webgl'), localStorageSupported: typeof Storage !== 'undefined', cookiesEnabled: navigator.cookieEnabled } const allPassed = Object.values(checks).every(check => check) if (allPassed) { setSystemChecked(true) alert('System requirements check passed! ✅') } else { alert('System requirements not met. Please use a modern browser.') } return allPassed } const acceptSystemRequirements = () => { if (checkSystemRequirements()) { enableSecureMode() } } const enableSecureMode = () => { // Enter fullscreen document.documentElement.requestFullscreen().then(() => { setIsSecureMode(true) disableBrowserFeatures() detectVirtualEnvironment() // Start exam timer if in active exam if (examInfo?.status === 'active') { startExamTimer() } }).catch(() => { alert('Fullscreen mode is required for secure coding') }) } const disableBrowserFeatures = () => { // Disable right-click, copy/paste, dev tools const blockActions = (e: KeyboardEvent) => { if (e.ctrlKey && ['c', 'v', 'x', 'a'].includes(e.key)) { e.preventDefault() alert('Copy/paste is disabled in exam mode') } if (e.key === 'F12' || (e.ctrlKey && e.shiftKey && ['I', 'C'].includes(e.key))) { e.preventDefault() alert('Developer tools are disabled') } } document.addEventListener('keydown', blockActions) document.addEventListener('contextmenu', e => e.preventDefault()) document.addEventListener('selectstart', e => e.preventDefault()) } const detectVirtualEnvironment = () => { const canvas = document.createElement('canvas') const gl = canvas.getContext('webgl') if (gl) { const renderer = gl.getParameter(gl.RENDERER) if (renderer.includes('VMware') || renderer.includes('VirtualBox')) { alert('Virtual environment detected. Exam will be terminated.') window.location.href = '/' } } } // ✅ UPDATED CREATE EXAM WITH HOST PANEL REDIRECT const createExam = async () => { try { const response = await fetch('http://127.0.0.1:5000/api/exam/create-exam', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'String Capitalizer Challenge', problem_id: 'string-capitalizer', duration_minutes: 30, host_name: participantName, max_participants: 50 }) }) const data = await response.json() console.log('📦 Create exam response:', data) if (data.success) { // ✅ CORRECTED: Use exam_code, NOT exam_id const participantCode = data.exam_code // This is the 6-character code const databaseId = data.exam_id // This is the MongoDB ObjectId setExamId(participantCode) setExamInfo({ title: 'String Capitalizer Challenge', status: 'waiting' }) // Store host exam data localStorage.setItem('host_exam', JSON.stringify({ exam_code: participantCode, exam_id: databaseId, host_name: participantName, created_at: new Date().toISOString(), exam_details: data.exam_details || {} })) // ✅ ENHANCED SUCCESS MESSAGE WITH REDIRECT INFO alert(`✅ Exam Created Successfully! 📝 Exam Code: ${participantCode} 📋 Title: String Capitalizer Challenge 👤 Host: ${participantName} ⏱️ Duration: 30 minutes 🔗 Share this code with participants: ${participantCode} Redirecting to Host Management Panel...`) // ✅ REDIRECT TO HOST PANEL setTimeout(() => { router.push(`/coding/host/${participantCode}`) }, 2000) } else { alert(`❌ Failed to create exam: ${data.error}`) } } catch (error) { console.error('Create exam error:', error) alert('❌ Failed to create exam - network error') } } // ✅ CORRECTED JOIN FUNCTION WITH PROPER REDIRECT const joinExam = async () => { try { console.log('🚀 Joining with:', { exam_code: examId, student_name: participantName }) const response = await fetch('http://127.0.0.1:5000/api/exam/join-exam', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ exam_code: examId, // ✅ Correct field name student_name: participantName // ✅ Changed from 'name' to 'student_name' }) }) const data = await response.json() console.log('📦 Join response:', data) if (data.success) { setExamInfo(data.exam_info) // Store exam session data for the exam interface localStorage.setItem('exam_session', JSON.stringify({ exam_code: examId, student_name: participantName, exam_info: data.exam_info, joined_at: new Date().toISOString() })) alert(`✅ Successfully joined: ${data.exam_info.title}! 👤 Joined as: ${participantName} 📊 Participants: ${data.exam_info.participants_count}/${data.exam_info.max_participants} ⏱️ Duration: ${data.exam_info.duration_minutes} minutes Redirecting to exam interface...`) // ✅ REDIRECT TO EXAM INTERFACE setTimeout(() => { router.push('/coding/exam') }, 1500) } else { alert(`❌ Error: ${data.error}`) } } catch (error) { console.error('Join error:', error) alert('❌ Failed to join exam - network error') } } const startExam = async () => { try { const response = await fetch('http://127.0.0.1:5000/api/exam/start-exam', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ exam_code: examId }) }) const data = await response.json() if (data.success) { setExamInfo(prev => ({ ...prev, status: 'active' })) alert('Exam started! Participants can now begin coding.') startExamTimer() } } catch (error) { alert('Failed to start exam') } } const startExamTimer = () => { const duration = 30 * 60 // 30 minutes in seconds setTimeRemaining(duration) const timer = setInterval(() => { setTimeRemaining(prev => { if (prev <= 1) { clearInterval(timer) alert('Time is up!') return 0 } return prev - 1 }) }, 1000) } const submitSolution = async () => { try { const response = await fetch('http://127.0.0.1:5000/api/exam/submit-solution', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) }) const data = await response.json() if (data.success) { alert(`Solution submitted! Your score: ${data.score}%`) fetchLeaderboard() } } catch (error) { alert('Failed to submit solution') } } const fetchLeaderboard = async () => { try { const response = await fetch(`http://127.0.0.1:5000/api/exam/leaderboard/${examId}`) const data = await response.json() setLeaderboard(data.leaderboard) } catch (error) { console.error('Failed to fetch leaderboard') } } const formatTime = (seconds: number) => { const mins = Math.floor(seconds / 60) const secs = seconds % 60 return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}` } // Role Selection Screen if (userRole === 'selector') { return (

OpenLearnX Coding Exam

) } // Host Setup Screen if (userRole === 'host' && !examId) { return (

Host Coding Exam

setParticipantName(e.target.value)} className="w-full p-3 border border-gray-300 rounded-lg" />
{/* Debug Info */}

Will create with host_name: "{participantName}"

✅ Will display exam_code (6 chars), not exam_id

🔄 After creation → redirect to /coding/host/[examCode]

) } // Join Exam Screen if (userRole === 'participant' && !examInfo) { return (

Join Coding Exam

setExamId(e.target.value.toUpperCase())} className="w-full p-3 border border-gray-300 rounded-lg text-center font-mono text-lg tracking-widest uppercase" maxLength={6} /> setParticipantName(e.target.value)} className="w-full p-3 border border-gray-300 rounded-lg" /> {/* Debug Info */}

Will send: exam_code="{examId}" student_name="{participantName}"

✅ After join → redirect to /coding/exam

) } // System Requirements Check if (!systemChecked) { return (

System Requirements Check

Fullscreen mode support
Copy/paste will be disabled
Virtual environments will be detected
) } // Main Exam Interface return (
{/* Security Status Bar */}
SECURE MODE ACTIVE Copy/Paste Disabled
{timeRemaining > 0 && (
{formatTime(timeRemaining)}
)} Exam: {examId}
{/* Main Coding Area */}
{/* Problem Description */}

Problem: String Capitalizer

Write a function that converts a string to uppercase.

{`def capitalize_string(text): # Your code here pass # Test: capitalize_string("hello") should return "HELLO"`}
{/* Code Editor */}

Code Editor