'use client' import React, { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Play, Lock, Shield, AlertTriangle, Users, Trophy, Clock, Code, Zap, Sparkles, Star, Brain, CheckCircle, XCircle } 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 || {} })) 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 () => { setIsExecuting(true) 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') } finally { setIsExecuting(false) } } 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 with Enhanced Animations if (userRole === 'selector') { return (
{/* Animated Background Elements */}
{/* Floating particles */}
{/* Floating sparkles */}
{/* Card shine effect */}

OpenLearnX Coding Exam

Choose your role to get started

{/* Animated footer */}

Secure • Real-time • Professional

) } // Host Setup Screen with Enhanced UI if (userRole === 'host' && !examId) { return (
{/* Enhanced background animations */}
{/* Floating icons */}
{/* Enhanced shine effect */}
{/* Floating particles around icon */}

Host Coding Exam

Create a secure coding environment for your participants

setParticipantName(e.target.value)} className="w-full p-4 border-2 border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 rounded-xl text-lg text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 transition-all duration-300 focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-800 focus:border-blue-500 dark:focus:border-blue-400 hover:border-blue-300 dark:hover:border-blue-500 hover:bg-white dark:hover:bg-gray-600 focus:bg-white dark:focus:bg-gray-700 group" /> {/* Input decoration */}
{/* Enhanced Debug Info */}
System Status

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 with Enhanced Animations if (userRole === 'participant' && !examInfo) { return (
{/* Enhanced background effects */}
{/* Animated particles */}
{/* Enhanced card effects */}
{/* Animated ring around icon */}

Join Coding Exam

Enter the exam code to participate in the coding challenge

setExamId(e.target.value.toUpperCase())} className="w-full p-4 border-2 border-gray-200 dark:border-gray-600 rounded-xl text-center font-mono text-2xl tracking-widest uppercase text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 transition-all duration-300 focus:ring-4 focus:ring-green-200 dark:focus:ring-green-800 focus:border-green-500 dark:focus:border-green-400 hover:border-green-300 dark:hover:border-green-500 bg-gray-50 dark:bg-gray-700 hover:bg-white dark:hover:bg-gray-600 focus:bg-white dark:focus:bg-gray-700 relative group" maxLength={6} /> {/* Input decorations */}
{examId.length === 6 && (
)}
setParticipantName(e.target.value)} className="w-full p-4 border-2 border-gray-200 dark:border-gray-600 rounded-xl text-lg text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 transition-all duration-300 focus:ring-4 focus:ring-green-200 dark:focus:ring-green-800 focus:border-green-500 dark:focus:border-green-400 hover:border-green-300 dark:hover:border-green-500 bg-gray-50 dark:bg-gray-700 hover:bg-white dark:hover:bg-gray-600 focus:bg-white dark:focus:bg-gray-700 group" /> {/* Name validation indicator */} {participantName.length > 2 && (
)}
{/* Enhanced Debug Info */}
Connection Status

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

After join → redirect to /coding/exam

) } // Enhanced System Requirements Check if (!systemChecked) { return (
{/* Animated warning elements */}
{/* Floating warning icons */}
{/* Security-themed background */}
{/* Security rings */}

System Requirements Check

Preparing secure exam environment

Fullscreen mode support

Required for secure examination

Copy/paste will be disabled

Prevents unauthorized assistance

Virtual environments will be detected

Ensures exam integrity

{/* Security notice */}
Security Notice

This exam uses advanced security measures. Browser restrictions will be enforced during the examination period.

) } // Enhanced Main Exam Interface return (
{/* Animated background elements */}
{/* Enhanced Security Status Bar */}
{/* Security bar background animation */}
SECURE MODE ACTIVE
Copy/Paste Disabled
VM Detection Active
{timeRemaining > 0 && (
{formatTime(timeRemaining)} {timeRemaining < 300 && ( // Last 5 minutes warning
)}
)}
Exam: {examId}
{/* Enhanced Main Coding Area */}
{/* Problem Description with Enhanced Styling */}
{/* Card background animation */}

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"`}
                
{/* Hover shine effect */}
{/* Enhanced Code Editor */}
{/* Editor background animation */}

Code Editor

{/* Editor status indicators */}
Ready
Lines: {code.split('\n').length} | Chars: {code.length}