Study/src/app/(protected)/[classSlug]/quizzes/[quizId]/page.tsx

246 lines
8.2 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback } from "react";
import { useParams, useRouter } from "next/navigation";
import { QuizViewer } from "@/components/quizzes/QuizViewer";
import { AttemptHistory } from "@/components/quizzes/AttemptHistory";
import { ShareMenu } from "@/components/ui/ShareMenu";
interface Option {
id: string;
text: string;
isCorrect: boolean;
}
interface Question {
id: string;
type: string;
prompt: string;
rationale: string;
category: string;
options: Option[];
}
interface QuizAttempt {
id: string;
score: number;
maxScore: number;
answersJson: string;
reviewSnapshotJson?: string | null;
isPartialRetake: boolean;
completedAt: string;
}
interface QuizData {
id: string;
name: string;
description: string | null;
questions: Question[];
class: { slug: string; name: string };
progress: Array<{
mode: string;
currentIndex: number;
orderJson: string;
answersJson: string | null;
sessionId: string;
revision: number;
}>;
}
export default function QuizStudyPage() {
const params = useParams();
const router = useRouter();
const classSlug = params.classSlug as string;
const quizId = params.quizId as string;
const [quiz, setQuiz] = useState<QuizData | null>(null);
const [attempts, setAttempts] = useState<QuizAttempt[]>([]);
const [loading, setLoading] = useState(true);
const [view, setView] = useState<"history" | "take">("take");
const [retakeIds, setRetakeIds] = useState<string[] | null>(null);
const [restartKey, setRestartKey] = useState(0);
async function handleRestart() {
if (!quiz) return;
const progress = quiz.progress.find((item) => item.mode === "SEQUENTIAL");
if (progress) {
const response = await fetch("/api/progress", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contentType: "QUIZ",
contentId: quiz.id,
mode: "SEQUENTIAL",
sessionId: progress.sessionId,
}),
}).catch(() => null);
if (!response?.ok) {
window.alert("The quiz could not be restarted. Your saved progress was kept.");
return;
}
}
// Clear locally and force remount
setQuiz({ ...quiz, progress: [] });
setRetakeIds(null);
setRestartKey(prev => prev + 1);
setView("take");
}
const fetchQuizAndAttempts = useCallback(async () => {
try {
const [quizRes, attemptsRes] = await Promise.all([
fetch(`/api/quizzes/${quizId}`),
fetch(`/api/quizzes/${quizId}/attempt`)
]);
if (!quizRes.ok) throw new Error("Not found");
const [quizData, attemptsData] = await Promise.all([
quizRes.json(),
attemptsRes.ok ? attemptsRes.json() : []
]);
setQuiz(quizData);
setAttempts(attemptsData);
// Optional: keep track of attempt count, but default view is already "take"
if (attemptsData.length > 0) {
// We can do something here if we wanted to auto-switch to history, but user wants take
}
} catch {
router.push(`/${classSlug}/quizzes`);
} finally {
setLoading(false);
}
}, [quizId, classSlug, router]);
useEffect(() => {
const timer = window.setTimeout(() => void fetchQuizAndAttempts(), 0);
return () => window.clearTimeout(timer);
}, [fetchQuizAndAttempts]);
const [showTopics, setShowTopics] = useState(false);
const categories = quiz
? Array.from(new Set(quiz.questions.map(q => q.category.toUpperCase()))).join(" · ")
: "";
if (loading || !quiz) {
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="animate-subtle-pulse">
<div className="h-8 bg-bg-surface-alt rounded w-1/3 mb-4" />
<div className="h-64 bg-bg-surface rounded-xl border border-border-light" />
</div>
</div>
);
}
return (
<div className="mx-auto w-full max-w-5xl py-1 md:py-3">
{/* Header */}
<div className="mb-7 flex flex-col items-start justify-between gap-4 rounded-2xl border border-border-light bg-bg-surface/70 p-4 shadow-[var(--shadow-card)] sm:p-5 md:flex-row">
<div>
<button
onClick={() => router.push(`/${classSlug}/quizzes`)}
className="inline-flex items-center gap-1 text-sm text-text-muted hover:text-text-heading mb-4 transition-colors cursor-pointer"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Back to quizzes
</button>
<button
onClick={() => setShowTopics(!showTopics)}
className="flex items-center gap-2 group cursor-pointer text-left focus:outline-none mb-2"
>
<h1 className="editorial-title text-3xl text-text-heading transition-colors group-hover:text-primary sm:text-4xl">
{quiz.name}
</h1>
<svg
className={`w-6 h-6 text-text-muted transition-transform duration-200 ${showTopics ? "rotate-180" : ""}`}
fill="none" viewBox="0 0 24 24" stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{showTopics && (
<div className="text-sm tracking-widest text-text-muted font-medium mb-3 animate-in fade-in slide-in-from-top-2 duration-200 leading-relaxed">
{categories}
</div>
)}
{quiz.description && (
<p className="text-sm text-text-secondary mt-1">{quiz.description}</p>
)}
</div>
{/* View toggle & Share */}
<div className="flex items-center gap-2 md:gap-4 self-end md:self-auto md:mt-10">
{view === "take" && (
<button
onClick={handleRestart}
className="p-1.5 rounded-lg text-text-muted hover:text-text-heading hover:bg-bg-surface-alt transition-all duration-200 cursor-pointer"
title="Restart Quiz"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
)}
<ShareMenu targetType="QUIZ" contentId={quiz.id} classSlug={classSlug} />
{attempts.length > 0 && (
<div className="flex rounded-xl border border-border-light bg-bg-surface-alt p-1">
<button
onClick={() => setView("history")}
className={`px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 cursor-pointer ${
view === "history"
? "bg-bg-surface text-text-heading shadow-sm"
: "text-text-muted hover:text-text-heading"
}`}
>
History
</button>
<button
onClick={() => setView("take")}
className={`px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 cursor-pointer ${
view === "take"
? "bg-bg-surface text-text-heading shadow-sm"
: "text-text-muted hover:text-text-heading"
}`}
>
Take Quiz
</button>
</div>
)}
</div>
</div>
{/* Content */}
{view === "history" && attempts.length > 0 ? (
<AttemptHistory
quiz={quiz}
attempts={attempts}
onRetake={(missedIds) => {
setRetakeIds(missedIds);
setView("take");
}}
/>
) : (
<QuizViewer
key={restartKey}
quiz={quiz}
retakeIds={retakeIds}
sessionKey={restartKey}
onFinished={() => {
router.push(`/${classSlug}/quizzes`);
}}
/>
)}
</div>
);
}