17 Commits
main ... master

Author SHA1 Message Date
e091a78bdb fix(ts): fix interfaces for type safety 2025-07-27 13:41:02 +06:00
3ef526ec1a chore: refactor code for type safety 2025-07-27 03:19:25 +06:00
0ea199c0fe fix(ui): fix question item answer indexing in results page 2025-07-25 19:09:06 +06:00
d57aa9b073 fix(exam): fix startexam function (not finding examdata) 2025-07-22 22:08:42 +06:00
341a46e788 fix(ui): fix results screen 2025-07-22 17:59:15 +06:00
5245ab878d fix(func): fix issues in results page 2025-07-16 22:28:26 +06:00
32c9065f6f fix(ui): fix profile screen 2025-07-16 16:25:26 +06:00
aa7bc67dc9 feat(screens): implement bookmark and profile screens 2025-07-15 21:20:26 +06:00
71eeafdaee feat(ui): add modal functionality, leaderboard view 2025-07-10 19:28:50 +06:00
64fc4d9a9a feat(ui): add avatar and badge components 2025-07-10 14:51:45 +06:00
d42a42a8d1 fix(exam): fix pretest screen start exam button 2025-07-07 21:01:11 +06:00
22eb8285ec fix(ui): fix exam and result screen ui 2025-07-07 17:52:01 +06:00
48519c42c3 fix(ui): fix exam screen layout, bottom navigation tabs 2025-07-07 13:57:04 +06:00
06418a82ab added exam routes 2025-07-05 19:05:47 +06:00
576398883d fixed sliding gallery, fixed styling 2025-07-04 02:49:17 +06:00
17ebe63dfd Merge branch 'main' of https://git.omukk.dev/shafin808s/examjam-frontend 2025-07-03 01:54:56 +06:00
913ec11bc7 initial commit 2025-07-03 01:50:10 +06:00
64 changed files with 5222 additions and 2290 deletions

109
app/(auth)/login/page.tsx Normal file
View File

@ -0,0 +1,109 @@
"use client";
import React, { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Image from "next/image";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import FormField from "@/components/FormField";
import { login } from "@/lib/auth";
import DestructibleAlert from "@/components/DestructibleAlert";
import { useAuth } from "@/context/AuthContext";
const page = () => {
const router = useRouter();
const { setToken } = useAuth();
const [form, setForm] = useState({
email: "",
password: "",
});
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
// For Rafeed
// Function to login a user. I've kept it in a barebones form right now, but you can just call the login function from /lib/auth.ts and pass on the form.
const loginUser = async () => {
try {
setIsLoading(true);
setError(null);
await login(form, setToken); // Call the login function
router.push("/home"); // Redirect on successful login
} catch (error) {
console.log(error);
setError(error.message); // Handle error messages
} finally {
setIsLoading(false);
}
};
return (
<BackgroundWrapper>
<div className="flex-1 min-h-screen">
<div className="min-h-screen overflow-y-auto">
<div className="min-h-full flex flex-col justify-center gap-10 mt-7 mx-6 py-8">
{/* Logo Container */}
<div
className="w-full self-center mt-7"
style={{ aspectRatio: "368/89" }}
>
<Image
src="/images/logo/logo.png"
alt="Logo"
width={368}
height={89}
className="w-full h-full object-contain"
priority
/>
</div>
{/* Form Container */}
<div className="flex flex-col justify-between gap-10">
<div className="flex flex-col w-full gap-5">
<FormField
title="Email Address"
value={form.email}
placeholder="Enter your email address..."
handleChangeText={(e) => setForm({ ...form, email: e })}
/>
<FormField
title="Password"
value={form.password}
placeholder="Enter a password"
handleChangeText={(e) => setForm({ ...form, password: e })}
/>
</div>
{error && <DestructibleAlert text={error} extraStyles="" />}
<button
onClick={loginUser}
disabled={isLoading}
className="w-full h-14 flex justify-center items-center border border-[#113768] rounded-full bg-transparent hover:bg-[#113768] hover:text-white transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
>
<span
className="font-medium"
style={{ fontFamily: "Montserrat, sans-serif" }}
>
{isLoading ? "Logging in..." : "Login"}
</span>
</button>
</div>
{/* Register Link */}
<p
className="text-center mb-[70px]"
style={{ fontFamily: "Montserrat, sans-serif" }}
>
Don't have an account?{" "}
<Link href="/register" className="text-[#276ac0] hover:underline">
Register here.
</Link>
</p>
</div>
</div>
</div>
</BackgroundWrapper>
);
};
export default page;

View File

@ -0,0 +1,161 @@
"use client";
import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { register } from "@/lib/auth";
import { useAuth } from "@/context/AuthContext";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import FormField from "@/components/FormField";
import DestructibleAlert from "@/components/DestructibleAlert";
export default function RegisterPage() {
const { setToken } = useAuth();
const router = useRouter();
const [form, setForm] = useState({
name: "",
institution: "",
sscRoll: "",
hscRoll: "",
email: "",
phone: "",
password: "",
});
const [error, setError] = useState<string | null>(null);
const handleError = (error: any) => {
if (error?.detail) {
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
if (match) {
const field = match[1];
const value = match[2];
return `The ${field} already exists. Please use a different value.`;
}
}
return "An unexpected error occurred. Please try again.";
};
const validateForm = () => {
const { sscRoll, hscRoll, password } = form;
if (sscRoll === hscRoll) {
return "SSC Roll and HSC Roll must be unique.";
}
const passwordRegex =
/^(?=.*[A-Z])(?=.*[!@#$%^&*(),.?":{}|<>])[A-Za-z\d!@#$%^&*(),.?":{}|<>]{8,16}$/;
if (!passwordRegex.test(password)) {
return "Password must be 8-16 characters long, include at least one uppercase letter and one special character.";
}
return null;
};
const createUser = async () => {
const validationError = validateForm();
if (validationError) {
setError(validationError);
return;
}
try {
await register(form, setToken);
router.push("/home");
} catch (error: any) {
console.error("Error:", error.response || error.message);
if (error.response?.detail) {
const decodedError = handleError({ detail: error.response.detail });
setError(decodedError);
} else {
setError(error.message || "An unexpected error occurred.");
}
}
};
return (
<BackgroundWrapper>
<div className="min-h-screen flex flex-col items-center justify-center px-4 py-10">
<div className="w-full max-w-md space-y-6">
<div className="w-full aspect-[368/89] mx-auto">
<Image
src="/images/logo/logo.png"
alt="Logo"
width={368}
height={89}
className="w-full h-auto"
/>
</div>
<div className="space-y-10">
<div className="space-y-6">
<FormField
title="Full name"
value={form.name}
handleChangeText={(value) => setForm({ ...form, name: value })}
/>
<FormField
title="Institution"
value={form.institution}
handleChangeText={(value) =>
setForm({ ...form, institution: value })
}
/>
<FormField
title="SSC Roll No."
value={form.sscRoll}
handleChangeText={(value) =>
setForm({ ...form, sscRoll: value })
}
/>
<FormField
title="HSC Roll No."
value={form.hscRoll}
handleChangeText={(value) =>
setForm({ ...form, hscRoll: value })
}
/>
<FormField
title="Email Address"
value={form.email}
handleChangeText={(value) => setForm({ ...form, email: value })}
/>
<FormField
title="Phone Number"
value={form.phone}
handleChangeText={(value) => setForm({ ...form, phone: value })}
/>
<FormField
title="Password"
value={form.password}
handleChangeText={(value) =>
setForm({ ...form, password: value })
}
placeholder={undefined}
/>
</div>
{error && <DestructibleAlert text={error} />}
<button
onClick={createUser}
className="w-full h-14 rounded-full border border-blue-900 text-center text-base font-medium"
>
Get started
</button>
<p className="text-center text-sm">
Already have an account?{" "}
<Link href="/login" className="text-blue-600">
Login here
</Link>
</p>
</div>
</div>
</div>
</BackgroundWrapper>
);
}

View File

@ -0,0 +1,87 @@
"use client";
import React, { useState, useEffect } from "react";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { Bookmark, BookmarkCheck, ListFilter, MoveLeft } from "lucide-react";
import { useRouter } from "next/navigation";
interface Question {
id: number;
question: string;
options: Record<string, string>;
}
interface QuestionItemProps {
question: Question;
}
const QuestionItem = ({ question }: QuestionItemProps) => {
const [bookmark, setBookmark] = useState(true);
return (
<div className="border border-[#8abdff]/50 rounded-2xl p-4 flex flex-col gap-7">
<h3 className="text-xl font-medium">
{question.id + 1}. {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]) => {
return (
<div key={key} className="flex items-center gap-3">
<span className="px-2 py-1 flex items-center rounded-full border font-medium text-sm">
{key.toUpperCase()}
</span>
<span className="option-description">{value}</span>
</div>
);
})}
</div>
</div>
);
};
const BookmarkPage = () => {
const router = useRouter();
const [questions, setQuestions] = useState();
useEffect(() => {
fetch("/data/bookmark.json")
.then((res) => res.json())
.then((data) => setQuestions(data))
.catch((err) => console.error("Error loading questions: ", err));
}, []);
return (
<BackgroundWrapper>
<section className="min-h-screen flex flex-col justify-between">
<div className="flex-1 mb-20">
<div className="mx-8 mt-10 pb-6 space-y-6">
<button onClick={() => router.push("/home")}>
<MoveLeft size={30} color="#113768" />
</button>
<h1 className="text-4xl font-semibold text-[#113768]">Bookmark</h1>
<div className="flex justify-between">
<h3 className="text-xl font-semibold text-[#113768]">Recent</h3>
<button>
<ListFilter size={24} color="#113768" />
</button>
</div>
{questions?.map((question) => (
<QuestionItem key={question.id} question={question} />
))}
</div>
</div>
</section>
</BackgroundWrapper>
);
};
export default BookmarkPage;

View File

@ -0,0 +1,7 @@
import React from "react";
const page = () => {
return <div>page</div>;
};
export default page;

235
app/(tabs)/home/page.tsx Normal file
View File

