feat(ui): add modal functionality, leaderboard view

This commit is contained in:
shafin-r
2025-07-10 19:28:50 +06:00
parent 64fc4d9a9a
commit 71eeafdaee
9 changed files with 358 additions and 83 deletions

View File

@ -0,0 +1,102 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import { API_URL, getToken } from "@/lib/auth";
import React, { useEffect, useState } from "react";
const page = () => {
const [boardError, setBoardError] = useState<string | null>(null);
const [boardData, setBoardData] = useState([]);
const [userData, setUserData] = useState(null);
const [loading, setLoading] = useState(true);
async function fetchBoardData() {
try {
const boardResponse = await fetch(`${API_URL}/leaderboard`, {
method: "GET",
});
if (!boardResponse.ok) {
throw new Error("Failed to fetch leaderboard data");
}
const fetchedBoardData = await boardResponse.json();
if (Array.isArray(fetchedBoardData) && fetchedBoardData.length > 0) {
setBoardData(fetchedBoardData);
} else {
setBoardError("No leaderboard data available.");
setBoardData([]);
}
} catch (error) {
console.error(error);
setBoardError("Something went wrong. Please try again.");
setBoardData([]);
}
}
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) throw new Error("User is not authenticated");
const response = await fetch(`${API_URL}/me`, {
method: "get",
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) throw new Error("Failed to fetch user data");
const fetchedUserData = await response.json();
setLoading(false);
setUserData(fetchedUserData);
} catch (error) {
console.error(error);
setUserData(null);
}
}
fetchUser();
fetchBoardData();
}, []);
const getTopThree = (boardData) => {
if (!boardData || !Array.isArray(boardData)) return [];
const sortedData = boardData
.filter((player) => player?.points !== undefined) // Ensure `points` exists
.sort((a, b) => b.points - a.points);
const topThree = sortedData.slice(0, 3).map((player, index) => ({
...player,
rank: index + 1,
height: index === 0 ? 280 : index === 1 ? 250 : 220,
}));
return [topThree[1], topThree[0], topThree[2]].filter(Boolean); // Handle missing players
};
const getLeaderboard = (boardData) => {
return boardData.slice().sort((a, b) => b.points - a.points);
};
const getUserData = (boardData, name) => {
if (!boardData || !Array.isArray(boardData)) return [];
const sortedData = boardData
.filter((player) => player?.name && player?.points !== undefined)
.sort((a, b) => b.points - a.points);
const result = sortedData.find((player) => player.name === name);
return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
};
return (
<BackgroundWrapper>
<section>
<Header displaySubject={"Leaderboard"} displayTabTitle={null} />
</section>
</BackgroundWrapper>
);
};
export default page;

View File

