'use client' import React, { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Trophy, Clock, Users, Send, RefreshCw, Play, Code, Wallet, Shield } from 'lucide-react' interface Participant { name: string score: number rank: number completed: boolean language?: string submission_time?: string wallet_address?: string wallet_short?: string blockchain_verified?: boolean } interface Problem { title: string description: string function_name: string languages: string[] examples: Array<{input: string, expected_output: string, description: string}> constraints: string[] starter_code: {[key: string]: string} } interface ExamSession { exam_code: string student_name: string wallet_address?: string blockchain_verified?: boolean exam_info: any } export default function EnhancedExamInterface() { const [examSession, setExamSession] = useState(null) const [problem, setProblem] = useState(null) const [selectedLanguage, setSelectedLanguage] = useState('python') const [code, setCode] = useState('') const [output, setOutput] = useState('') const [testResults, setTestResults] = useState([]) const [leaderboard, setLeaderboard] = useState([]) const [waitingParticipants, setWaitingParticipants] = useState([]) const [timeRemaining, setTimeRemaining] = useState(0) const [isRunning, setIsRunning] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false) const [hasSubmitted, setHasSubmitted] = useState(false) const [examStats, setExamStats] = useState({}) const router = useRouter() const languageIcons: {[key: string]: string} = { python: 'šŸ', java: 'ā˜•', c: '⚔', bash: 'šŸ’»' } useEffect(() => { const sessionData = localStorage.getItem('exam_session') if (!sessionData) { router.push('/coding/join') return } const session = JSON.parse(sessionData) setExamSession(session) // Fetch problem details fetchProblem(session.exam_code) // Start polling for updates const interval = setInterval(() => { fetchLeaderboard(session.exam_code) }, 3000) return () => clearInterval(interval) }, [router]) const fetchProblem = async (examCode: string) => { try { const response = await fetch(`http://127.0.0.1:5000/api/exam/get-problem/${examCode}`) const data = await response.json() if (data.success) { setProblem(data.problem) const defaultLang = data.problem.languages[0] || 'python' setSelectedLanguage(defaultLang) setCode(data.problem.starter_code[defaultLang] || '') } } catch (error) { console.error('Failed to fetch problem:', error) } } const fetchLeaderboard = async (examCode: string) => { try { const response = await fetch(`http://127.0.0.1:5000/api/exam/leaderboard/${examCode}`) const data = await response.json() if (data.success) { setLeaderboard(data.leaderboard || []) setWaitingParticipants(data.waiting_participants || []) setExamStats(data.stats || {}) if (data.exam_info.status === 'active' && data.exam_info.end_time) { const endTime = new Date(data.exam_info.end_time) const now = new Date() const remaining = Math.max(0, Math.floor((endTime.getTime() - now.getTime()) / 1000)) setTimeRemaining(remaining) } } } catch (error) { console.error('Failed to fetch leaderboard:', error) } } const handleLanguageChange = (language: string) => { setSelectedLanguage(language) if (problem?.starter_code[language]) { setCode(problem.starter_code[language]) } setOutput('') setTestResults([]) } const runCode = async () => { if (!code.trim()) { alert('Please write some code first!') return } setIsRunning(true) setOutput('') setTestResults([]) try { const response = await fetch('http://127.0.0.1:5000/api/exam/execute-code', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, language: selectedLanguage }) }) const result = await response.json() if (result.success) { setOutput('Code executed successfully!') setTestResults(result.test_results || []) } else { setOutput(`Error: ${result.error}`) } } catch (error) { setOutput(`Execution failed: ${(error as Error).message}`) } finally { setIsRunning(false) } } const submitSolution = async () => { if (!code.trim()) { alert('Please write some code before submitting!') return } setIsSubmitting(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, language: selectedLanguage }) }) const data = await response.json() if (data.success) { setHasSubmitted(true) setTestResults(data.test_results || []) let alertMessage = `Solution submitted successfully!\nScore: ${data.score}%\nPassed: ${data.passed_tests}/${data.total_tests} tests` if (data.blockchain_verified) { alertMessage += `\nšŸ”— Blockchain Verified: ${data.wallet_address?.slice(0, 6)}...${data.wallet_address?.slice(-4)}` } alert(alertMessage) fetchLeaderboard(examSession!.exam_code) } else { alert(data.error || 'Failed to submit solution') } } catch (error) { alert('Failed to submit solution. Please try again.') } finally { setIsSubmitting(false) } } 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')}` } const getRankColor = (rank: number) => { switch (rank) { case 1: return 'bg-gradient-to-r from-yellow-400 to-yellow-600 text-white' case 2: return 'bg-gradient-to-r from-gray-300 to-gray-500 text-white' case 3: return 'bg-gradient-to-r from-orange-400 to-orange-600 text-white' default: return 'bg-gray-100 text-gray-700' } } if (!examSession || !problem) { return (

Loading exam interface...

) } return (
{/* Header with Timer */}

{problem.title}

Code: {examSession.exam_code}

{/* Timer */} {timeRemaining > 0 && (
{formatTime(timeRemaining)}
)} {/* Wallet Info Display */} {examSession.blockchain_verified && examSession.wallet_address && (
{examSession.wallet_address.slice(0, 6)}...{examSession.wallet_address.slice(-4)}
)} {/* Participant Count */}
{examStats.total_participants || 0} participants {examStats.blockchain_participants > 0 && ( ({examStats.blockchain_participants} šŸ”—) )}
{/* Problem & Code Editor */}
{/* Problem Description */}

{problem.title}

{examSession.blockchain_verified && (
Blockchain Verified
)}

{problem.description}

Examples:

{problem.examples.map((example, index) => (
Input: "{example.input}"
Output: "{example.expected_output}"
{example.description && (
{example.description}
)}
))}

Constraints:

    {problem.constraints.map((constraint, index) => (
  • {constraint}
  • ))}
{/* Code Editor */}

Your Solution

{/* Language Selector */}