@ -0,0 +1,235 @@
"use client";
import React, { useState, useEffect, ReactNode } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import Header from "@/components/Header";
import SlidingGallery from "@/components/SlidingGallery";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import DestructibleAlert from "@/components/DestructibleAlert";
import { ChevronRight } from "lucide-react";
import styles from "@/css/Home.module.css";
import { API_URL } from "@/lib/auth";
import { Avatar } from "@/components/ui/avatar";
import { getLinkedViews } from "@/lib/gallery-views";
import { getTopThree } from "@/lib/leaderboard";
interface LinkedView {
id: string;
content: ReactNode;
}
const page = () => {
const router = useRouter();
const [boardData, setBoardData] = useState([]);
const [boardError, setBoardError] = useState(null);
const [linkedViews, setLinkedViews] = useState<LinkedView[]>();
const performanceData = [
{ label: "Mock Test", progress: 20 },
{ label: "Topic Test", progress: 70 },
{ label: "Subject Test", progress: 50 },
];
const progressData = [
{ label: "Physics", progress: 25 },
{ label: "Chemistry", progress: 57 },
];
useEffect(() => {
let isMounted = true;
async function fetchBoardData() {
try {
const response = await fetch(`${API_URL}/leaderboard`);
if (!response.ok) {
throw new Error("Failed to fetch leaderboard data");
}
const data = await response.json();
if (isMounted) setBoardData(data);
} catch (error) {
if (isMounted) setBoardError(error.message || "An error occurred");
}
}
const fetchedLinkedViews = getLinkedViews();
setLinkedViews(fetchedLinkedViews);
fetchBoardData();
return () => {
isMounted = false;
};
}, []);
return (
<BackgroundWrapper>
<div className={styles.container}>
<Header displayUser />
<div className={styles.scrollContainer}>
<div className={styles.contentWrapper}>
<SlidingGallery views={linkedViews} height="23vh" />
<div className={styles.mainContent}>
{/* Categories Section */}
<div>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionTitle}>Categories</h2>
<button
onClick={() => router.push("/categories")}
className={styles.arrowButton}
>
<ChevronRight size={24} color="#113768" />
</button>
</div>
<div className={styles.categoriesContainer}>
<div className={styles.categoryRow}>
<button
disabled
className={`${styles.categoryButton} ${styles.disabled}`}
>
<Image
src="/images/icons/topic-test.png"
alt="Topic Test"
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
Topic Test
</span>
</button>
<button
onClick={() => router.push("/unit")}
className={styles.categoryButton}
>
<Image
src="/images/icons/mock-test.png"
alt="Mock Test"
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
Mock Test
</span>
</button>
</div>
<div className={styles.categoryRow}>
<button
disabled
className={`${styles.categoryButton} ${styles.disabled}`}
>
<Image
src="/images/icons/past-paper.png"
alt="Past Papers"
width={68}
height={68}
/>
<span className={styles.categoryButtonText}>
Past Papers
</span>
</button>
<button
disabled
className={`${styles.categoryButton} ${styles.disabled}`}
>
<Image
src="/images/icons/subject-test.png"
alt="Subject Test"
width={80}
height={80}
/>
<span className={styles.categoryButtonText}>
Subject Test
</span>
</button>
</div>
</div>
</div>
{/* Leaderboard Section */}
<div className={styles.leaderboardWrapper}>
<h2 className={styles.sectionTitle}>Leaderboard</h2>
<div className={styles.leaderboardContainer}>
<div className={styles.topThreeHeader}>
<span className={styles.topThreeTitle}>Top 3</span>
<button
onClick={() => router.push("/leaderboard")}
className={styles.arrowButton}
>
<ChevronRight size={24} color="#113768" />
</button>
</div>
<div className={styles.divider}></div>
<div className={styles.topThreeList}>
{getTopThree(boardData).map((student, idx) => (
<div key={idx} className={styles.topThreeItem}>
<div className={styles.studentInfo}>
<span className={styles.rank}>{student.rank}</span>
<Avatar className="bg-slate-300 w-4 h-4 rounded-full"></Avatar>
<span className={styles.studentName}>
{student.name}
</span>
</div>
<span className={styles.points}>
{student.points}pt
</span>
</div>
))}
</div>
</div>
</div>
{/* Performance Summary Section */}
<div className={styles.section}>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionTitle}>Performance Summary</h2>
<button
disabled
onClick={() => router.push("/performance")}
className={styles.arrowButton}
>
<ChevronRight size={24} color="#113768" />
</button>
</div>
<div className={styles.comingSoonCard}>
<p className={styles.comingSoonText}>Coming soon.</p>
</div>
</div>
{/* Progress Tracker Section */}
<div className={styles.section}>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionTitle}>Progress Tracker</h2>
<button
disabled
onClick={() => router.push("/progress")}
className={styles.arrowButton}
>
<ChevronRight size={24} color="#113768" />
</button>
</div>
<div className={styles.comingSoonCard}>
<p className={styles.comingSoonText}>Coming soon.</p>
</div>
</div>
{/* Daily Quiz Section */}
<div className={styles.section}>
<h2 className={styles.sectionTitle}>Daily Quiz</h2>
<div className={styles.comingSoonCard}>
<p className={styles.comingSoonText}>Coming soon.</p>
</div>
</div>
{/* Live Exams Section */}
<div className={`${styles.section} ${styles.lastSection}`}>
<h2 className={styles.sectionTitle}>Live Exams</h2>
<div className={styles.comingSoonCard}>
<p className={styles.comingSoonText}>Coming soon.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</BackgroundWrapper>
);
};
export default page;

40
app/(tabs)/layout.tsx Normal file
View File

@ -0,0 +1,40 @@
// app/tabs/layout.tsx
"use client";
import Link from "next/link";
import { ReactNode } from "react";
import { usePathname } from "next/navigation";
import clsx from "clsx";
import { House, LayoutGrid, Bookmark, Settings } from "lucide-react";
const tabs = [
{ name: "Home", href: "/home", component: <House size={30} /> },
{ name: "Unit", href: "/unit", component: <LayoutGrid size={30} /> },
{ name: "Bookmark", href: "/bookmark", component: <Bookmark size={30} /> },
{ name: "Settings", href: "/settings", component: <Settings size={30} /> },
];
export default function TabsLayout({ children }: { children: ReactNode }) {
const pathname = usePathname();
return (
<div className="min-h-screen flex flex-col">
<main className="flex-1">{children}</main>
<nav className="h-[70px] w-full flex justify-around items-center border-t border-t-neutral-400 p-4 rounded-t-4xl bg-white fixed bottom-0">
{tabs.map((tab) => (
<Link
key={tab.name}
href={tab.href}
className={clsx(
"text-center text-sm font-medium",
pathname === tab.href ? "text-blue-600" : "text-gray-500"
)}
>
{tab.component}
</Link>
))}
</nav>
</div>
);
}

View File

@ -0,0 +1,187 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { API_URL, getToken } from "@/lib/auth";
import { BoardData, getLeaderboard } from "@/lib/leaderboard";
import { UserData } from "@/types/auth";
import React, { useEffect, useState } from "react";
const LeaderboardPage = () => {
const [boardError, setBoardError] = useState<string | null>(null);
const [boardData, setBoardData] = useState<BoardData[]>([]);
const [userData, setUserData] = useState<UserData>({
name: "",
institution: "",
sscRoll: "",
hscRoll: "",
email: "",
phone: "",
});
const [loading, setLoading] = useState(true);
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(undefined);
}
}
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([]);
}
}
fetchUser();
fetchBoardData();
}, []);
const getTopThree = (boardData: 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 getUserData = (boardData: BoardData[], name: string) => {
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 displayTabTitle={"Leaderboard"} />
<section className="flex flex-col mx-10 pt-10 space-y-4">
<section className="flex justify-evenly items-end">
{getTopThree(boardData).map((student, idx) =>
student ? (
<div
key={idx}
className="w-[100px] flex flex-col bg-[#113768] rounded-t-xl items-center justify-start pt-4 space-y-3"
style={{ height: student.height }}
>
<h3 className="font-bold text-xl text-white">
{student.rank}
</h3>
<Avatar className="bg-slate-300 w-12 h-12">
<AvatarFallback className="text-xl font-semibold">
{student.name.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<p className="font-bold text-md text-center text-white">
{student.name}
</p>
<p className="text-sm text-white">({student.points}pt)</p>
</div>
) : null
)}
</section>
<div className="w-full border-[0.5px] border-[#c5dbf8] bg-[#c5dbf8]"></div>
<section className="border-[1px] border-[#c0dafc] w-full rounded-3xl p-6 space-y-4 mb-20">
<section>
{getUserData(boardData, userData.name).map((user, idx) => (
<div
key={idx}
className="flex bg-[#113768] rounded-[8] py-2 px-4 justify-between items-center"
>
<div className=" flex gap-3 items-center">
<h2 className="font-medium text-sm text-white">
{user.rank}
</h2>
<Avatar className="bg-slate-300 w-6 h-6">
<AvatarFallback className="text-sm font-semibold">
{user.name.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<h3 className="font-medium text-sm text-white">You</h3>
</div>
<p className="font-medium text-white/70 text-sm">
{user.points}pt
</p>
</div>
))}
</section>
<div className="w-full border-[0.5px] border-[#c5dbf8] bg-[#c5dbf8]"></div>
<section className="space-y-4">
{getLeaderboard(boardData)
.slice(0, 10)
.map((user, idx) => (
<div
key={idx}
className="flex border-2 border-[#c5dbf8] rounded-[8] py-2 px-4 justify-between items-center"
>
<div className="flex gap-3 items-center">
<h2 className="font-medium text-sm">{idx + 1}</h2>
<Avatar className="bg-slate-300 w-6 h-6">
<AvatarFallback className="text-sm font-semibold">
{user.name.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<h3 className="font-medium text-sm">
{user.name.split(" ").slice(0, 2).join(" ")}
</h3>
</div>
<p className="font-medium text-[#000]/40 text-sm">
{user.points}pt
</p>
</div>
))}
</section>
</section>
</section>
</section>
</BackgroundWrapper>
);
};
export default LeaderboardPage;

0
app/(tabs)/live/page.tsx Normal file
View File

126
app/(tabs)/paper/page.tsx Normal file
View File

@ -0,0 +1,126 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
interface Mock {
id: string;
title: string;
rating: number;
}
export default function PaperScreen() {
const router = useRouter();
const searchParams = useSearchParams();
const name = searchParams.get("name") || "";
const [questions, setQuestions] = useState<Mock[] | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
const [componentKey, setComponentKey] = useState<number>(0);
async function fetchMocks() {
try {
const questionResponse = await fetch(`${API_URL}/mocks`, {
method: "GET",
});
const fetchedQuestionData: Mock[] = await questionResponse.json();
setQuestions(fetchedQuestionData);
} catch (error) {
setErrorMsg(error instanceof Error ? error.message : "An error occurred");
}
}
useEffect(() => {
if (name) {
fetchMocks();
}
}, [name]);
const onRefresh = async () => {
setRefreshing(true);
await fetchMocks();
setComponentKey((prevKey) => prevKey + 1);
setTimeout(() => {
setRefreshing(false);
}, 1000);
};
if (errorMsg) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<Header displayTabTitle={name} />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<DestructibleAlert text={errorMsg} extraStyles="" />
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" /> */}
</div>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle={name} />
<div className="mx-10 pt-10 overflow-y-auto">
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4">
{questions ? (
questions.map((mock) => (
<div key={mock.id}>
<button
onClick={() =>
router.push(
`/exam/pretest?unitname=${name}&id=${mock.id}&title=${mock.title}&rating=${mock.rating}`
)
}
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 gap-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-xl font-medium">{mock.title}</h3>
<p className="text-md font-normal">
Rating: {mock.rating} / 10
</p>
</button>
</div>
))
) : (
<div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="p-2 bg-blue-500 text-white hover:bg-blue-600 disabled:opacity-50 rounded-full"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" useCustomHandler={false} /> */}
</BackgroundWrapper>
);
}

View File

@ -0,0 +1,7 @@
import React from "react";
const page = () => {
return <div>page</div>;
};
export default page;

122
app/(tabs)/profile/page.tsx Normal file
View File

@ -0,0 +1,122 @@
"use client";
import ProfileManager from "@/components/ProfileManager";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { getToken, API_URL } from "@/lib/auth";
import { ChevronLeft, Edit2, Lock, Save } from "lucide-react";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import { UserData } from "@/types/auth";
const ProfilePage = () => {
const router = useRouter();
const [userData, setUserData] = useState<UserData | undefined>();
const [editStatus, setEditStatus] = useState(false);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) return;
const response = await fetch(`${API_URL}/me`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const fetchedUserData = await response.json();
setUserData(fetchedUserData);
}
} catch (error) {
console.error("Error fetching user data: ", error);
}
}
fetchUser();
}, []);
const handleSave = async () => {
// try {
// const token = await getToken();
// if (!token || !userData) return;
// const response = await fetch(`${API_URL}/profile/edit`, {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// Authorization: `Bearer ${token}`,
// },
// body: JSON.stringify(userData),
// });
// if (response.ok) {
// setEditStatus(false);
// } else {
// console.error("Failed to save profile");
// }
// } catch (error) {
// console.error("Error saving profile:", error);
// }
console.log("Updated user data:", userData);
setEditStatus(false);
};
return (
<section className="min-h-screen mb-32">
<div className="h-48 bg-gradient-to-b from-[#113768] to-white w-full">
<button
onClick={() => router.push("/settings")}
className="absolute top-10 left-6 p-2 bg-black/30 rounded-full"
>
<ChevronLeft size={30} color="white" />
</button>
</div>
<div className="relative mx-10">
<Avatar className="bg-[#113768] w-32 h-32 absolute -top-20 left-1/2 transform -translate-x-1/2">
<AvatarFallback className="text-3xl text-white">
{userData?.name ? userData.name.charAt(0).toUpperCase() : ""}
</AvatarFallback>
</Avatar>
<div className="pt-14 space-y-8">
<ProfileManager
userData={userData}
edit={editStatus}
setUserData={setUserData}
/>
<button
onClick={() => {
if (editStatus) handleSave();
else setEditStatus(true);
}}
className={`p-3 ${
editStatus ? "bg-green-500" : "bg-[#113768]"
} w-full flex gap-3 justify-center items-center rounded-full`}
>
{editStatus ? (
<Save size={20} color="white" />
) : (
<Edit2 size={20} color="white" />
)}
<p className="text-white">
{editStatus ? "Save Changes" : "Edit Profile"}
</p>
</button>
<button className="p-3 bg-[#113768] w-full flex gap-3 justify-center items-center rounded-full">
<Lock size={20} color="white" />
<p className="text-white">Change Password</p>
</button>
</div>
</div>
</section>
);
};
export default ProfilePage;

