"use client"; import React, { useEffect, useState } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import Header from "@/components/Header"; import QuestionItem from "@/components/QuestionItem"; import BackgroundWrapper from "@/components/BackgroundWrapper"; import { useExamStore } from "@/stores/examStore"; import { useTimerStore } from "@/stores/timerStore"; export default function ExamPage() { const router = useRouter(); const searchParams = useSearchParams(); const test_id = searchParams.get("test_id") || ""; const type = searchParams.get("type") || ""; const { setStatus, test, answers, startExam, setAnswer, submitExam } = useExamStore(); const { resetTimer, stopTimer } = useTimerStore(); const [isSubmitting, setIsSubmitting] = useState(false); // Start exam + timer automatically useEffect(() => { if (!type || !test_id) return; const initExam = async () => { const fetchedTest = await startExam(type, test_id); if (!fetchedTest) return; setStatus("in-progress"); const timeLimit = fetchedTest.metadata.time_limit_minutes; if (timeLimit) { resetTimer(timeLimit * 60, async () => { // Auto-submit when timer ends stopTimer(); setStatus("finished"); await submitExam(type); router.replace("/exam/results"); }); } }; initExam(); }, [ type, test_id, startExam, resetTimer, stopTimer, submitExam, router, setStatus, ]); if (isSubmitting) { return (

Submitting exam...

); } if (!test) { return (

Loading exam...

); } const handleSubmitExam = async (type: string) => { setIsSubmitting(true); stopTimer(); try { const result = await submitExam(type); // throws if fails if (!result) throw new Error("Submission failed"); router.replace("/exam/results"); // navigate } catch (err) { console.error("Submit exam failed:", err); alert("Failed to submit exam. Please try again."); } finally { setIsSubmitting(false); } }; return (
{/* Header with live timer */}
{/* Questions */}
{test.questions.map((q, idx) => (
setAnswer(idx, answer)} />
))} {/* Bottom submit bar */}
); }