@ -1,11 +1,14 @@
"use client";
import React, { useEffect, useState, useCallback } from "react";
import React, { useEffect, useState, useCallback, useMemo } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useTimer } from "@/context/TimerContext";
import { useExam } from "@/context/ExamContext";
import { API_URL, getToken } from "@/lib/auth";
import Header from "@/components/Header";
import { Bookmark, BookmarkCheck } from "lucide-react";
import { useModal } from "@/context/ModalContext";
import Modal from "@/components/ExamModal";
// Types
interface Question {
@ -21,33 +24,47 @@ interface QuestionItemProps {
}
const QuestionItem = React.memo<QuestionItemProps>(
({ question, selectedAnswer, handleSelect }) => (
<div className="border border-[#8abdff]/50 rounded-2xl p-4">
<h3 className="text-xl font-medium mb-[20px]">
{question.id}. {question.question}
</h3>
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options).map(([key, value]) => (
<button
key={key}
className="flex items-center gap-3"
onClick={() => handleSelect(question.id, key)}
>
<span
className={`flex items-center rounded-full border px-1.5 ${
selectedAnswer === key
? "text-white bg-[#113768] border-[#113768]"
: ""
}`}
>
{key.toUpperCase()}
</span>
<span className="option-description">{value}</span>
({ question, selectedAnswer, handleSelect }) => {
const [bookmark, setBookmark] = useState(false);
return (
<div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
<h3 className="text-xl font-medium mb-[20px]">
{question.id}. {question.question}
</h3>
<div className="flex justify-between items-center">
<div></div>
<button onClick={() => setBookmark(!bookmark)}>
{bookmark ? (
<BookmarkCheck size={25} color="#113768" />
) : (
<Bookmark size={25} color="#113768" />
)}
</button>
))}
</div>
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options).map(([key, value]) => (
<button
key={key}
className="flex items-center gap-3"
onClick={() => handleSelect(question.id, key)}
>
<span
className={`flex items-center rounded-full border px-1.5 ${
selectedAnswer === key
? "text-white bg-[#113768] border-[#113768]"
: ""
}`}
>
{key.toUpperCase()}
</span>
<span className="option-description">{value}</span>
</button>
))}
</div>
</div>
</div>
)
);
}
);
QuestionItem.displayName = "QuestionItem";
@ -56,6 +73,7 @@ export default function ExamPage() {
const router = useRouter();
const { id } = useParams();
const time = useSearchParams().get("time");
const { isOpen, close } = useModal();
const { setInitialTime, stopTimer } = useTimer();
const {
@ -76,17 +94,6 @@ export default function ExamPage() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [submissionLoading, setSubmissionLoading] = useState(false);
useEffect(() => {
console.log(
"hydrated:",
isHydrated,
"initialized:",
isInitialized,
"exam:",
currentExam
);
}, [isHydrated, isInitialized, currentExam]);
// Initial checks
useEffect(() => {
if (!isHydrated || !isInitialized || isSubmitting) return;
@ -203,6 +210,11 @@ export default function ExamPage() {
);
}
const answeredSet = useMemo(() => {
if (!currentAttempt) return new Set<string>();
return new Set(currentAttempt.answers.map((a) => String(a.questionId)));
}, [currentAttempt]);
return (
<div className="min-h-screen bg-gray-50">
<Header
@ -212,7 +224,54 @@ export default function ExamPage() {
displayUser={undefined}
displaySubject={undefined}
/>
<div className="container mx-auto px-4 py-8">
<Modal open={isOpen} onClose={close} title={currentExam?.title}>
{currentAttempt ? (
<div>
<div className="flex gap-4">
<p className="">Questions: {currentExam?.questions.length}</p>
<p className="">
Answers:{" "}
<span className="text-[#113768] font-bold">
{currentAttempt?.answers.length}
</span>
</p>
<p className="">
Skipped:{" "}
<span className="text-yellow-600 font-bold">
{currentExam?.questions.length -
currentAttempt?.answers.length}
</span>
</p>
{/* more details */}
</div>
<div className="h-[0.5px] border-[0.5px] border-black/10 w-full my-3"></div>
<section className="flex flex-wrap gap-4">
{currentExam?.questions.map((q, idx) => {
const answered = answeredSet.has(String(q.id)); // ← convert to string
return (
<div
key={q.id ?? idx}
className={`h-16 w-16 rounded-full flex items-center justify-center
text-2xl
${
answered
? "bg-[#0E2C53] text-white font-semibold"
: "bg-[#E9EDF1] text-black font-normal"
}`}
>
{idx + 1}
</div>
);
})}
</section>
</div>
) : (
<p>No attempt data.</p>
)}
</Modal>
<div className="container mx-auto px-6 py-8">
{loading ? (
<div className="flex items-center justify-center min-h-64">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900"></div>
@ -231,15 +290,13 @@ export default function ExamPage() {
)}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
<div className="container mx-auto">
<button
onClick={handleSubmit}
disabled={submissionLoading}
className="w-full bg-blue-900 text-white py-4 px-6 rounded-lg font-bold text-lg hover:bg-blue-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Submit
</button>
</div>
<button
onClick={handleSubmit}
disabled={submissionLoading}
className="w-full bg-blue-900 text-white py-4 px-6 rounded-lg font-bold text-lg hover:bg-blue-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Submit
</button>
</div>
</div>
</div>

View File

@ -31,18 +31,18 @@ const QuestionItem = ({ question, selectedAnswer }: QuestionItemProps) => (
<div className="flex justify-between items-center">
<div></div>
{selectedAnswer?.answer === question.correctAnswer ? (
{!selectedAnswer ? (
<Badge className="bg-yellow-500" variant="destructive">
Skipped
</Badge>
) : selectedAnswer.answer === question.correctAnswer ? (
<Badge className="bg-green-500 text-white" variant="default">
Correct
</Badge>
) : selectedAnswer?.answer !== question.correctAnswer ? (
) : (
<Badge className="bg-red-500 text-white" variant="default">
Incorrect
</Badge>
) : (
<Badge className="bg-yellow-500" variant="destructive">
Skipped
</Badge>
)}
</div>
@ -74,7 +74,7 @@ const QuestionItem = ({ question, selectedAnswer }: QuestionItemProps) => (
);
})}
</div>
<div className="h-[0.5px] border-[0.5px] border-dashed border-black/20"></div>
<div className="flex flex-col gap-2">
<h3 className="text-lg font-bold text-black/40">Solution:</h3>
<p className="text-lg">{question.solution}</p>
@ -96,6 +96,7 @@ export default function ResultsPage() {
try {
examResults = useExamResults();
console.log(examResults);
} catch (error) {
// Handle case where there's no completed exam
return (
@ -221,12 +222,16 @@ export default function ResultsPage() {
return (
<div className="min-h-screen bg-white">
<button className="p-10" onClick={() => router.push("/unit")}>
<button className="p-10" onClick={() => handleBackToHome()}>
<ArrowLeft size={30} color="black" />
</button>
<div className="bg-white rounded-lg shadow-lg px-10 pb-20">
<h1 className="text-2xl font-bold text-gray-900 mb-4 text-center">
Keep up the good work!
<h1 className="text-2xl font-bold text-[#113768] mb-4 text-center">
{examResults?.score < 30
? "Try harder!"
: examResults?.score < 70
? "Getting Better"
: "You did great!"}
</h1>
{/* Score Display */}
@ -246,16 +251,6 @@ export default function ResultsPage() {
/>
))}
</div>
<div className="flex gap-4 items-center mb-6 text-sm text-gray-600">
<div className="flex items-center gap-2">
<div className="w-4 h-4 bg-green-600 rounded-full"></div>{" "}
Correct
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-4 bg-red-600 rounded-full"></div> Your
Answer (Incorrect)
</div>
</div>
</div>
)}

View File

@ -3,12 +3,15 @@
import { ExamProvider } from "@/context/ExamContext";
import { TimerProvider } from "@/context/TimerContext";
import { AuthProvider } from "@/context/AuthContext";
import { ModalProvider } from "@/context/ModalContext";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<TimerProvider>
<AuthProvider>
<ExamProvider>{children}</ExamProvider>
<ExamProvider>
<ModalProvider>{children}</ModalProvider>
</ExamProvider>
</AuthProvider>
</TimerProvider>
);