View File

@ -0,0 +1,7 @@
import React from "react";
const page = () => {
return <div>page</div>;
};
export default page;

View File

@ -0,0 +1,189 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { API_URL, getToken } from "@/lib/auth";
import {
Bookmark,
ChartColumn,
ChevronRight,
Clock4,
CreditCard,
Crown,
Globe,
LogOut,
MapPin,
MoveLeft,
Trash2,
UserCircle2,
} from "lucide-react";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
const SettingsPage = () => {
const router = useRouter();
const [userData, setUserData] = useState(null);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) return;
const response = await fetch(`${API_URL}/me`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const fetchedUserData = await response.json();
setUserData(fetchedUserData);
}
} catch (error) {
console.error("Error fetching user data: ", error);
}
}
fetchUser();
}, []);
return (
<BackgroundWrapper>
<section className="min-h-screen flex flex-col justify-between">
<div className="flex-1 mb-20">
<div className="mx-8 mt-10 pb-6 space-y-6">
<section className="flex justify-between">
<button onClick={() => router.push("/home")}>
<MoveLeft size={30} color="#113768" />
</button>
<h3 className="text-lg font-semibold text-[#113768]">Settings</h3>
<button onClick={() => router.push("/profile")}>
<UserCircle2 size={30} color="#113768" />
</button>
</section>
<section className="flex flex-col gap-4">
<div className="flex gap-4 items-center">
<Avatar className="bg-[#113768] w-20 h-20">
<AvatarFallback className="text-3xl text-white">
{userData?.name
? userData.name.charAt(0).toUpperCase()
: ""}
</AvatarFallback>
</Avatar>
<div className="flex flex-col items-start">
<h1 className="font-semibold text-2xl">{userData?.name}</h1>
<h3 className=" text-md">{userData?.email}</h3>
</div>
</div>
</section>
<section className="flex flex-col gap-8">
<button
onClick={() => router.push("/profile")}
className="flex justify-between"
>
<div className="flex items-center gap-4">
<UserCircle2 size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Your profile
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</button>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Bookmark size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Bookmarks
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<CreditCard size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Payments
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Globe size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Languages
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<MapPin size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Location
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Crown size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Subscription
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<ChartColumn size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Performance
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Trash2 size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Clear Cache
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<Clock4 size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Clear History
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="flex justify-between">
<div className="flex items-center gap-4">
<LogOut size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Log out
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</div>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
<p className="text-center text-[#113768]/50 font-medium">
ExamJam | Version 1.0
</p>
</section>
</div>
</div>
</section>
</BackgroundWrapper>
);
};
export default SettingsPage;

63
app/(tabs)/unit/page.tsx Normal file
View File

@ -0,0 +1,63 @@
"use client";
import React from "react";
import { useRouter } from "next/navigation";
import Header from "@/components/Header";
import BackgroundWrapper from "@/components/BackgroundWrapper";
const units = [
{
id: 3,
name: "C Unit (Business Studies)",
rating: 9,
},
];
const Unit = () => {
const router = useRouter();
const handleUnitPress = (unit) => {
router.push(`/paper?name=${encodeURIComponent(unit.name)}`);
};
return (
<BackgroundWrapper>
<div className="flex flex-col min-h-screen">
<Header
displayExamInfo={null}
displayTabTitle={"Units"}
displaySubject={null}
displayUser={false}
title=""
image={""}
/>
<div className="flex-1">
<div className="overflow-y-auto">
<div className="border border-blue-200 gap-4 rounded-3xl p-4 mx-10 mt-10">
{units ? (
units.map((unit) => (
<button
key={unit.id}
onClick={() => handleUnitPress(unit)}
className="border-2 border-blue-300 py-4 rounded-xl px-6 gap-2 block w-full text-left hover:bg-blue-50 transition-colors duration-200"
>
<p className="text-lg font-medium">{unit.name}</p>
<p className="text-sm">Rating: {unit.rating} / 10</p>
</button>
))
) : (
<div className="flex flex-col items-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mb-4"></div>
<p className="font-bold text-2xl text-center">Loading...</p>
</div>
)}
</div>
</div>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="home" useCustomHandler={false} /> */}
</BackgroundWrapper>
);
};
export default Unit;

366
app/exam/[id]/page.tsx Normal file
View File

@ -0,0 +1,366 @@
"use client";
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";
import { Question } from "@/types/exam";
import QuestionItem from "@/components/QuestionItem";
// Types
// interface Question {
// id: number;
// question: string;
// options: Record<string, string>;
// }
// interface QuestionItemProps {
// question: Question;
// selectedAnswer?: string;
// handleSelect: (questionId: number, option: string) => void;
// }
// const QuestionItem = React.memo<QuestionItemProps>(
// ({ 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>
// );
// }
// );
// QuestionItem.displayName = "QuestionItem";
export default function ExamPage() {
// All hooks at the top - no conditional calls
const router = useRouter();
const { id } = useParams();
const time = useSearchParams().get("time");
const { isOpen, close } = useModal();
const { setInitialTime, stopTimer } = useTimer();
const {
currentAttempt,
setAnswer,
getAnswer,
submitExam: submitExamContext,
setApiResponse,
isExamStarted,
isExamCompleted,
isHydrated,
isInitialized,
currentExam,
} = useExam();
// State management
const [questions, setQuestions] = useState<Question[] | null>(null);
const [loading, setLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [submissionLoading, setSubmissionLoading] = useState(false);
const [componentState, setComponentState] = useState<
"loading" | "redirecting" | "ready"
>("loading");
// Combined initialization effect
useEffect(() => {
let mounted = true;
const initializeComponent = async () => {
// Wait for hydration and initialization
if (!isHydrated || !isInitialized || isSubmitting) {
return;
}
// Check exam state and handle redirects
if (!isExamStarted()) {
if (mounted) {
setComponentState("redirecting");
setTimeout(() => {
if (mounted) router.push("/unit");
}, 100);
}
return;
}
if (isExamCompleted()) {
if (mounted) {
setComponentState("redirecting");
setTimeout(() => {
if (mounted) router.push("/exam/results");
}, 100);
}
return;
}
// Component is ready to render
if (mounted) {
setComponentState("ready");
}
};
initializeComponent();
return () => {
mounted = false;
};
}, [
isHydrated,
isInitialized,
isExamStarted,
isExamCompleted,
isSubmitting,
router,
]);
// Fetch questions effect
useEffect(() => {
if (componentState !== "ready") return;
const fetchQuestions = async () => {
try {
const response = await fetch(`${API_URL}/mock/${id}`);
const data = await response.json();
setQuestions(data.questions);
} catch (error) {
console.error("Error fetching questions:", error);
} finally {
setLoading(false);
}
};
fetchQuestions();
if (time) setInitialTime(Number(time));
}, [id, time, setInitialTime, componentState]);
const handleSelect = useCallback(
(questionId: number, option: string) => {
setAnswer(questionId.toString(), option);
},
[setAnswer]
);
const handleSubmit = async () => {
if (!currentAttempt) return console.error("No exam attempt found");
stopTimer();
setSubmissionLoading(true);
setIsSubmitting(true);
const answersForAPI = currentAttempt.answers.reduce(
(acc, { questionId, answer }) => {
acc[+questionId] = answer;
return acc;
},
{} as Record<number, string>
);
try {
const response = await fetch(`${API_URL}/submit`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${await getToken()}`,
},
body: JSON.stringify({ mock_id: id, data: answersForAPI }),
});
if (!response.ok)
throw new Error((await response.json()).message || "Submission failed");
const responseData = await response.json();
submitExamContext();
setApiResponse(responseData);
router.push("/exam/results");
} catch (error) {
console.error("Error submitting answers:", error);
setIsSubmitting(false);
} finally {
setSubmissionLoading(false);
}
};
const showExitDialog = useCallback(() => {
if (window.confirm("Are you sure you want to quit the exam?")) {
stopTimer();
router.push("/unit");
}
}, [stopTimer, router]);
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = "";
};
const handlePopState = (e: PopStateEvent) => {
e.preventDefault();
showExitDialog();
};
window.addEventListener("beforeunload", handleBeforeUnload);
window.addEventListener("popstate", handlePopState);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
window.removeEventListener("popstate", handlePopState);
};
}, [showExitDialog]);
const answeredSet = useMemo(() => {
if (!currentAttempt) return new Set<string>();
return new Set(currentAttempt.answers.map((a) => String(a.questionId)));
}, [currentAttempt]);
// Show loading/redirecting state
if (componentState === "loading" || componentState === "redirecting") {
const loadingText =
componentState === "redirecting" ? "Redirecting..." : "Loading...";
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div>
<p className="text-lg font-medium text-gray-900">{loadingText}</p>
</div>
</div>
);
}
// Show submission loading
if (submissionLoading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div>
<p className="text-lg font-medium text-gray-900">Submitting...</p>
</div>
</div>
);
}
// Render the main exam interface
return (
<div className="min-h-screen bg-gray-50">
<Header
examDuration={time}
displayTabTitle={null}
image={undefined}
displayUser={undefined}
displaySubject={undefined}
/>
<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>
</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));
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>
</div>
) : (
<div className="space-y-6 mb-20">
{questions?.map((q) => (
<QuestionItem
key={q.id}
question={q}
selectedAnswer={getAnswer(q.id.toString())}
handleSelect={handleSelect}
mode="exam"
/>
))}
</div>
)}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
<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>
);
}

194
app/exam/pretest/page.tsx Normal file
View File

@ -0,0 +1,194 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { useExam } from "@/context/ExamContext";
import { Exam } from "@/types/exam";
interface Metadata {
metadata: {
quantity: number;
type: string;
duration: number;
marking: string;
};
}
export default function PretestPage() {
const router = useRouter();
const searchParams = useSearchParams();
const [examData, setExamData] = useState<Exam>();
const { startExam, setCurrentExam } = useExam();
// Get params from URL search params
const name = searchParams.get("name") || "";
const id = searchParams.get("id") || "";
const title = searchParams.get("title") || "";
const rating = searchParams.get("rating") || "";
const [metadata, setMetadata] = useState<Metadata | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
async function fetchQuestions() {
if (!id) return;
try {
setLoading(true);
const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
method: "GET",
});
if (!questionResponse.ok) {
throw new Error("Failed to fetch questions");
}
const data = await questionResponse.json();
const fetchedMetadata: Metadata = data;
setExamData(data);
setMetadata(fetchedMetadata);
} catch (error) {
console.error(error);
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setLoading(false);
}
}
useEffect(() => {
if (id) {
fetchQuestions();
}
}, [id]);
if (error) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<div className="mx-10 mt-10">
<button onClick={() => router.push("/unit")} className="mb-4">
<ArrowLeft size={30} color="black" />
</button>
<DestructibleAlert text={error} extraStyles="" />
</div>
{/* <CustomBackHandler fallbackRoute="paper" /> */}
</div>
</BackgroundWrapper>
);
}
function handleStartExam() {
setCurrentExam(examData);
startExam(examData); // Pass examData directly
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
}
return (
<BackgroundWrapper>
<div className="min-h-screen flex flex-col justify-between">
<div className="flex-1 overflow-y-auto mb-20">
{metadata ? (
<div className="mx-10 mt-10 gap-6 pb-6 space-y-6">
<button onClick={() => router.back()}>
<ArrowLeft size={30} color="black" />
</button>
<h1 className="text-4xl font-semibold text-[#113768]">{title}</h1>
<p className="text-xl font-medium text-[#113768]">
Rating: {rating} / 10
</p>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-8 py-7 px-5 space-y-8">
<div className="flex gap-5 items-center">
<HelpCircle size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.quantity}
</p>
<p className="font-normal text-lg">
{metadata.metadata.type}
</p>
</div>
</div>
<div className="flex gap-5 items-center">
<Clock size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.duration} mins
</p>
<p className="font-normal text-lg">Time Taken</p>
</div>
</div>
<div className="flex gap-5 items-center">
<XCircle size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.marking}
</p>
<p className="font-normal text-lg">
From each wrong answer
</p>
</div>
</div>
</div>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-4 py-7 px-5 space-y-4">
<h2 className="text-xl font-bold">Ready yourself!</h2>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
You must complete this test in one session - make sure your
internet connection is reliable.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
There is negative marking for the wrong answer.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
The more you answer correctly, the better chance you have of
winning a badge.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-normal text-lg">
You can retake this test however many times you want. But,
you will earn points only once.
</p>
</div>
</div>
</div>
) : (
<div className="mt-60 flex flex-col items-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<button
onClick={async () => handleStartExam()}
className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
>
Start Test
</button>
{/* <CustomBackHandler fallbackRoute="paper" /> */}
</div>
</BackgroundWrapper>
);
}

122
app/exam/results/page.tsx Normal file
View File

@ -0,0 +1,122 @@
"use client";
import { useRouter } from "next/navigation";
import { useExam, useExamResults } from "@/context/ExamContext";
import { useEffect, useState } from "react";
import React from "react";
import { ArrowLeft } from "lucide-react";
import SlidingGallery from "@/components/SlidingGallery";
import QuestionItem from "@/components/QuestionItem";
import { getResultViews } from "@/lib/gallery-views";
export default function ResultsPage() {
const router = useRouter();
const {
clearExam,
isExamCompleted,
getApiResponse,
currentAttempt,
isHydrated,
} = useExam();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Wait for hydration first
if (!isHydrated) return;
// Check if exam is completed, redirect if not
if (!isExamCompleted() || !currentAttempt) {
router.push("/unit");
return;
}
// If we have exam results, we're ready to render
if (currentAttempt?.answers) {
setIsLoading(false);
}
}, [isExamCompleted, currentAttempt, isHydrated, router]);
const handleBackToHome = () => {
clearExam();
router.push("/unit");
};
// Show loading screen while initializing or if no exam results
if (isLoading || !currentAttempt) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<div className="mt-60 flex flex-col items-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
</div>
</div>
);
}
const apiResponse = getApiResponse();
const timeTaken =
currentAttempt.endTime && currentAttempt.startTime
? Math.round(
(currentAttempt.endTime.getTime() -
currentAttempt.startTime.getTime()) /
1000 /
60
)
: 0;
const views = getResultViews(currentAttempt);
// Get score-based message
const getScoreMessage = () => {
if (!currentAttempt.score || currentAttempt.score < 30)
return "Try harder!";
if (currentAttempt.score < 70) return "Getting Better";
return "You did great!";
};
return (
<div className="min-h-screen bg-white">
<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-[#113768] mb-4 text-center">
{getScoreMessage()}
</h1>
{/* Score Display */}
<SlidingGallery className="my-8" views={views} height="170px" />
{apiResponse?.questions && (
<div className="mb-8">
<h3 className="text-2xl font-bold text-[#113768] mb-4">
Solutions
</h3>
<div className="flex flex-col gap-7">
{apiResponse.questions.map((question) => (
<QuestionItem
key={question.id}
question={question}
selectedAnswer={currentAttempt.answers[question.id - 1]}
mode="result"
/>
))}
</div>
</div>
)}
</div>
<button
onClick={handleBackToHome}
className="fixed bottom-0 w-full bg-blue-900 text-white h-[74px] font-bold text-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Finish
</button>
</div>
);
}

View File

@ -1,122 +1,5 @@
@import "tailwindcss"; @import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *)); @theme {
--font-sans: var(--font-montserrat), ui-sans-serif, system-ui, sans-serif;
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.129 0.042 264.695);
--card: oklch(1 0 0);
--card-foreground: oklch(0.129 0.042 264.695);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.129 0.042 264.695);
--primary: oklch(0.208 0.042 265.755);
--primary-foreground: oklch(0.984 0.003 247.858);
--secondary: oklch(0.968 0.007 247.896);
--secondary-foreground: oklch(0.208 0.042 265.755);
--muted: oklch(0.968 0.007 247.896);
--muted-foreground: oklch(0.554 0.046 257.417);
--accent: oklch(0.968 0.007 247.896);
--accent-foreground: oklch(0.208 0.042 265.755);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.929 0.013 255.508);
--input: oklch(0.929 0.013 255.508);
--ring: oklch(0.704 0.04 256.788);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.984 0.003 247.858);
--sidebar-foreground: oklch(0.129 0.042 264.695);
--sidebar-primary: oklch(0.208 0.042 265.755);
--sidebar-primary-foreground: oklch(0.984 0.003 247.858);
--sidebar-accent: oklch(0.968 0.007 247.896);
--sidebar-accent-foreground: oklch(0.208 0.042 265.755);
--sidebar-border: oklch(0.929 0.013 255.508);
--sidebar-ring: oklch(0.704 0.04 256.788);
}
.dark {
--background: oklch(0.129 0.042 264.695);
--foreground: oklch(0.984 0.003 247.858);
--card: oklch(0.208 0.042 265.755);
--card-foreground: oklch(0.984 0.003 247.858);
--popover: oklch(0.208 0.042 265.755);
--popover-foreground: oklch(0.984 0.003 247.858);
--primary: oklch(0.929 0.013 255.508);
--primary-foreground: oklch(0.208 0.042 265.755);
--secondary: oklch(0.279 0.041 260.031);
--secondary-foreground: oklch(0.984 0.003 247.858);
--muted: oklch(0.279 0.041 260.031);
--muted-foreground: oklch(0.704 0.04 256.788);
--accent: oklch(0.279 0.041 260.031);
--accent-foreground: oklch(0.984 0.003 247.858);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.551 0.027 264.364);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.208 0.042 265.755);
--sidebar-foreground: oklch(0.984 0.003 247.858);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.984 0.003 247.858);
--sidebar-accent: oklch(0.279 0.041 260.031);
--sidebar-accent-foreground: oklch(0.984 0.003 247.858);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.551 0.027 264.364);
}
@layer base {
* {
@apply border-border outline-ring/50;
} }
body {
@apply bg-background text-foreground;
}
}

View File

@ -1,20 +1,19 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Montserrat } from "next/font/google";
import "./globals.css"; import "./globals.css";
const geistSans = Geist({ import { Providers } from "./providers";
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({ const montserrat = Montserrat({
variable: "--font-geist-mono",
subsets: ["latin"], subsets: ["latin"],
weight: ["100", "200", "300", "400", "500", "600", "700", "800", "900"],
variable: "--font-montserrat",
display: "swap",
}); });
export const metadata: Metadata = { export const metadata: Metadata = {
title: "NextJS template", title: "ExamJam",
description: "With typescript, tailwindCSS and shadcnUI", description: "The best place to prepare for your exams!",
}; };
export default function RootLayout({ export default function RootLayout({
@ -23,11 +22,9 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
return ( return (
<html lang="en"> <html lang="en" className={montserrat.variable}>
<body <body className="font-sans">
className={`${geistSans.variable} ${geistMono.variable} antialiased`} <Providers>{children}</Providers>
>
{children}
</body> </body>
</html> </html>
); );

View File

@ -1,31 +1,66 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Image from "next/image"; import Image from "next/image";
import BackgroundWrapper from "@/components/BackgroundWrapper";
export default function Home() { export default function Home() {
const router = useRouter();
return ( return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> <BackgroundWrapper>
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start"> <div className="mx-10 h-screen">
<div className="h-full flex flex-col justify-around pt-10">
{/* Logo Container */}
<div className="w-full" style={{ aspectRatio: "368/89" }}>
<Image <Image
className="dark:invert" src="/images/logo/logo.png"
src="/next.svg" alt="Logo"
alt="Next.js logo" width={368}
width={180} height={89}
height={38} className="w-full h-full object-contain"
priority priority
/>{" "} />
template with typescript, tailwindCSS and shadcnUI
<ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold">
app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
</main>
</div> </div>
{/* Login Graphic */}
<div className="w-full h-1/2">
<Image
src="/images/static/login-graphic-1.png"
alt="Login illustration"
width={400}
height={300}
className="w-full h-full object-contain"
/>
</div>
{/* Action Buttons */}
<div className="flex flex-col gap-4">
<button
onClick={() => router.replace("/login")}
className="w-full h-[60px] flex justify-center items-center border border-[#113768] rounded-full bg-transparent hover:bg-[#113768] hover:text-white transition-colors duration-200"
>
<span
className="font-medium"
style={{ fontFamily: "Montserrat, sans-serif" }}
>
Login
</span>
</button>
<p
className="text-center font-medium"
style={{ fontFamily: "Montserrat, sans-serif" }}
>
Don't have an account?{" "}
<Link href="/register" className="text-[#276ac0] hover:underline">
Register here
</Link>
</p>
</div>
</div>
</div>
</BackgroundWrapper>
); );
} }

18
app/providers.tsx Normal file
View File

@ -0,0 +1,18 @@
"use client";
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>
<ModalProvider>{children}</ModalProvider>
</ExamProvider>
</AuthProvider>
</TimerProvider>
);
}

BIN
bun.lockb Normal file

Binary file not shown.

View File

@ -0,0 +1,23 @@
import React from "react";
const BackgroundWrapper = ({ children }) => {
return (
<div
className="min-h-screen bg-cover bg-center bg-no-repeat relative"
style={{
backgroundImage: "url('/images/static/paper-background.png')",
}}
>
<div
className="min-h-screen"
style={{
backgroundColor: "rgba(0, 0, 0, 0)", // Optional overlay - adjust opacity as needed
}}
>
{children}
</div>
</div>
);
};
export default BackgroundWrapper;

View File

@ -0,0 +1,38 @@
import React from "react";
const DestructibleAlert = ({
text,
extraStyles = "",
}: {
text: string;
extraStyles?: string;
}) => {
return (
<div
className={`border bg-red-200 border-blue-200 rounded-3xl py-6 ${extraStyles}`}
style={{
borderWidth: 1,
backgroundColor: "#fecaca",
borderColor: "#c0dafc",
paddingTop: 24,
paddingBottom: 24,
}}
>
<p
className="text-center text-red-800"
style={{
fontSize: 17,
lineHeight: "28px",
fontFamily: "Montserrat, sans-serif",
fontWeight: "bold",
textAlign: "center",
color: "#991b1b",
}}
>
{text}
</p>
</div>
);
};
export default DestructibleAlert;

91
components/ExamModal.tsx Normal file
View File

@ -0,0 +1,91 @@
"use client";
import { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
interface ModalProps {
/** Control visibility */
open: boolean;
/** Callback for both explicit and implicit close actions */
onClose: () => void;
/** Optional heading */
title?: string;
children: React.ReactNode;
/** Center horizontally and vertically? (default true) */
center?: boolean;
}
export default function Modal({
open,
onClose,
title,
children,
center = true,
}: ModalProps) {
const dialogRef = useRef<HTMLDialogElement | null>(null);
// Open / close imperatively to keep <dialog> in sync with prop
useEffect(() => {
const dialog = dialogRef.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
// Close on native <dialog> close event
useEffect(() => {
const dialog = dialogRef.current;
if (!dialog) return;
const handleClose = () => onClose();
dialog.addEventListener("close", handleClose);
return () => dialog.removeEventListener("close", handleClose);
}, [onClose]);
// ESC -> close (for browsers without builtin <dialog> handling)
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
if (typeof window === "undefined") return null; // SSR guard
return createPortal(
<dialog
ref={dialogRef}
className={`fixed top-0 right-0 h-[110vh] z-50 w-[87vw]
ml-auto transform-none /* 1 & 2 */
backdrop:bg-black/20
transition-[opacity,transform] duration-300
${
open
? "opacity-100 translate-x-0 translate-y-0"
: "opacity-0 translate-x-4"
}
${center ? "rounded-l-xl" : ""}
`}
>
{/* Card */}
<div className="bg-white rounded-xl overflow-hidden pb-10">
{title && (
<header className="flex items-center justify-between px-6 pt-10 pb-4 dark:border-zinc-700">
<h2 className="text-2xl font-semibold">{title}</h2>
<button
aria-label="Close"
onClick={onClose}
className="p-1 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full"
>
<X className="h-5 w-5" />
</button>
</header>
)}
<section className="px-6 ">{children}</section>
</div>
</dialog>,
document.body
);
}

80
components/FormField.tsx Normal file
View File

@ -0,0 +1,80 @@
import React, { useState } from "react";
const FormField = ({
title,
placeholder,
value,
handleChangeText,
...props
}) => {
const [showPassword, setShowPassword] = useState(false);
const isPasswordField = title === "Password" || title === "Confirm Password";
return (
<div className="w-full">
<label
className="block mb-2"
style={{
color: "#666666",
fontFamily: "Montserrat, sans-serif",
fontWeight: "500",
fontSize: 18,
marginBottom: 8,
letterSpacing: "-0.5px",
}}
>
{title}
</label>
<div
className="h-16 px-4 bg-blue-200 rounded-3xl flex items-center justify-between"
style={{
height: 64,
paddingLeft: 16,
paddingRight: 16,
backgroundColor: "#D2DFF0",
borderRadius: 20,
}}
>
<input
type={isPasswordField && !showPassword ? "password" : "text"}
value={value}
placeholder={placeholder}
onChange={(e) => handleChangeText(e.target.value)}
className="flex-1 bg-transparent outline-none border-none text-blue-950"
style={{
color: "#0D47A1",
fontSize: 16,
fontFamily: "inherit",
backgroundColor: "transparent",
border: "none",
outline: "none",
}}
{...props}
/>
{isPasswordField && (
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="ml-2 text-gray-600 hover:text-gray-800 focus:outline-none"
style={{
fontFamily: "Montserrat, sans-serif",
fontWeight: "500",
fontSize: 16,
background: "none",
border: "none",
cursor: "pointer",
padding: 0,
}}
>
{showPassword ? "Hide" : "Show"}
</button>
)}
</div>
</div>
);
};
export default FormField;

166
components/Header.tsx Normal file
View File

@ -0,0 +1,166 @@
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { ChevronLeft, Layers } from "lucide-react";
import { useTimer } from "@/context/TimerContext";
import styles from "@/css/Header.module.css";
import { useExam } from "@/context/ExamContext";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useModal } from "@/context/ModalContext";
import { API_URL, getToken } from "@/lib/auth";
import { UserData } from "@/types/auth";
interface HeaderProps {
displayUser?: boolean;
displaySubject?: string;
displayTabTitle?: string;
examDuration?: string;
}
const Header = ({
displayUser,
displaySubject,
displayTabTitle,
examDuration,
}: HeaderProps) => {
const router = useRouter();
const { open } = useModal();
const { clearExam } = useExam();
const [totalSeconds, setTotalSeconds] = useState(
examDuration ? parseInt(examDuration) * 60 : 0
);
const { timeRemaining, stopTimer } = useTimer();
const [userData, setUserData] = useState<UserData>();
useEffect(() => {
if (!examDuration) return;
const timer = setInterval(() => {
setTotalSeconds((prev) => {
if (prev <= 0) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [examDuration]);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) return;
const response = await fetch(`${API_URL}/me`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const fetchedUserData = await response.json();
setUserData(fetchedUserData);
}
} catch (error) {
console.error("Error fetching user data:", error);
}
}
if (displayUser) {
fetchUser();
}
}, [displayUser]);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const showExitDialog = () => {
const confirmed = window.confirm("Are you sure you want to quit the exam?");
if (confirmed) {
if (stopTimer) {
stopTimer();
}
clearExam();
router.push("/unit");
}
};
const handleBackClick = () => {
router.back();
};
return (
<header className={styles.header}>
{displayUser && (
<div className={styles.profile}>
<Avatar className="bg-gray-200 w-10 h-10">
<AvatarFallback className=" text-lg">
{userData?.name ? userData.name.charAt(0).toUpperCase() : ""}
</AvatarFallback>
</Avatar>
<span className={styles.text}>
Hello, {userData?.name ? userData.name.split(" ")[0] : ""}
</span>
</div>
)}
{displayTabTitle && (
<div className={styles.profile}>
<button onClick={handleBackClick} className={styles.iconButton}>
<ChevronLeft size={24} color="white" />
</button>
<span className={styles.text}>{displayTabTitle}</span>
</div>
)}
{displaySubject && (
<div className={styles.profile}>
<span className={styles.text}>{displaySubject}</span>
</div>
)}
{examDuration && (
<div className={styles.examHeader}>
<button onClick={showExitDialog} className={styles.iconButton}>
<ChevronLeft size={30} color="white" />
</button>
<div className={styles.timer}>
<div className={styles.timeUnit}>
<span className={styles.timeValue}>
{String(hours).padStart(2, "0")}
</span>
<span className={styles.timeLabel}>Hrs</span>
</div>
<div className={styles.timeUnit}>
<span className={styles.timeValue}>
{String(minutes).padStart(2, "0")}
</span>
<span className={styles.timeLabel}>Mins</span>
</div>
<div className={styles.timeUnit} style={{ borderRight: "none" }}>
<span className={styles.timeValue}>
{String(seconds).padStart(2, "0")}
</span>
<span className={styles.timeLabel}>Secs</span>
</div>
</div>
<button
onClick={open}
className={`${styles.iconButton} ${styles.disabled}`}
>
<Layers size={30} color="white" />
</button>
</div>
)}
</header>
);
};
export default Header;

View File

@ -0,0 +1,136 @@
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface UserData {
name: string;
institution: string;
sscRoll: string;
hscRoll: string;
email: string;
phone: string;
}
interface ProfileManagerProps {
userData: UserData | undefined;
edit: boolean;
setUserData: React.Dispatch<React.SetStateAction<UserData | undefined>>;
}
export default function ProfileManager({
userData,
edit,
setUserData,
}: ProfileManagerProps) {
if (!userData) return null;
const handleChange = (field: keyof UserData, value: string) => {
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
};
return (
<div className="mx-auto">
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name" className="text-sm font-semibold text-gray-700">
Name
</Label>
<Input
id="name"
type="text"
value={userData.name}
onChange={(e) => handleChange("name", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2">
<Label
htmlFor="institution"
className="text-sm font-semibold text-gray-700"
>
Institution
</Label>
<Input
id="institution"
type="text"
value={userData.institution}
onChange={(e) => handleChange("institution", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="flex gap-4">
<div className="space-y-2 w-full">
<Label
htmlFor="sscRoll"
className="text-sm font-semibold text-gray-700"
>
SSC Roll
</Label>
<Input
id="sscRoll"
type="text"
value={userData.sscRoll}
onChange={(e) => handleChange("sscRoll", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2 w-full">
<Label
htmlFor="hscRoll"
className="text-sm font-semibold text-gray-700"
>
HSC Roll
</Label>
<Input
id="hscRoll"
type="text"
value={userData.hscRoll}
onChange={(e) => handleChange("hscRoll", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
</div>
<div className="space-y-2">
<Label
htmlFor="email"
className="text-sm font-semibold text-gray-700"
>
Email
</Label>
<Input
id="email"
type="email"
value={userData.email}
onChange={(e) => handleChange("email", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2">
<Label
htmlFor="phone"
className="text-sm font-semibold text-gray-700"
>
Phone
</Label>
<Input
id="phone"
type="tel"
value={userData.phone}
onChange={(e) => handleChange("phone", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
</div>
</div>
);
}

132
components/QuestionItem.tsx Normal file
View File

@ -0,0 +1,132 @@
import { Question } from "@/types/exam";
import { BookmarkCheck, Bookmark } from "lucide-react";
import React, { useState } from "react";
import { Badge } from "./ui/badge";
interface ResultItemProps {
mode: "result";
question: Question;
selectedAnswer: string | undefined;
}
interface ExamItemProps {
mode: "exam";
question: Question;
selectedAnswer?: string;
handleSelect: (questionId: number, option: string) => void;
}
type QuestionItemProps = ResultItemProps | ExamItemProps;
const QuestionItem = (props: QuestionItemProps) => {
const [bookmark, setBookmark] = useState(false);
const { question, selectedAnswer } = props;
const isExam = props.mode === "exam";
return (
<div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
<h3 className="text-xl font-semibold ">
{question.id}. {question.question}
</h3>
{isExam && (
<div className="flex justify-between items-center mb-4">
<div></div>
<button onClick={() => setBookmark(!bookmark)}>
{bookmark ? (
<BookmarkCheck size={25} color="#113768" />
) : (
<Bookmark size={25} color="#113768" />
)}
</button>
</div>
)}
{isExam ? (
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options).map(([key, value]) => {
const isSelected = selectedAnswer === key;
return (
<button
key={key}
className="flex items-center gap-3"
onClick={
isExam
? () => props.handleSelect(question.id, key)
: undefined
}
disabled={!isExam}
>
<span
className={`flex items-center rounded-full border px-1.5 ${
isSelected ? "text-white bg-[#113768] border-[#113768]" : ""
}`}
>
{key.toUpperCase()}
</span>
<span className="option-description">{value}</span>
</button>
);
})}
</div>
) : (
<div className="flex flex-col gap-3">
<div className="flex justify-between items-center">
<div></div>
{!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>
) : (
<Badge className="bg-red-500 text-white" variant="default">
Incorrect
</Badge>
)}
</div>
<div className="flex flex-col gap-4 items-start">
{Object.entries(question.options).map(([key, value]) => {
const isCorrect = key === question.correctAnswer;
const isSelected = key === selectedAnswer?.answer;
let optionStyle =
"px-2 py-1 flex items-center rounded-full border font-medium text-sm";
if (isCorrect) {
optionStyle += " bg-green-600 text-white border-green-600";
}
if (isSelected && !isCorrect) {
optionStyle += " bg-red-600 text-white border-red-600";
}
if (!isCorrect && !isSelected) {
optionStyle += " border-gray-300 text-gray-700";
}
return (
<div key={key} className="flex items-center gap-3">
<span className={optionStyle}>{key.toUpperCase()}</span>
<span className="option-description">{value}</span>
</div>
);
})}
</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>
</div>
</div>
)}
</div>
);
};
export default QuestionItem;

View File

@ -0,0 +1,175 @@
import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import styles from "../css/SlidingGallery.module.css";
interface SlidingGalleryProps {
views?: {
id: string;
content: React.ReactNode;
}[];
className?: string;
showPagination?: boolean;
autoScroll?: boolean;
autoScrollInterval?: number;
onSlideChange?: (currentIndex: number) => void;
height?: string | number;
}
const SlidingGallery = ({
views = [],
className = "",
showPagination = true,
autoScroll = false,
autoScrollInterval = 5000,
onSlideChange = () => {},
height = "100vh",
}: SlidingGalleryProps) => {
const [activeIdx, setActiveIdx] = useState(0);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const scrollRef = useRef(null);
const galleryRef = useRef(null);
const autoScrollRef = useRef(null);
// Auto-scroll functionality
useEffect(() => {
if (autoScroll && views.length > 1) {
autoScrollRef.current = setInterval(() => {
setActiveIdx((prevIdx) => {
const nextIdx = (prevIdx + 1) % views.length;
goToSlide(nextIdx);
return nextIdx;
});
}, autoScrollInterval);
return () => {
if (autoScrollRef.current) {
clearInterval(autoScrollRef.current);
}
};
}
}, [autoScroll, autoScrollInterval, views.length]);
// Clear auto-scroll on user interaction
const handleUserInteraction = () => {
if (autoScrollRef.current) {
clearInterval(autoScrollRef.current);
}
};
useEffect(() => {
const updateDimensions = () => {
if (galleryRef.current) {
setDimensions({
width: galleryRef.current.clientWidth,
height: galleryRef.current.clientHeight,
});
}
};
// Initial dimension update
updateDimensions();
// Add resize listener
window.addEventListener("resize", updateDimensions);
// Cleanup
return () => window.removeEventListener("resize", updateDimensions);
}, []);
useEffect(() => {
// Recalculate active index when dimensions change
if (scrollRef.current && dimensions.width > 0) {
const scrollLeft = scrollRef.current.scrollLeft;
const slideWidth = dimensions.width;
const index = Math.round(scrollLeft / slideWidth);
setActiveIdx(index);
}
}, [dimensions]);
const handleScroll = (event: { target: { scrollLeft: any } }) => {
handleUserInteraction();
const scrollLeft = event.target.scrollLeft;
const slideWidth = dimensions.width;
const index = Math.round(scrollLeft / slideWidth);
if (index !== activeIdx) {
setActiveIdx(index);
onSlideChange(index);
}
};
const goToSlide = (index) => {
if (scrollRef.current) {
scrollRef.current.scrollTo({
left: index * dimensions.width,
behavior: "smooth",
});
}
};
const handleDotClick = (index) => {
handleUserInteraction();
goToSlide(index);
setActiveIdx(index);
onSlideChange(index);
};
// Early return if no views
if (!views || views.length === 0) {
return (
<div className={`${styles.gallery} ${className}`}>
<div className={styles.emptyState}>
<p>No content to display</p>
</div>
</div>
);
}
return (
<div
className={`${styles.gallery} ${className}`}
ref={galleryRef}
style={{ height }}
>
<div
className={styles.scrollContainer}
ref={scrollRef}
onScroll={handleScroll}
style={{
width: "100%",
height: "100%",
}}
>
{views.map((item) => (
<div
key={item.id}
className={styles.slide}
style={{
width: dimensions.width,
height: "100%",
flexShrink: 0,
}}
>
{item.content}
</div>
))}
</div>
{showPagination && views.length > 1 && (
<div className={styles.pagination}>
{views.map((_, index) => (
<div
key={index}
className={`${styles.dot} ${
activeIdx === index ? styles.activeDot : styles.inactiveDot
}`}
onClick={() => handleDotClick(index)}
style={{ cursor: "pointer" }}
/>
))}
</div>
)}
</div>
);
};
export default SlidingGallery;

53
components/ui/avatar.tsx Normal file
View File

@ -0,0 +1,53 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

46
components/ui/badge.tsx Normal file
View File

@ -0,0 +1,46 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

21
components/ui/input.tsx Normal file
View File

@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

24
components/ui/label.tsx Normal file
View File

@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

109
context/AuthContext.tsx Normal file
View File

@ -0,0 +1,109 @@
"use client";
import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
interface AuthContextType {
token: string | null;
setToken: (token: string | null) => void;
logout: () => void;
isLoading: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
// Cookie utility functions
const getCookie = (name: string): string | null => {
if (typeof document === "undefined") return null;
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
return parts.pop()?.split(";").shift() || null;
}
return null;
};
const setCookie = (
name: string,
value: string | null,
days: number = 7
): void => {
if (typeof document === "undefined") return;
if (value === null) {
// Delete cookie by setting expiration to past date
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
} else {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Strict; Secure`;
}
};
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [token, setTokenState] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
const pathname = usePathname();
// Custom setToken function that also updates cookies
const setToken = (newToken: string | null) => {
setTokenState(newToken);
setCookie("authToken", newToken);
};
// On app load, check if there's a token in cookies
useEffect(() => {
const initializeAuth = () => {
const storedToken = getCookie("authToken");
console.log("Current pathname:", pathname);
console.log("Stored token:", storedToken);
if (storedToken) {
setTokenState(storedToken);
if (
pathname === "/" ||
pathname === "/login" ||
pathname === "/register"
) {
console.log("Redirecting to /home");
router.replace("/home");
}
} else {
const publicPages = ["/", "/login", "/register"];
if (!publicPages.includes(pathname)) {
router.replace("/");
}
}
setIsLoading(false);
};
initializeAuth();
}, [pathname, router]);
// Function to log out
const logout = () => {
setTokenState(null);
setCookie("authToken", null); // Remove token from cookies
router.replace("/login"); // Redirect to login screen
};
return (
<AuthContext.Provider value={{ token, setToken, logout, isLoading }}>
{children}
</AuthContext.Provider>
);
};
// Hook to use the AuthContext
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};

276
context/ExamContext.tsx Normal file
View File

@ -0,0 +1,276 @@
"use client";
import React, {
createContext,
useContext,
useState,
useEffect,
ReactNode,
} from "react";
import { useRouter } from "next/navigation";
import { Exam, ExamAnswer, ExamAttempt, ExamContextType } from "@/types/exam";
import { getFromStorage, removeFromStorage, setToStorage } from "@/lib/utils";
const ExamContext = createContext<ExamContextType | undefined>(undefined);
const STORAGE_KEYS = {
CURRENT_EXAM: "current-exam",
CURRENT_ATTEMPT: "current-attempt",
} as const;
export const ExamProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const router = useRouter();
const [currentExam, setCurrentExamState] = useState<Exam | null>(null);
const [currentAttempt, setCurrentAttemptState] = useState<ExamAttempt | null>(
null
);
const [isHydrated, setIsHydrated] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
// Hydrate from session storage on mount
useEffect(() => {
const savedExam = getFromStorage<Exam>(STORAGE_KEYS.CURRENT_EXAM);
const savedAttempt = getFromStorage<ExamAttempt>(
STORAGE_KEYS.CURRENT_ATTEMPT
);
if (savedExam) {
setCurrentExamState(savedExam);
}
if (savedAttempt) {
// Convert date strings back to Date objects
const hydratedAttempt = {
...savedAttempt,
startTime: new Date(savedAttempt.startTime),
endTime: savedAttempt.endTime
? new Date(savedAttempt.endTime)
: undefined,
answers: savedAttempt.answers.map((answer) => ({
...answer,
timestamp: new Date(answer.timestamp),
})),
};
setCurrentAttemptState(hydratedAttempt);
}
setIsHydrated(true);
}, []);
// Persist to session storage whenever state changes
useEffect(() => {
if (!isHydrated) return;
if (currentExam) {
setToStorage(STORAGE_KEYS.CURRENT_EXAM, currentExam);
} else {
removeFromStorage(STORAGE_KEYS.CURRENT_EXAM);
}
}, [currentExam, isHydrated]);
useEffect(() => {
if (!isHydrated) return;
if (currentAttempt) {
setToStorage(STORAGE_KEYS.CURRENT_ATTEMPT, currentAttempt);
} else {
removeFromStorage(STORAGE_KEYS.CURRENT_ATTEMPT);
}
}, [currentAttempt, isHydrated]);
const setCurrentExam = (exam: Exam) => {
setCurrentExamState(exam);
setCurrentAttemptState(null);
};
const startExam = (exam?: Exam) => {
const examToUse = exam || currentExam;
if (!examToUse) {
console.warn("No exam selected, redirecting to /unit");
router.push("/unit");
return;
}
const attempt: ExamAttempt = {
examId: examToUse.id,
exam: examToUse,
answers: [],
startTime: new Date(),
totalQuestions: 0,
};
setCurrentAttemptState(attempt);
setIsInitialized(true);
};
const setAnswer = (questionId: string, answer: any) => {
if (!currentAttempt) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
setCurrentAttemptState((prev) => {
if (!prev) return null;
const existingAnswerIndex = prev.answers.findIndex(
(a) => a.questionId === questionId
);
const newAnswer: ExamAnswer = {
questionId,
answer,
timestamp: new Date(),
};
let newAnswers: ExamAnswer[];
if (existingAnswerIndex >= 0) {
// Update existing answer
newAnswers = [...prev.answers];
newAnswers[existingAnswerIndex] = newAnswer;
} else {
// Add new answer
newAnswers = [...prev.answers, newAnswer];
}
return {
...prev,
answers: newAnswers,
};
});
};
const setApiResponse = (response: any) => {
if (!currentAttempt) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
setCurrentAttemptState((prev) => {
if (!prev) return null;
return {
...prev,
apiResponse: response,
};
});
};
const submitExam = (): ExamAttempt | null => {
if (!currentAttempt) {
console.warn("No exam attempt to submit, redirecting to /unit");
router.push("/unit");
return null;
}
// Calculate score (simple example - you can customize this)
const attemptQuestions = currentAttempt.exam.questions;
const totalQuestions = attemptQuestions.length;
const answeredQuestions = currentAttempt.answers.filter(
(a) => a.questionId !== "__api_response__"
).length;
const score = Math.round((answeredQuestions / totalQuestions) * 100);
const completedAttempt: ExamAttempt = {
...currentAttempt,
endTime: new Date(),
score,
totalQuestions,
passed: currentAttempt.exam.passingScore
? score >= currentAttempt.exam.passingScore
: undefined,
};
setCurrentAttemptState(completedAttempt);
return completedAttempt;
};
const clearExam = (): void => {
setCurrentExamState(null);
setCurrentAttemptState(null);
};
const getAnswer = (questionId: string): any => {
if (!currentAttempt) return undefined;
const answer = currentAttempt.answers.find(
(a) => a.questionId === questionId
);
return answer?.answer;
};
const getApiResponse = (): any => {
return currentAttempt?.apiResponse;
};
const getProgress = (): number => {
if (!currentAttempt || !currentAttempt.exam) return 0;
const totalQuestions = currentAttempt.exam.questions.length;
const answeredQuestions = currentAttempt.answers.filter(
(a) => a.questionId !== "__api_response__"
).length;
return totalQuestions > 0 ? (answeredQuestions / totalQuestions) * 100 : 0;
};
const isExamStarted = () => !!currentExam && !!currentAttempt;
const isExamCompleted = (): boolean => {
if (!isHydrated) return false; // wait for hydration
return currentAttempt !== null && currentAttempt.endTime !== undefined;
};
const contextValue: ExamContextType = {
currentExam,
currentAttempt,
setCurrentExam,
startExam,
setAnswer,
submitExam,
clearExam,
setApiResponse,
getAnswer,
getProgress,
isExamStarted,
isExamCompleted,
getApiResponse,
isHydrated,
isInitialized,
};
return (
<ExamContext.Provider value={contextValue}>{children}</ExamContext.Provider>
);
};
export const useExam = (): ExamContextType => {
const context = useContext(ExamContext);
if (context === undefined) {
throw new Error("useExam must be used within an ExamProvider");
}
return context;
};
// Hook for exam results (only when exam is completed) - now returns null instead of throwing
export const useExamResults = (): ExamAttempt | null => {
const { currentAttempt, isExamCompleted, isHydrated } = useExam();
// Wait for hydration before making decisions
if (!isHydrated) {
return null;
}
// If no completed exam is found, return null (let component handle redirect)
if (!isExamCompleted() || !currentAttempt) {
return null;
}
return currentAttempt;
};

24
context/ModalContext.tsx Normal file
View File

@ -0,0 +1,24 @@
"use client";
import { createContext, useContext, useState } from "react";
const ModalContext = createContext(null);
export function ModalProvider({ children }) {
const [isOpen, setIsOpen] = useState(false);
const open = () => setIsOpen(true);
const close = () => setIsOpen(false);
const toggle = () => setIsOpen((prev) => !prev);
return (
<ModalContext.Provider value={{ isOpen, open, close, toggle }}>
{children}
</ModalContext.Provider>
);
}
export function useModal() {
const ctx = useContext(ModalContext);
if (!ctx) throw new Error("useModal must be inside <ModalProvider>");
return ctx;
}

70
context/TimerContext.tsx Normal file
View File

@ -0,0 +1,70 @@
"use client";
import React, { createContext, useContext, useState, useEffect } from "react";
// Define the context type
interface TimerContextType {
timeRemaining: number;
resetTimer: (duration: number) => void;
stopTimer: () => void;
setInitialTime: (duration: number) => void; // New function to set the initial time
}
// Create the context with a default value of `undefined`
const TimerContext = createContext<TimerContextType | undefined>(undefined);
// Provider Component
export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [timeRemaining, setTimeRemaining] = useState<number>(0); // Default is 0
let timer: NodeJS.Timeout;
useEffect(() => {
if (timeRemaining > 0) {
timer = setInterval(() => {
setTimeRemaining((prev) => {
if (prev <= 1) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
}
return () => {
clearInterval(timer); // Cleanup timer on unmount
};
}, [timeRemaining]);
const resetTimer = (duration: number) => {
clearInterval(timer);
setTimeRemaining(duration);
};
const stopTimer = () => {
clearInterval(timer);
};
const setInitialTime = (duration: number) => {
setTimeRemaining(duration);
};
return (
<TimerContext.Provider
value={{ timeRemaining, resetTimer, stopTimer, setInitialTime }}
>
{children}
</TimerContext.Provider>
);
};
// Hook to use the TimerContext
export const useTimer = (): TimerContextType => {
const context = useContext(TimerContext);
if (!context) {
throw new Error("useTimer must be used within a TimerProvider");
}
return context;
};

181
css/Header.module.css Normal file
View File

@ -0,0 +1,181 @@
.header {
background-color: #113768;
height: 130px;
width: 100%;
padding-top: 30px;
padding-left: 30px;
padding-right: 30px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 100;
}
.profile {
display: flex;
flex-direction: row;
align-items: center;
gap: 20px;
}
.profileImg {
width: 40px;
height: 40px;
border-radius: 50%;
object-fit: cover;
}
.text {
font-size: 20px ;
font-family: 'Montserrat', sans-serif;
font-weight: 700;
color: #fff;
}
.iconButton {
background: none;
border: none;
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
transition: opacity 0.2s;
}
.iconButton:hover {
opacity: 0.8;
}
.iconButton.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.examHeader {
display: flex;
flex-direction: row;
justify-content: space-between;
width: 100%;
align-items: center;
}
.timer {
width: 167px;
height: 55px;
background-color: #fff;
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
border-radius: 10px;
padding: 0 10px;
}
.timeUnit {
display: flex;
flex-direction: column;
align-items: center;
border-right: 1px solid #000;
width: 100%;
}
.timeValue {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
font-size: 20px;
color: #082E5E;
}
.timeLabel {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
font-size: 14px;
color: #082E5E;
}
/* Responsive Design */
@media (max-width: 768px) {
.header {
height: 100px;
padding-top: 20px;
padding-left: 20px;
padding-right: 20px;
}
.text {
font-size: 15px;
}
.profile {
gap: 15px;
}
.profileImg {
width: 35px;
height: 35px;
}
.timer {
width: 140px;
height: 45px;
}
.timeValue {
font-size: 16px;
}
.timeLabel {
font-size: 12px;
}
}
@media (max-width: 480px) {
.header {
height: 100px;
padding-top: 15px;
padding-left: 15px;
padding-right: 15px;
}
.text {
font-size: 17px;
}
.profile {
gap: 10px;
}
.profileImg {
width: 40px;
height: 40px;
}
.timer {
width: 180px;
height: 60px;
padding: 0 5px;
}
.timeValue {
font-size: 18px;
}
.timeLabel {
font-size: 12px;
}
.examHeader {
gap: 10px;
}
}
/* Safe area considerations for mobile */
@media (max-width: 480px) {
.header {
padding-top: max(15px, env(safe-area-inset-top));
}
}

268
css/Home.module.css Normal file
View File

@ -0,0 +1,268 @@
.container {
flex: 1;
min-height: 100vh;
}
.scrollContainer {
overflow-y: auto;
padding-top: 40px;
height: calc(100vh - 80px); /* Adjust based on header height */
}
.contentWrapper {
margin: 0 35px;
padding-bottom: 80px; /* Extra space at bottom for mobile */
}
.mainContent {
padding-top: 25px;
display: flex;
flex-direction: column;
gap: 35px;
}
.section {
display: flex;
flex-direction: column;
gap: 24px;
}
.lastSection {
margin-bottom: 80px;
}
.sectionHeader {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.sectionTitle {
font-size: 32px;
font-family: 'Montserrat', sans-serif;
font-weight: 700;
color: #113768;
margin: 0;
}
.arrowButton {
background: none;
border: none;
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
transition: opacity 0.2s;
}
.arrowButton:hover {
opacity: 0.7;
}
.arrowButton:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Categories Styles */
.categoriesContainer {
display: flex;
flex-direction: column;
justify-content: space-evenly;
gap: 16px;
padding-top: 25px;
}
.categoryRow {
display: flex;
flex-direction: row;
justify-content: space-between;
gap: 16px;
}
.categoryButton {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: 1px solid #c5dbf8;
width: 48%;
height: 150px; /* Approximate scaled height */
border-radius: 25px;
background: white;
cursor: pointer;
transition: all 0.2s;
gap: 8px;
}
.categoryButton:hover:not(:disabled) {
background-color: #f8fbff;
transform: translateY(-2px);
}
.categoryButton.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.categoryButtonText {
font-size: 14px;
font-family: 'Montserrat', sans-serif;
font-weight: 500;
color: #113768;
}
/* Leaderboard Styles */
.leaderboardWrapper {
display: flex;
flex-direction: column;
gap: 20px;
}
.leaderboardContainer {
border: 1px solid #c5dbf8;
padding: 22px 15px;
border-radius: 20px;
display: flex;
flex-direction: column;
gap: 15px;
background: white;
}
.topThreeHeader {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.topThreeTitle {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
font-size: 17px;
}
.divider {
border-top: 0.5px solid #c5dbf8;
}
.topThreeList {
display: flex;
flex-direction: column;
gap: 12px;
}
.topThreeItem {
display: flex;
flex-direction: row;
border: 1px solid #c5dbf8;
border-radius: 10px;
padding: 6px 12px;
justify-content: space-between;
align-items: center;
}
.studentInfo {
display: flex;
flex-direction: row;
gap: 12px;
align-items: center;
}
.rank {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
font-size: 20px;
}
.avatar {
border-radius: 50%;
}
.studentName {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
font-size: 14px;
}
.points {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
color: rgba(0, 0, 0, 0.4);
}
/* Coming Soon Card */
.comingSoonCard {
border: 2px solid #c5dbf8;
width: 100%;
padding: 24px;
border-radius: 20px;
background: white;
display: flex;
align-items: center;
justify-content: center;
}
.comingSoonText {
font-family: 'Montserrat', sans-serif;
font-weight: 500;
font-size: 20px;
text-align: center;
margin: 0;
}
/* Responsive Design */
@media (max-width: 768px) {
.contentWrapper {
margin: 0 20px;
}
.sectionTitle {
font-size: 20px;
}
.categoryButton {
height: 120px;
}
.categoryButtonText {
font-size: 14px;
}
.categoryRow {
gap: 12px;
}
.comingSoonText {
font-size: 18px;
}
}
@media (max-width: 480px) {
.contentWrapper {
margin: 0 15px;
}
.sectionTitle {
font-size: 22px;
}
.categoryButton {
height: 200px;
}
.mainContent {
gap: 25px;
}
.categoryRow {
flex-direction: row;
}
.categoryButton {
width: 100%;
}
}

View File

@ -0,0 +1,167 @@
/* SlidingGallery.module.css */
.gallery {
position: relative;
width: 100%;
height: 100vh; /* Default height, can be overridden by props */
overflow: hidden;
display: flex;
flex-direction: column;
}
.emptyState {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: #666;
font-size: 1.2rem;
}
.scrollContainer {
flex: 1;
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE and Edge */
}
.scrollContainer::-webkit-scrollbar {
display: none; /* Chrome, Safari, Opera */
}
.slide {
min-width: 100%;
scroll-snap-align: start;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
box-sizing: border-box;
}
.link {
width: 100%;
height: 100%;
display: block;
text-decoration: none;
color: inherit;
}
.facebook {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 40px;
box-sizing: border-box;
background: linear-gradient(135deg, #1877f2 0%, #42a5f5 100%);
border-radius: 20px;
color: white;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.facebook:hover {
transform: translateY(-5px);
}
.textView {
flex: 1;
padding-right: 20px;
}
.facebookOne {
font-size: clamp(1.5rem, 4vw, 2.5rem);
font-weight: 700;
margin: 0 0 16px 0;
line-height: 1.2;
}
.facebookTwo {
font-size: clamp(1rem, 2.5vw, 1.25rem);
margin: 0;
opacity: 0.9;
line-height: 1.4;
}
.logoView {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.logoView img {
width: clamp(120px, 15vw, 120px);
height: clamp(120px, 15vw, 120px);
object-fit: contain;
}
.pagination {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 6px;
z-index: 10;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
transition: all 0.3s ease;
cursor: pointer;
}
.activeDot {
background-color: #113768;
}
.inactiveDot {
background-color: #b1d3ff;
}
.inactiveDot:hover {
background-color: rgba(255, 255, 255, 0.8);
}
/* Responsive adjustments */
@media (max-width: 768px) {
.gallery {
height: 70vh; /* Adjust for mobile */
}
.facebook {
flex-direction: column;
text-align: center;
padding: 30px 20px;
}
.textView {
padding-right: 0;
margin-bottom: 20px;
}
.slide {
padding: 15px;
}
}
@media (max-width: 480px) {
.gallery {
height: 60vh;
}
.facebook {
padding: 20px 15px;
}
.slide {
padding: 10px;
}
}

100
lib/auth.ts Normal file
View File

@ -0,0 +1,100 @@
export const API_URL = "https://examjam-api.pptx704.com";
// Cookie utility functions
const setCookie = (name, value, days = 7) => {
if (typeof document === "undefined") return;
if (value === null) {
// Delete cookie by setting expiration to past date
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
} else {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Strict; Secure`;
}
};
export const login = async (form, setToken) => {
const response = await fetch(`${API_URL}/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(form),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Login failed");
}
// Save the token to cookies instead of secure storage
setCookie("authToken", data.token);
setToken(data.token); // Update the token in context
};
const handleError = (error) => {
// Check if error has a "detail" property
if (error?.detail) {
// Match the field causing the issue
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
if (match) {
const field = match[1]; // The field name, e.g., "phone"
const value = match[2]; // The duplicate value, e.g., "0987654321"
return `The ${field} already exists. Please use a different value.`;
}
}
return "An unexpected error occurred. Please try again.";
};
export const register = async (form, setToken) => {
const response = await fetch(`${API_URL}/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(form),
});
const data = await response.json(); // Parse the response JSON
if (!response.ok) {
// Instead of throwing a string, include full error data for debugging
const error = new Error(data?.detail || "Registration failed");
error.response = data; // Attach the full response for later use
throw error;
}
// Save the token to cookies instead of secure storage
setCookie("authToken", data.token);
setToken(data.token); // Update the token in context
};
// Additional utility function to get token from cookies (if needed elsewhere)
export const getTokenFromCookie = () => {
if (typeof document === "undefined") return null;
const value = `; ${document.cookie}`;
const parts = value.split(`; authToken=`);
if (parts.length === 2) {
return parts.pop()?.split(";").shift() || null;
}
return null;
};
// Utility function to clear auth token (for logout)
export const clearAuthToken = () => {
setCookie("authToken", null);
};
export const getToken = async () => {
if (typeof window === "undefined") {
return null;
}
// Extract authToken from cookies
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
return match ? decodeURIComponent(match[1]) : null;
};

136
lib/gallery-views.tsx Normal file
View File

@ -0,0 +1,136 @@
// lib/gallery-views.tsx
import Link from "next/link";
import Image from "next/image";
interface ExamResults {
score: number;
totalQuestions: number;
answers: string[];
}
interface LinkedViews {
id: string;
content: React.ReactNode;
}
export const getResultViews = (examResults: ExamResults | null) => [
{
id: 1,
content: (
<div className="w-full">
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[170px] flex flex-col items-center justify-center gap-4">
<div className="text-xl text-black">
<span className="font-bold">Accuracy</span> Rate:
</div>
<div className="flex gap-4">
<Image
src="/images/icons/accuracy.png"
alt="accuracy"
width={60}
height={60}
/>
<h2 className="text-6xl font-bold text-[#113678]">
{examResults
? (
(examResults.score / examResults.totalQuestions) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
{
id: 2,
content: (
<div className="w-full">
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[170px] flex flex-col items-center justify-center gap-3">
<div className="text-xl text-black">
<span className="font-bold">Error</span> Rate:
</div>
<div className="flex gap-4">
<Image
src="/images/icons/error.png"
alt="error"
width={60}
height={60}
/>
<h2 className="text-6xl font-bold text-[#113678]">
{examResults
? (
((examResults.totalQuestions - examResults.score) /
examResults.totalQuestions) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
{
id: 3,
content: (
<div className="my-8 w-full">
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[170px] flex flex-col items-center justify-center gap-4">
<div className="text-xl text-black">
<span className="font-bold">Attempt</span> Rate:
</div>
<div className="flex gap-4">
<Image
src="/images/icons/attempt.png"
alt="attempt"
width={60}
height={60}
/>
<h2 className="text-6xl font-bold text-[#113678]">
{examResults
? (
(examResults.answers.length / examResults.totalQuestions) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
];
export const getLinkedViews = (): LinkedViews[] => [
{
id: "1",
content: (
<Link
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
className="w-full h-full block text-inherit box-border"
>
<div className="w-full h-full p-6 flex text-black bg-blue-50 rounded-4xl border-[0.5px] border-[#113768]/30">
<div className="">
<h3 className="text-2xl text-[#113768] font-black">
Meet, Share, and Learn!
</h3>
<p className="font-bold text-sm text-[#113768] ">
Join Facebook Community
</p>
</div>
<div className="flex justify-center items-center shrink-0">
<Image
src="/images/static/facebook-logo.png"
alt="Facebook Logo"
width={150}
height={150}
/>
</div>
</div>
</Link>
),
},
];

32
lib/leaderboard.ts Normal file
View File

@ -0,0 +1,32 @@
export interface BoardData {
id: string;
name: string;
points: number;
}
export const getTopThree = (boardData: BoardData[]) => {
if (!boardData || boardData.length === 0) return [];
return boardData
.slice()
.sort((a, b) => b.points - a.points)
.slice(0, 3)
.map((player, index) => ({
...player,
rank: index + 1,
height: index === 0 ? 250 : index === 1 ? 200 : 170,
}));
};
export const getLeaderboard = (boardData: BoardData[]) => {
return boardData.slice().sort((a, b) => b.points - a.points);
};
export const getUserData = (boardData: BoardData[], name: string) => {
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 }] : [];
};

View File

@ -1,6 +1,38 @@
import { clsx, type ClassValue } from "clsx" import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs));
} }
export const getFromStorage = <T>(key: string): T | null => {
if (typeof window === "undefined") return null;
try {
const item = sessionStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (error) {
console.error(`Error reading from sessionStorage (${key}):`, error);
return null;
}
};
export const setToStorage = <T>(key: string, value: T): void => {
if (typeof window === "undefined") return;
try {
sessionStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error writing to sessionStorage (${key}):`, error);
}
};
export const removeFromStorage = (key: string): void => {
if (typeof window === "undefined") return;
try {
sessionStorage.removeItem(key);
} catch (error) {
console.error(`Error removing from sessionStorage (${key}):`, error);
}
};

2611
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
{ {
"name": "nextjs-template-shadcn", "name": "examjam-frontend",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
@ -9,25 +9,27 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"class-variance-authority": "^0.7.1", "@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-slot": "^1.2.3",
"capacitor-secure-storage-plugin": "^0.11.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^0.525.0", "lucide-react": "^0.523.0",
"next": "15.3.4", "next": "15.3.2",
"postcss": "^8.5.6",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0"
"tailwind-merge": "^3.3.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3", "@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4.1.11", "@tailwindcss/postcss": "^4",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"autoprefixer": "^10.4.21",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "15.3.4", "eslint-config-next": "15.3.2",
"tailwindcss": "^4.1.11", "postcss": "^8.5.6",
"tw-animate-css": "^1.3.4", "tailwindcss": "^4",
"typescript": "^5" "typescript": "^5"
} }
} }

152
public/data/bookmark.json Normal file
View File

@ -0,0 +1,152 @@
[
{
"id": 0,
"question": "What is the gravitational acceleration on Earth's surface?",
"options": {
"a": "8.9 m/s²",
"b": "9.8 m/s²",
"c": "10.5 m/s²",
"d": "11.2 m/s²"
}
},
{
"id": 1,
"question": "Which planet is known as the Red Planet?",
"options": {
"a": "Venus",
"b": "Jupiter",
"c": "Mars",
"d": "Saturn"
}
},
{
"id": 2,
"question": "What is the chemical symbol for gold?",
"options": {
"a": "Go",
"b": "Gd",
"c": "Au",
"d": "Ag"
}
},
{
"id": 3,
"question": "How many chambers does a human heart have?",
"options": {
"a": "2",
"b": "3",
"c": "4",
"d": "5"
}
},
{
"id": 4,
"question": "What is the speed of light in a vacuum?",
"options": {
"a": "299,792,458 m/s",
"b": "300,000,000 m/s",
"c": "298,000,000 m/s",
"d": "301,000,000 m/s"
}
},
{
"id": 5,
"question": "Which gas makes up approximately 78% of Earth's atmosphere?",
"options": {
"a": "Oxygen",
"b": "Carbon dioxide",
"c": "Nitrogen",
"d": "Argon"
}
},
{
"id": 6,
"question": "What is the hardest natural substance on Earth?",
"options": {
"a": "Quartz",
"b": "Diamond",
"c": "Graphite",
"d": "Titanium"
}
},
{
"id": 7,
"question": "How many bones are in an adult human body?",
"options": {
"a": "196",
"b": "206",
"c": "216",
"d": "226"
}
},
{
"id": 8,
"question": "What is the pH of pure water?",
"options": {
"a": "6",
"b": "7",
"c": "8",
"d": "9"
}
},
{
"id": 9,
"question": "Which organelle is known as the powerhouse of the cell?",
"options": {
"a": "Nucleus",
"b": "Ribosome",
"c": "Mitochondria",
"d": "Golgi apparatus"
}
},
{
"id": 10,
"question": "What is the most abundant element in the universe?",
"options": {
"a": "Helium",
"b": "Hydrogen",
"c": "Oxygen",
"d": "Carbon"
}
},
{
"id": 11,
"question": "At what temperature does water boil at sea level?",
"options": {
"a": "90°C",
"b": "95°C",
"c": "100°C",
"d": "105°C"
}
},
{
"id": 12,
"question": "How many chromosomes do humans have?",
"options": {
"a": "44",
"b": "46",
"c": "48",
"d": "50"
}
},
{
"id": 13,
"question": "What is the smallest unit of matter?",
"options": {
"a": "Molecule",
"b": "Atom",
"c": "Electron",
"d": "Proton"
}
},
{
"id": 14,
"question": "Which type of electromagnetic radiation has the longest wavelength?",
"options": {
"a": "X-rays",
"b": "Visible light",
"c": "Radio waves",
"d": "Gamma rays"
}
}
]

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
public/images/logo/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

8
types/auth.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
export interface UserData {
name: string;
institution: string;
sscRoll: string;
hscRoll: string;
email: string;
phone: string;
}

57
types/exam.d.ts vendored Normal file
View File

@ -0,0 +1,57 @@
export interface Question {
id: string;
text: string;
options?: Record<string, string>;
type: "multiple-choice" | "text" | "boolean" | undefined;
correctAnswer: string | undefined;
solution?: string | undefined;
}
export interface Exam {
id: string;
title: string;
description: string;
questions: Question[];
timeLimit?: number;
passingScore?: number;
}
export interface ExamAnswer {
questionId: string;
answer: any;
timestamp: Date;
}
export interface ExamAttempt {
examId: string;
exam: Exam;
answers: ExamAnswer[];
startTime: Date;
endTime?: Date;
score?: number;
passed?: boolean;
apiResponse?: any;
totalQuestions: number;
}
export interface ExamContextType {
currentExam: Exam | null;
currentAttempt: ExamAttempt | null;
isHydrated: boolean;
isInitialized: boolean;
// Actions
setCurrentExam: (exam: Exam) => void;
startExam: () => void;
setAnswer: (questionId: string, answer: any) => void;
submitExam: () => ExamAttempt;
clearExam: () => void;
setApiResponse: (response: any) => void;
// Getters
getAnswer: (questionId: string) => any;
getProgress: () => number;
isExamStarted: () => boolean;
isExamCompleted: () => boolean;
getApiResponse: () => any;
}