46 Commits

Author SHA1 Message Date
11108ad8cf fix(ui): fix ui icons and readability 2025-11-12 15:38:07 +06:00
d1947e8e6e fix(auth): fix fetch user info at login 2025-10-07 13:50:29 +06:00
e1a33d1398 fix(nav): improve redirection logic 2025-10-06 19:16:03 +06:00
981fe6973f fix(ui): improve ui/ux and visibility 2025-10-06 18:39:58 +06:00
351c8eab48 feat(ui): improve error handling on categories page 2025-10-06 18:14:00 +06:00
108d34988d fix(nav): fix exam flow navigation
chore(zustand): refactor auth code for zustand store
2025-09-09 20:45:30 +06:00
c3ead879ad feat(auth): add verification feature in settings 2025-09-09 00:54:06 +06:00
4042e28bf7 feat(ui): add verified badge to header 2025-09-08 14:30:01 +06:00
53a2228dc9 fix(nav): improve navigation for authorization routes 2025-09-08 14:15:27 +06:00
99d6c15e38 chore(capacitor): refactor codebase for capacitor entry 2025-09-08 13:42:15 +06:00
3b2488054c feat(nav): add flow-guarding for exam result screens 2025-09-01 17:53:44 +06:00
5fd76bc0ec fix(ui): fix timer reappearing after exam submission 2025-09-01 17:13:35 +06:00
5507602031 fix(ui): refactor results page for exam results logic 2025-08-31 23:27:32 +06:00
7df2708db7 feat(zustand): add zustand stores for exam, timer and auth 2025-08-31 18:28:01 +06:00
65e3338859 fix(api): exam logic yet to be fixed 2025-08-31 17:45:08 +06:00
b112a8fdac fix(api): fix api logic for exam screen
needs more work for the timercontext
2025-08-31 02:20:55 +06:00
08a560abe5 fix(api): fix exam screen api logic 2025-08-27 23:45:37 +06:00
84bc192e02 feat(ui): add icons to destructible alert 2025-08-23 13:51:11 +06:00
46608356ee fix(ui): minor ui tweak in pretest screen 2025-08-23 13:36:26 +06:00
6f4f2a8668 feat(ui): add topic, subject screen
fix(api): fix api endpoint logic for pretest screen
2025-08-21 14:19:55 +06:00
be5c723bff feat(ui): add topic test screen 2025-08-20 20:11:15 +06:00
399c0b0060 chore(ui): refactor subjects ui 2025-08-19 00:28:49 +06:00
d74b81e962 fix(api): fix api endpoint logic #6 2025-08-18 17:48:32 +06:00
58d4d14a51 fix(api): fix api endpoint logic #5
chore(env): obscure api url in env

feat(ui): render subjects according to user preparation unit
2025-08-18 15:06:50 +06:00
e3673951c6 fix(api): fix api endpoint logic #3 2025-08-17 19:59:14 +06:00
4f23f357e6 fix(api): fix api endpoint logic #3 2025-08-17 14:08:17 +06:00
ad46bf954e fix(api): fix api endpoint logic #2 2025-08-16 17:05:40 +06:00
713696760e fix(api): fix api endpoint logic #1 2025-08-10 19:25:25 +06:00
0bca09f8ef fix(ts): refactor codebase for capacitor setup 2025-07-28 20:22:04 +06:00
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
b0737ea703 Initial commit 2025-07-02 19:41:20 +00:00
70 changed files with 7584 additions and 1371 deletions

1
.env.example Normal file
View File

@ -0,0 +1 @@
NEXT_PUBLIC_EXAMJAM_API_URL=api_url_here

5
.gitignore vendored
View File

@ -16,6 +16,7 @@
# next.js
/.next/
/out/
android
# production
/build
@ -31,7 +32,7 @@ yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
.env
# vercel
.vercel
@ -39,3 +40,5 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
.vercel

View File

@ -6,31 +6,42 @@ 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";
import { LoginForm } from "@/types/auth";
import { CircleAlert } from "lucide-react";
import { useAuthStore } from "@/stores/authStore";
const page = () => {
const LoginPage = () => {
const router = useRouter();
const { setToken } = useAuth();
const [form, setForm] = useState({
email: "",
const { login } = useAuthStore();
const [form, setForm] = useState<LoginForm>({
identifier: "",
password: "",
});
const [error, setError] = useState(null);
const [error, setError] = useState<string | null>(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
await login(form);
router.replace("/home");
} catch (err: unknown) {
console.error(err);
if (
typeof err === "object" &&
err !== null &&
"message" in err &&
typeof err.message === "string"
) {
setError(err.message);
} else {
setError("An unexpected error occurred.");
}
} finally {
setIsLoading(false);
}
@ -60,23 +71,31 @@ const page = () => {
<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}
title="Email \ Username"
value={form.identifier}
placeholder="Enter your email address..."
handleChangeText={(e) => setForm({ ...form, email: e })}
handleChangeText={(value) =>
setForm({ ...form, identifier: value })
}
/>
<FormField
title="Password"
value={form.password}
placeholder="Enter a password"
handleChangeText={(e) => setForm({ ...form, password: e })}
handleChangeText={(value) =>
setForm({ ...form, password: value })
}
/>
</div>
{error && <DestructibleAlert text={error} />}
{error && <DestructibleAlert text={error} extraStyles="" />}
<h1 className="flex justify-center items-center gap-2 bg-green-200 p-4 rounded-full">
<CircleAlert size={20} />
Your login details will be remembered.
</h1>
<button
onClick={() => router.push("/home")}
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"
>
@ -94,7 +113,7 @@ const page = () => {
className="text-center mb-[70px]"
style={{ fontFamily: "Montserrat, sans-serif" }}
>
Don't have an account?{" "}
Don&apos;t have an account?{" "}
<Link href="/register" className="text-[#276ac0] hover:underline">
Register here.
</Link>
@ -106,4 +125,4 @@ const page = () => {
);
};
export default page;
export default LoginPage;

View File

@ -4,42 +4,69 @@ 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";
import { RegisterForm } from "@/types/auth";
import { useAuthStore } from "@/stores/authStore";
interface ValidationErrorItem {
type: string;
loc: string[];
msg: string;
input?: unknown;
ctx?: Record<string, unknown>;
}
interface CustomError extends Error {
response?: {
detail?: string | ValidationErrorItem;
};
}
export default function RegisterPage() {
const { setToken } = useAuth();
const { register } = useAuthStore();
const router = useRouter();
const [form, setForm] = useState({
name: "",
institution: "",
sscRoll: "",
hscRoll: "",
const [form, setForm] = useState<RegisterForm>({
full_name: "",
username: "",
email: "",
phone: "",
password: "",
phone_number: "",
ssc_roll: 0,
ssc_board: "",
hsc_roll: 0,
hsc_board: "",
college: "",
preparation_unit: "",
});
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.`;
function formatError(error: unknown): string {
if (error && typeof error === "object" && "response" in (error as any)) {
const customError = error as CustomError;
const detail = customError.response?.detail;
if (typeof detail === "string") {
return detail; // plain backend error string
}
if (Array.isArray(detail)) {
// Pick the first validation error, or join them if multiple
return detail.map((d) => d.msg).join("; ");
}
}
return "An unexpected error occurred. Please try again.";
};
if (error instanceof Error) {
return error.message;
}
return "An unexpected error occurred.";
}
const validateForm = () => {
const { sscRoll, hscRoll, password } = form;
if (sscRoll === hscRoll) {
const { ssc_roll, hsc_roll, password } = form;
if (ssc_roll === hsc_roll) {
return "SSC Roll and HSC Roll must be unique.";
}
const passwordRegex =
@ -56,28 +83,23 @@ export default function RegisterPage() {
setError(validationError);
return;
}
try {
await register(form, setToken);
router.push("/tabs/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.");
}
await register(form);
router.replace("/login");
} catch (err: unknown) {
setError(formatError(err));
console.error("User creation error: ", err);
}
};
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 space-y-6">
<div className="w-full aspect-[368/89] mx-auto">
<Image
src="/images/logo/logo.png"
alt="Logo"
alt="logo"
width={368}
height={89}
className="w-full h-auto"
@ -86,61 +108,94 @@ export default function RegisterPage() {
<div className="space-y-10">
<div className="space-y-6">
<h1 className="text-2xl font-semibold">Personal Info</h1>
<FormField
title="Full name"
value={form.name}
handleChangeText={(e) =>
setForm({ ...form, name: e.target.value })
value={form.full_name}
handleChangeText={(value) =>
setForm({ ...form, full_name: value })
}
/>
<FormField
title="Institution"
placeholder="Enter a institution"
value={form.institution}
handleChangeText={(e) =>
setForm({ ...form, institution: e.target.value })
}
/>
<FormField
title="SSC Roll No."
placeholder="Enter your SSC Roll No."
value={form.sscRoll}
handleChangeText={(e) =>
setForm({ ...form, sscRoll: e.target.value })
}
/>
<FormField
title="HSC Roll No."
placeholder="Enter your HSC Roll No."
value={form.hscRoll}
handleChangeText={(e) =>
setForm({ ...form, hscRoll: e.target.value })
}
/>
<FormField
title="Email Address"
placeholder="Enter your email address..."
value={form.email}
handleChangeText={(e) =>
setForm({ ...form, email: e.target.value })
title="User name"
value={form.username}
handleChangeText={(value) =>
setForm({ ...form, username: value })
}
/>
<FormField
title="Phone Number"
placeholder="Enter your phone number.."
value={form.phone}
handleChangeText={(e) =>
setForm({ ...form, phone: e.target.value })
value={form.phone_number}
handleChangeText={(value) =>
setForm({ ...form, phone_number: value })
}
/>
<FormField
title="Email Address"
value={form.email}
handleChangeText={(value) => setForm({ ...form, email: value })}
/>
<FormField
title="Password"
placeholder="Enter a password"
value={form.password}
handleChangeText={(e) =>
setForm({ ...form, password: e.target.value })
handleChangeText={(value) =>
setForm({ ...form, password: value })
}
placeholder={undefined}
/>
<h1 className="text-2xl font-semibold">Educational Background</h1>
<FormField
title="College"
value={form.college}
handleChangeText={(value) =>
setForm({ ...form, college: value })
}
/>
<FormField
title="Preparation Unit"
value={form.preparation_unit}
handleChangeText={(value) =>
setForm({ ...form, preparation_unit: value })
}
/>
<div className="w-full flex gap-4">
<FormField
title="SSC Board"
value={form.ssc_board}
handleChangeText={(value) =>
setForm({ ...form, ssc_board: value })
}
/>
<FormField
title="SSC Roll No."
value={form.ssc_roll}
handleChangeText={(value: string) =>
setForm({ ...form, ssc_roll: Number(value) })
}
className="max-w-26"
/>
</div>
<div className="w-full flex gap-4">
<FormField
title="HSC Board"
value={form.hsc_board}
handleChangeText={(value) =>
setForm({ ...form, hsc_board: value })
}
/>
<FormField
title="HSC Roll No."
value={form.hsc_roll}
handleChangeText={(value: string) =>
setForm({ ...form, hsc_roll: Number(value) })
}
className="max-w-26"
/>
</div>
</div>
{error && <DestructibleAlert text={error} />}
@ -153,7 +208,7 @@ export default function RegisterPage() {
</button>
<p className="text-center text-sm">
Already have an account?{" "}
Already have an account?
<Link href="/login" className="text-blue-600">
Login here
</Link>

View File

@ -1,7 +1,92 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
import React from "react";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { ListFilter, MoveLeft } from "lucide-react";
import { useRouter } from "next/navigation";
import DestructibleAlert from "@/components/DestructibleAlert";
// 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<Question[]>([]);
// 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: Question) => (
<QuestionItem key={question.id} question={question} />
))} */}
<DestructibleAlert
text="Page under construction"
variant="warning"
/>
</div>
</div>
</section>
</BackgroundWrapper>
);
};
export default page;
export default BookmarkPage;

View File

@ -0,0 +1,150 @@
"use client";
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, getToken } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
import { useAuthStore } from "@/stores/authStore";
type Mock = {
test_id: string;
name: string;
type: string;
num_questions: number;
time_limit_minutes: number;
deduction: number;
total_possible_score: number;
unit: string;
};
export default function MockScreen() {
const router = useRouter();
const { user } = useAuthStore();
const [mocks, setMocks] = useState<Mock[]>([]);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
async function fetchMocks() {
setRefreshing(true);
try {
const token = await getToken();
const response = await fetch(`${API_URL}/tests/mock/`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error("Failed to fetch topics");
}
const fetchedMocks: Mock[] = await response.json();
setMocks(fetchedMocks);
} catch (error) {
setErrorMsg(
"Error fetching mocks: " +
(error instanceof Error ? error.message : "Unknown error")
);
} finally {
setRefreshing(false);
}
}
useEffect(() => {
const fetchData = async () => {
if (await getToken()) {
fetchMocks();
}
};
fetchData();
}, []);
const onRefresh = async () => {
fetchMocks();
};
if (errorMsg) {
return (
<BackgroundWrapper>
<Header displayTabTitle="Mocks" />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit}
</h1>
<DestructibleAlert text={errorMsg} variant="error" />
</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>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle="Mocks" />
<div className="mx-10 pb-20 overflow-y-auto">
<h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit}
</h1>
<div className="border border-[#c0dafc]/50 flex flex-col gap-4 w-full rounded-[25px] p-3">
{mocks.length > 0 ? (
mocks.map((mocks) => (
<div key={mocks.test_id}>
<button
onClick={() =>
router.push(
`/exam/pretest?type=mock&test_id=${mocks.test_id}`
)
}
className="w-full border-1 border-[#B0C2DA] py-3 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-lg font-medium">{mocks.name}</h3>
<div className="flex space-x-2">
<p className="text-sm font-normal bg-slate-500 w-fit px-3 py-1 rounded-full text-white">
{mocks.unit}
</p>
</div>
</button>
</div>
))
) : refreshing ? (
<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>
) : (
<DestructibleAlert
text="There aren't any tests available for you. Check back later?"
variant="warning"
/>
)}
</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

@ -1,7 +1,75 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import React from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
const CategoriesPage = () => {
const router = useRouter();
return (
<BackgroundWrapper>
<main>
<Header displayTabTitle="Categories" />
<div className="grid grid-cols-2 gap-4 pt-6 mx-4">
<button
onClick={() => router.push("/categories/topics")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/topic-test.png"
alt="Topic Test"
width={85}
height={85}
/>
<span className="font-medium text-[#113768]">Topic Test</span>
</button>
<button
onClick={() => router.push("/categories/mocks")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/mock-test.png"
alt="Mock Test"
width={85}
height={85}
/>
<span className="font-medium text-[#113768]">Mock Test</span>
</button>
<button
disabled
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/past-paper.png"
alt="Past Papers"
width={68}
height={68}
className="opacity-50"
/>
<span className="font-medium text-[#113768]/50">Past Papers</span>
</button>
<button
onClick={() => router.push("/categories/subjects")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/subject-test.png"
alt="Subject Test"
width={80}
height={80}
/>
<span className="font-medium text-[#113768]">Subject Test</span>
</button>
</div>
</main>
</BackgroundWrapper>
);
};
export default page;
export default CategoriesPage;

View File

@ -0,0 +1,144 @@
"use client";
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, getToken } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
import { useAuthStore } from "@/stores/authStore";
import { FaStar } from "react-icons/fa";
type Subject = {
subject_id: string;
name: string;
unit: string;
};
export default function PaperScreen() {
const router = useRouter();
const { user } = useAuthStore();
const [subjects, setSubjects] = useState<Subject[]>([]);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
async function fetchSubjects() {
setRefreshing(true);
try {
const token = await getToken();
const response = await fetch(`${API_URL}/subjects/`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error("Failed to fetch subjects");
}
const fetchedSubjects: Subject[] = await response.json();
setSubjects(fetchedSubjects);
} catch (error) {
setErrorMsg(
"Error fetching subjects: " +
(error instanceof Error ? error.message : "Unknown error")
);
} finally {
setRefreshing(false);
}
}
useEffect(() => {
const fetchData = async () => {
if (await getToken()) {
fetchSubjects();
}
};
fetchData();
}, []);
const onRefresh = async () => {
fetchSubjects();
};
if (errorMsg) {
return (
<BackgroundWrapper>
<Header displayTabTitle="Subjects" />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit}
</h1>
<DestructibleAlert text={errorMsg} variant="error" />
</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>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle="Subjects" />
<div className="mx-10 pt-5 overflow-y-auto">
<h1 className="text-2xl font-semibold mb-5">
{user?.preparation_unit}
</h1>
<div className="border border-[#c0dafc]/50 flex flex-col gap-4 w-full rounded-[20px] p-3">
{subjects.length > 0 ? (
subjects
.filter((subject) => subject.unit === user?.preparation_unit)
.map((subject) => (
<div key={subject.subject_id}>
<button
onClick={() =>
router.push(
`/exam/pretest?type=subject&test_id=${subject.subject_id}`
)
}
className="w-full border-1 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-xl font-medium">{subject.name}</h3>
<p className="text-xl font-medium text-[#113768] flex items-center gap-1">
<FaStar size={15} />
<FaStar size={15} />
<FaStar size={15} />
<FaStar size={15} />
</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,144 @@
"use client";
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, getToken } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
import { useAuthStore } from "@/stores/authStore";
type Topic = {
topic_id: string;
name: string;
subject: {
subject_id: string;
name: string;
unit: string;
};
};
export default function TopicScreen() {
const router = useRouter();
const { user } = useAuthStore();
const [topics, setTopics] = useState<Topic[]>([]);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
async function fetchTopics() {
setRefreshing(true);
try {
const token = await getToken();
const response = await fetch(`${API_URL}/topics/`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error("Failed to fetch topics");
}
const fetchedTopics: Topic[] = await response.json();
setTopics(fetchedTopics);
} catch (error) {
setErrorMsg(
"Error fetching subjects: " +
(error instanceof Error ? error.message : "Unknown error")
);
} finally {
setRefreshing(false);
}
}
useEffect(() => {
const fetchData = async () => {
if (await getToken()) {
fetchTopics();
}
};
fetchData();
}, []);
const onRefresh = async () => {
fetchTopics();
};
if (errorMsg) {
return (
<BackgroundWrapper>
<Header displayTabTitle="Subjects" />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit}
</h1>
<DestructibleAlert text={errorMsg} variant="error" />
</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>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle="Topics" />
<div className="mx-10 pb-20 overflow-y-auto">
<h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit}
</h1>
<div className="border border-[#c0dafc]/50 flex flex-col gap-4 w-full rounded-[20px] p-3">
{topics.length > 0 ? (
topics.map((topic) => (
<div key={topic.topic_id}>
<button
onClick={() =>
router.push(
`/exam/pretest?type=topic&test_id=${topic.topic_id}`
)
}
className="w-full border-1 border-[#B0C2DA] py-3 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-lg font-medium">{topic.name}</h3>
<div className="flex space-x-2">
<p className="text-sm font-normal bg-slate-500 w-fit px-3 py-1 rounded-full text-white">
{topic.subject.name}
</p>
</div>
</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

@ -3,79 +3,46 @@
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
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"; // Using Lucide React for icons
import { ChevronRight } from "lucide-react";
import styles from "@/css/Home.module.css";
import { getLinkedViews } from "@/lib/gallery-views";
import { GalleryViews } from "@/types/gallery";
import { useAuthStore } from "@/stores/authStore";
import DestructibleAlert from "@/components/DestructibleAlert";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000/api";
const page = () => {
const profileImg = "/images/static/avatar.jpg";
const HomePage = () => {
const router = useRouter();
const [boardData, setBoardData] = useState([]);
const [boardError, setBoardError] = useState(null);
const [linkedViews, setLinkedViews] = useState<GalleryViews[]>();
const { user } = useAuthStore();
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 },
];
// Fetch function for leaderboard data
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");
}
}
fetchBoardData();
return () => {
isMounted = false;
};
const fetchedLinkedViews: GalleryViews[] = getLinkedViews();
setLinkedViews(fetchedLinkedViews);
}, []);
const getTopThree = (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,
}));
};
return (
<BackgroundWrapper>
<div className={styles.container}>
<Header displayTabTitle={null} displayUser image={profileImg} />
<div className={styles.scrollContainer}>
<div className={styles.contentWrapper}>
<SlidingGallery />
<div className={styles.mainContent}>
<div className="flex-1 min-h-screen">
<Header displayUser />
<div className="overflow-y-auto pt-4 h-[calc(100vh-80px)]">
<div className="pb-40 mx-6">
{!user?.is_verified && (
<DestructibleAlert
text="Please verify your account. Check your email for the verification link."
variant="warning"
/>
)}
<SlidingGallery views={linkedViews} height="23vh" />
<div className="flex flex-col gap-9">
{/* Categories Section */}
<div>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionTitle}>Categories</h2>
<div className="flex item-scenter justify-between">
<h2 className="text-2xl font-bold text-[#113768]">
Categories
</h2>
<button
onClick={() => router.push("/categories")}
className={styles.arrowButton}
@ -83,69 +50,69 @@ const page = () => {
<ChevronRight size={24} color="#113768" />
</button>
</div>
<div className={styles.categoriesContainer}>
<div className={styles.categoryRow}>
<div className="grid grid-cols-2 gap-4 pt-6 ">
<button
disabled
className={`${styles.categoryButton} ${styles.disabled}`}
onClick={() => router.push("/categories/topics")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/topic-test.png"
alt="Topic Test"
width={70}
height={70}
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]">
Topic Test
</span>
</button>
<button
onClick={() => router.push("/unit")}
className={styles.categoryButton}
onClick={() => router.push("/categories/mocks")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/mock-test.png"
alt="Mock Test"
width={70}
height={70}
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]">
Mock Test
</span>
</button>
</div>
<div className={styles.categoryRow}>
<button
disabled
className={`${styles.categoryButton} ${styles.disabled}`}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/past-paper.png"
alt="Past Papers"
width={62}
height={62}
width={68}
height={68}
className="opacity-50"
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]/50">
Past Papers
</span>
</button>
<button
disabled
className={`${styles.categoryButton} ${styles.disabled}`}
onClick={() => router.push("/categories/subjects")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/subject-test.png"
alt="Subject Test"
width={70}
height={70}
width={80}
height={80}
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]">
Subject Test
</span>
</button>
</div>
</div>
</div>
{/* Leaderboard Section */}
<div className={styles.leaderboardWrapper}>
@ -162,17 +129,14 @@ const page = () => {
</div>
<div className={styles.divider}></div>
<div className={styles.topThreeList}>
{getTopThree(boardData).map((student, idx) => (
{/* {boardError ? (
<DestructibleAlert text={boardError} />
) : (
getTopThree(boardData).map((student, idx) => (
<div key={idx} className={styles.topThreeItem}>
<div className={styles.studentInfo}>
<span className={styles.rank}>{student.rank}</span>
<Image
src="/images/static/avatar.jpg"
alt="Avatar"
width={20}
height={20}
className={styles.avatar}
/>
<Avatar className="bg-slate-300 w-4 h-4 rounded-full" />
<span className={styles.studentName}>
{student.name}
</span>
@ -181,7 +145,9 @@ const page = () => {
{student.points}pt
</span>
</div>
))}
))
)} */}
<h2 className="text-center text-xl">Coming soon</h2>
</div>
</div>
</div>
@ -243,4 +209,4 @@ const page = () => {
);
};
export default page;
export default HomePage;

View File

@ -5,11 +5,20 @@ import Link from "next/link";
import { ReactNode } from "react";
import { usePathname } from "next/navigation";
import clsx from "clsx";
import { GoHomeFill } from "react-icons/go";
import { HiViewGrid } from "react-icons/hi";
import { FaBookmark } from "react-icons/fa";
import { HiCog6Tooth } from "react-icons/hi2";
const tabs = [
{ name: "Home", href: "/tabs/home" },
{ name: "Profile", href: "/tabs/profile" },
{ name: "Leaderboard", href: "/tabs/leaderboard" },
{ name: "Home", href: "/home", component: <GoHomeFill size={30} /> },
{
name: "Categories",
href: "/categories",
component: <HiViewGrid size={30} />,
},
{ name: "Bookmark", href: "/bookmark", component: <FaBookmark size={23} /> },
{ name: "Settings", href: "/settings", component: <HiCog6Tooth size={30} /> },
];
export default function TabsLayout({ children }: { children: ReactNode }) {
@ -19,7 +28,7 @@ export default function TabsLayout({ children }: { children: ReactNode }) {
<div className="min-h-screen flex flex-col">
<main className="flex-1">{children}</main>
<nav className="flex justify-around border-t p-4 bg-white">
<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}
@ -29,7 +38,7 @@ export default function TabsLayout({ children }: { children: ReactNode }) {
pathname === tab.href ? "text-blue-600" : "text-gray-500"
)}
>
{tab.name}
{tab.component}
</Link>
))}
</nav>

View File

@ -0,0 +1,9 @@
"use client";
import React from "react";
const LeaderboardPage = () => {
return <></>;
};
export default LeaderboardPage;

View File

@ -1,7 +1,146 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
import ProfileManager from "@/components/ProfileManager";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { getToken, API_URL } from "@/lib/auth";
import {
BadgeCheck,
ChevronLeft,
Edit2,
Lock,
Save,
ShieldX,
} 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/profile/`, {
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?.username
? userData.username.charAt(0).toUpperCase()
: ""}
</AvatarFallback>
</Avatar>
<div className="pt-14 space-y-4">
{userData?.is_verified ? (
<div className="flex gap-4 justify-center items-center bg-green-200 border border-green-700 px-3 py-4 rounded-2xl ">
<BadgeCheck size={30} />
<p className="text-sm font-semibold text-black">
This account is verified.
</p>
</div>
) : (
<div className="flex gap-2 justify-center items-center bg-red-200 border border-red-700 px-3 py-4 rounded-2xl ">
<ShieldX size={30} />
<p className="text-sm font-semibold text-black">
This account is not verified.
</p>
</div>
)}
<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 page;
export default ProfilePage;

View File

@ -0,0 +1,187 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useAuthStore } from "@/stores/authStore";
import {
BadgeCheck,
Bookmark,
ChartColumn,
ChevronRight,
Clock4,
CreditCard,
Crown,
Globe,
LogOut,
MapPin,
MoveLeft,
Trash2,
UserCircle2,
} from "lucide-react";
import { useRouter } from "next/navigation";
import React from "react";
const SettingsPage = () => {
const router = useRouter();
const { user, logout } = useAuthStore();
function handleLogout() {
logout();
router.replace("/");
}
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 items-center gap-4 bg-blue-100 border-1 border-blue-300/40 rounded-2xl py-5 px-4">
<Avatar className="bg-[#113768] w-20 h-20">
<AvatarFallback className="text-3xl text-white">
{user?.username
? user.username.charAt(0).toUpperCase()
: "User"}
</AvatarFallback>
</Avatar>
<div className="flex flex-col items-start">
<h1 className="font-semibold text-2xl flex gap-1 items-center">
{user?.full_name}
</h1>
<h3 className=" text-md">{user?.email}</h3>
</div>
</section>
<section className="flex flex-col gap-8">
{!user?.is_verified && (
<>
<button
onClick={() => router.push("/settings/verify")}
className="flex justify-between"
>
<div className="flex items-center gap-4">
<BadgeCheck size={30} color="#113768" />
<h3 className="text-md font-medium text-[#113768]">
Verify your account
</h3>
</div>
<ChevronRight size={30} color="#113768" />
</button>
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
</>
)}
<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>
<button onClick={handleLogout} 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" />
</button>
<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;

View File

@ -0,0 +1,93 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "@/components/ui/input-otp";
import { API_URL } from "@/lib/auth";
import Image from "next/image";
import React, { useState } from "react";
const VerificationScreen = () => {
const [otp, setOtp] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleVerify = async () => {
if (otp.length < 6) return;
setLoading(true);
setError(null);
try {
const response = await fetch(`${API_URL}/auth/verify?code=${otp}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Verification failed");
}
// 🔥 Call zustand action to update auth state
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<BackgroundWrapper>
<Header displayTabTitle="Verification" />
<div className="flex flex-col items-center justify-center pt-10 px-6 gap-4">
<Image
src={"/images/icons/otp.svg"}
height={200}
width={300}
alt="otp-banner"
/>
<h1 className="font-medium text-xl text-center ">
Enter the code here that you received in your email.
</h1>
<InputOTP
maxLength={6}
value={otp}
onChange={setOtp}
onComplete={handleVerify} // auto-submit when complete
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
{error && <p className="text-red-500 mt-3">{error}</p>}
<button
onClick={handleVerify}
disabled={otp.length < 6 || loading}
className="mt-6 px-6 py-2 bg-blue-600 text-white rounded-lg disabled:bg-gray-400 transition"
>
{loading ? "Verifying..." : "Verify"}
</button>
</div>
</BackgroundWrapper>
);
};
export default VerificationScreen;

View File

@ -1,63 +0,0 @@
"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-6 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;

View File

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

View File

@ -0,0 +1,133 @@
"use client";
import React, { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Header from "@/components/Header";
import QuestionItem from "@/components/QuestionItem";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { useExamStore } from "@/stores/examStore";
import { useTimerStore } from "@/stores/timerStore";
export default function ExamPage() {
const router = useRouter();
const searchParams = useSearchParams();
const test_id = searchParams.get("test_id") || "";
const type = searchParams.get("type") || "";
const { setStatus, test, answers, startExam, setAnswer, submitExam } =
useExamStore();
const { resetTimer, stopTimer } = useTimerStore();
const [isSubmitting, setIsSubmitting] = useState(false);
// Start exam + timer automatically
useEffect(() => {
if (!type || !test_id) return;
const initExam = async () => {
const fetchedTest = await startExam(type, test_id);
if (!fetchedTest) return;
setStatus("in-progress");
const timeLimit = fetchedTest.metadata.time_limit_minutes;
if (timeLimit) {
resetTimer(timeLimit * 60, async () => {
// Auto-submit when timer ends
stopTimer();
setStatus("finished");
await submitExam(type);
router.replace("/exam/results");
});
}
};
initExam();
return () => {
stopTimer();
};
}, [
type,
test_id,
startExam,
resetTimer,
stopTimer,
submitExam,
router,
setStatus,
]);
if (isSubmitting) {
return (
<div className="min-h-screen bg-gray-50 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 exam...</p>
</div>
);
}
if (!test) {
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">Loading exam...</p>
</div>
</div>
);
}
const handleSubmitExam = async (type: string) => {
setIsSubmitting(true);
stopTimer();
try {
const result = await submitExam(type); // throws if fails
if (!result) throw new Error("Submission failed");
router.replace("/exam/results"); // navigate
} catch (err) {
console.error("Submit exam failed:", err);
alert("Failed to submit exam. Please try again.");
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-screen bg-gray-50">
{/* Header with live timer */}
<Header />
{/* Questions */}
<BackgroundWrapper>
<div className="container mx-auto px-6 py-8 mb-20">
{test.questions.map((q, idx) => (
<div id={`question-${idx}`} key={q.question_id}>
<QuestionItem
question={q}
index={idx}
selectedAnswer={answers[idx]}
onSelect={(answer) => setAnswer(idx, answer)}
/>
</div>
))}
{/* Bottom submit bar */}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex">
<button
onClick={() => handleSubmitExam(type)}
disabled={isSubmitting}
className="flex-1 bg-blue-900 text-white p-6 font-bold text-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-blue-800 transition-colors flex justify-center items-center gap-2"
>
Submit
</button>
</div>
</div>
</BackgroundWrapper>
</div>
);
}

View File

@ -1,7 +1,254 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
};
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import {
ArrowLeft,
HelpCircle,
Clock,
XCircle,
OctagonX,
RotateCw,
} from "lucide-react";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL, getToken } from "@/lib/auth";
import { Metadata } from "@/types/exam";
import { useExamStore } from "@/stores/examStore";
import { FaStar } from "react-icons/fa";
export default page;
function PretestPageContent() {
const router = useRouter();
const searchParams = useSearchParams();
// Get params from URL search params
const id = searchParams.get("test_id") || "";
const type = searchParams.get("type");
const [metadata, setMetadata] = useState<Metadata | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>();
const { setStatus } = useExamStore();
useEffect(() => {
async function fetchQuestions() {
if (!id || !type) return;
try {
setLoading(true);
const token = await getToken();
const questionResponse = await fetch(`${API_URL}/tests/${type}/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${token}`,
},
});
if (!questionResponse.ok) {
throw new Error("Failed to fetch questions");
}
const data = await questionResponse.json();
const fetchedMetadata: Metadata = data.metadata;
setMetadata(fetchedMetadata);
} catch (error) {
console.error(error);
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setLoading(false);
}
}
fetchQuestions();
}, [id, type]);
if (error) {
return (
<BackgroundWrapper>
<div className="min-h-screen mx-10 pt-10 flex flex-col justify-center items-center gap-4">
<div className="flex flex-col justify-center items-center gap-4 w-full">
<DestructibleAlert
text={error}
icon={<OctagonX size={150} color="red" />}
/>
<div className="flex items-center justify-evenly w-full">
<button
onClick={() => router.push(`/categories/${type}s`)}
className="p-4 border border-blue-200 rounded-full bg-blue-400"
>
<ArrowLeft size={35} color="white" />
</button>
<button
onClick={() => router.refresh()}
className="p-4 border border-blue-200 rounded-full bg-red-400"
>
<RotateCw size={35} color="white" />
</button>
</div>
</div>
</div>
</BackgroundWrapper>
);
}
if (loading) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<div className="mx-10 pt-10">
<button
onClick={() => router.push(`/categories/${type}s`)}
className="mb-4"
>
<ArrowLeft size={30} color="black" />
</button>
<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-lg font-medium text-gray-900">Loading...</p>
</div>
</div>
</div>
</BackgroundWrapper>
);
}
function handleStartExam() {
if (!metadata) return;
setStatus("in-progress");
router.push(
`/exam/exam-screen?type=${type}&test_id=${metadata?.test_id}&attempt_id=${metadata?.attempt_id}`
);
}
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-5">
<button onClick={() => router.replace(`/categories/${type}s`)}>
<ArrowLeft size={30} color="black" />
</button>
<h1 className="text-4xl font-semibold text-[#113768]">
{metadata.name}
</h1>
<p className="text-xl font-medium text-[#113768] flex items-center gap-1">
<FaStar size={15} />
<FaStar size={15} />
<FaStar size={15} />
<FaStar size={15} />
</p>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] py-5 px-5 space-y-6">
<div className="flex gap-5 items-center">
<HelpCircle size={52} color="#113768" />
<div className="">
<p className="font-bold text-3xl text-[#113768]">
{metadata.num_questions}
</p>
<p className="font-normal text-md">
Multiple Choice Questions
</p>
</div>
</div>
<div className="flex gap-5 items-center">
<Clock size={52} color="#113768" />
<div className="">
<p className="font-bold text-3xl text-[#113768]">
{String(metadata.time_limit_minutes)} mins
</p>
<p className="font-normal text-md">Time Taken</p>
</div>
</div>
<div className="flex gap-5 items-center">
<XCircle size={52} color="#113768" />
<div className="">
<p className="font-bold text-3xl text-[#113768]">
{metadata.deduction} marks
</p>
<p className="font-normal text-md">
From each wrong answer
</p>
</div>
</div>
</div>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] px-6 py-5 space-y-3">
<h2 className="text-xl font-bold">Ready yourself!</h2>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-medium text-md">
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-medium text-md">
There is no negative marking for the wrong answer.
</p>
</div>
<div className="flex pr-4">
<span className="mx-4"></span>
<p className="font-medium text-md">
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-medium text-md">
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={() => 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>
);
}
export default function PretestPage() {
return (
<Suspense
fallback={
<BackgroundWrapper>
<div className="min-h-screen">
<div className="mx-10 mt-10 flex flex-col justify-center items-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">Loading...</p>
</div>
</div>
</BackgroundWrapper>
}
>
<PretestPageContent />
</Suspense>
);
}

View File

@ -1,7 +1,101 @@
import React from "react";
"use client";
const page = () => {
return <div>page</div>;
};
import { useRouter } from "next/navigation";
import React, { useCallback, useEffect } from "react";
import { ArrowLeft } from "lucide-react";
import { useExamStore } from "@/stores/examStore";
import QuestionItem from "@/components/QuestionItem";
import SlidingGallery from "@/components/SlidingGallery";
import { getResultViews } from "@/lib/gallery-views";
export default page;
export default function ResultsPage() {
const router = useRouter();
const { result, clearResult, setStatus, status } = useExamStore();
const handleBackToHome = useCallback(() => {
clearResult();
router.replace("/categories");
}, [clearResult, router]);
useEffect(() => {
const handlePopState = () => {
if (status !== "finished") {
handleBackToHome();
}
};
window.addEventListener("popstate", handlePopState);
return () => {
window.removeEventListener("popstate", handlePopState);
};
}, [status, router, setStatus, handleBackToHome]);
if (!result) {
return (
<div className="min-h-screen flex items-center justify-center">
<p className="text-lg font-medium">Redirecting...</p>
</div>
);
}
const views = getResultViews(result);
return (
<div className="min-h-screen bg-white">
<button className="px-10 pt-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] text-center">
You did great!
</h1>
<SlidingGallery views={views} height={"26vh"} />
{/* Render questions with correctness */}
{result.user_questions.map((q, idx) => {
const userAnswer = result.user_answers[idx];
const correctAnswer = result.correct_answers[idx];
return (
<div key={q.question_id} className="rounded-3xl mb-6">
<QuestionItem
question={q}
index={idx}
selectedAnswer={userAnswer}
onSelect={() => {}}
userAnswer={userAnswer}
correctAnswer={correctAnswer}
showResults={true}
/>
{/* Optional answer feedback below the question */}
{/* <div className="mt-2 text-sm">
{userAnswer === null ? (
<span className="text-yellow-600 font-medium">
Skipped — Correct: {String.fromCharCode(65 + correctAnswer)}
</span>
) : userAnswer === correctAnswer ? (
<span className="text-green-600 font-medium">Correct</span>
) : (
<span className="text-red-600 font-medium">
Your Answer: {String.fromCharCode(65 + userAnswer)} |
Correct Answer: {String.fromCharCode(65 + correctAnswer)}
</span>
)}
</div> */}
</div>
);
})}
</div>
<button
onClick={handleBackToHome}
className="fixed bottom-0 w-full bg-blue-900 text-white h-[74px] font-bold text-lg hover:bg-blue-800 transition-colors"
>
Finish
</button>
</div>
);
}

View File

@ -1,8 +1,9 @@
import type { Metadata } from "next";
import { Montserrat } from "next/font/google";
import "./globals.css";
import { AuthProvider } from "@/context/AuthContext";
import { TimerProvider } from "@/context/TimerContext";
import { Providers } from "./providers";
import AuthInitializer from "@/components/AuthInitializer";
const montserrat = Montserrat({
subsets: ["latin"],
@ -13,7 +14,7 @@ const montserrat = Montserrat({
export const metadata: Metadata = {
title: "ExamJam",
description: "Your exam preparation platform",
description: "The best place to prepare for your exams!",
};
export default function RootLayout({
@ -24,9 +25,9 @@ export default function RootLayout({
return (
<html lang="en" className={montserrat.variable}>
<body className="font-sans">
<TimerProvider>
<AuthProvider>{children}</AuthProvider>
</TimerProvider>
<AuthInitializer>
<Providers>{children}</Providers>
</AuthInitializer>
</body>
</html>
);

View File

@ -3,34 +3,10 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { useState, useEffect } from "react";
import BackgroundWrapper from "@/components/BackgroundWrapper";
export default function Home() {
const router = useRouter();
const [windowDimensions, setWindowDimensions] = useState({
width: 0,
height: 0,
});
useEffect(() => {
function handleResize() {
setWindowDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Set initial dimensions
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const handleLogin = () => {
router.push("/login");
};
return (
<BackgroundWrapper>
@ -62,7 +38,7 @@ export default function Home() {
{/* Action Buttons */}
<div className="flex flex-col gap-4">
<button
onClick={handleLogin}
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
@ -77,7 +53,7 @@ export default function Home() {
className="text-center font-medium"
style={{ fontFamily: "Montserrat, sans-serif" }}
>
Don't have an account?{" "}
Don&apos;t have an account?
<Link href="/register" className="text-[#276ac0] hover:underline">
Register here
</Link>

7
app/providers.tsx Normal file
View File

@ -0,0 +1,7 @@
"use client";
import { ModalProvider } from "@/context/ModalContext";
export function Providers({ children }: { children: React.ReactNode }) {
return <ModalProvider>{children}</ModalProvider>;
}

28
bash.exe.stackdump Normal file
View File

@ -0,0 +1,28 @@
Stack trace:
Frame Function Args
0007FFFFB730 00021006118E (00021028DEE8, 000210272B3E, 0007FFFFB730, 0007FFFFA630) msys-2.0.dll+0x2118E
0007FFFFB730 0002100469BA (000000000000, 000000000000, 000000000000, 0007FFFFBA08) msys-2.0.dll+0x69BA
0007FFFFB730 0002100469F2 (00021028DF99, 0007FFFFB5E8, 0007FFFFB730, 000000000000) msys-2.0.dll+0x69F2
0007FFFFB730 00021006A41E (000000000000, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x2A41E
0007FFFFB730 00021006A545 (0007FFFFB740, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x2A545
0007FFFFBA10 00021006B9A5 (0007FFFFB740, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x2B9A5
End of stack trace
Loaded modules:
000100400000 bash.exe
7FFA7B7E0000 ntdll.dll
7FFA7A000000 KERNEL32.DLL
7FFA78C70000 KERNELBASE.dll
7FFA7A690000 USER32.dll
7FFA79000000 win32u.dll
7FFA79860000 GDI32.dll
7FFA79490000 gdi32full.dll
7FFA79280000 msvcp_win.dll
000210040000 msys-2.0.dll
7FFA79160000 ucrtbase.dll
7FFA79630000 advapi32.dll
7FFA7B240000 msvcrt.dll
7FFA7B090000 sechost.dll
7FFA79890000 RPCRT4.dll
7FFA784C0000 CRYPTBASE.DLL
7FFA795B0000 bcryptPrimitives.dll
7FFA79FC0000 IMM32.DLL

BIN
bun.lockb

Binary file not shown.

9
capacitor.config.ts Normal file
View File

@ -0,0 +1,9 @@
import type { CapacitorConfig } from "@capacitor/cli";
const config: CapacitorConfig = {
appId: "com.examjam.omukk",
appName: "ExamJam",
webDir: "out",
};
export default config;

21
components.json Normal file
View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@ -0,0 +1,49 @@
"use client";
import { useEffect } from "react";
import { useAuthStore } from "@/stores/authStore";
import { useRouter, usePathname } from "next/navigation";
export default function AuthInitializer({
children,
}: {
children: React.ReactNode;
}) {
const { initializeAuth, token, hydrated } = useAuthStore();
const router = useRouter();
const pathname = usePathname();
// 1⃣ Run initialization once
useEffect(() => {
initializeAuth();
}, [initializeAuth]);
// 2⃣ Run routing logic only after hydration
useEffect(() => {
if (!hydrated) return;
const publicPages = ["/", "/login", "/register"];
if (token) {
if (publicPages.includes(pathname)) {
router.replace("/home");
}
} else {
if (!publicPages.includes(pathname)) {
router.replace("/login");
}
}
}, [pathname, token, hydrated, router]);
// 3⃣ Show loading until hydrated
if (!hydrated) {
return (
<div className="min-h-screen flex flex-col justify-center items-center gap-3">
<div className="animate-spin rounded-full h-20 w-20 border-b-2 border-blue-500"></div>
<p className="text-2xl font-semibold tracking-tighter">Loading...</p>
</div>
);
}
return <>{children}</>;
}

View File

@ -1,6 +1,10 @@
import React from "react";
import React, { ReactNode } from "react";
const BackgroundWrapper = ({ children }) => {
interface BackgroundWrapperProps {
children: ReactNode;
}
const BackgroundWrapper = ({ children }: BackgroundWrapperProps) => {
return (
<div
className="min-h-screen bg-cover bg-center bg-no-repeat relative"
@ -10,9 +14,7 @@ const BackgroundWrapper = ({ children }) => {
>
<div
className="min-h-screen"
style={{
backgroundColor: "rgba(0, 0, 0, 0)", // Optional overlay - adjust opacity as needed
}}
style={{ backgroundColor: "rgba(0, 0, 0, 0)" }}
>
{children}
</div>

View File

@ -1,33 +1,35 @@
import React from "react";
import React, { JSX } from "react";
const DestructibleAlert = ({
text,
extraStyles = "",
}: {
interface DestructibleAlertProps {
variant?: "error" | "warning" | "alert";
text: string;
extraStyles?: string;
icon?: JSX.Element;
}
const DestructibleAlert: React.FC<DestructibleAlertProps> = ({
variant,
text,
icon,
}) => {
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,
}}
className={`${
variant === "error"
? "bg-red-200"
: variant === "warning"
? "bg-yellow-200"
: "bg-green-200"
} rounded-3xl py-6 flex flex-col items-center justify-center gap-2 w-full `}
>
<div>{icon}</div>
<p
className="text-center text-red-800"
style={{
fontSize: 17,
lineHeight: "28px",
fontFamily: "Montserrat, sans-serif",
fontWeight: "bold",
textAlign: "center",
color: "#991b1b",
}}
className={`text-lg font-bold text-center ${
variant === "error"
? "text-red-800"
: variant === "warning"
? "text-yellow-800"
: "text-green-800"
}`}
>
{text}
</p>

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
);
}

View File

@ -1,73 +1,61 @@
import React, { useState } from "react";
import React, { useState, useId, InputHTMLAttributes } from "react";
const FormField = ({
interface FormFieldProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "onChange"> {
title: string;
value: string | number;
placeholder?: string;
handleChangeText: (value: string) => void;
}
const FormField: React.FC<FormFieldProps> = ({
title,
placeholder,
value,
placeholder,
handleChangeText,
type,
...props
}) => {
const [showPassword, setShowPassword] = useState(false);
const inputId = useId();
const isPasswordField = title === "Password" || title === "Confirm Password";
const isPasswordField =
type === "password" || title.toLowerCase().includes("password");
const inputType = isPasswordField
? showPassword
? "text"
: "password"
: type || "text";
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",
}}
htmlFor={inputId}
className="block mb-2 text-[#666666] text-[18px] font-medium font-montserrat tracking-[-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,
}}
>
<div className="h-16 px-4 bg-[#D2DFF0] rounded-3xl flex items-center justify-between">
<input
type={isPasswordField && !showPassword ? "password" : "text"}
id={inputId}
type={inputType}
value={value}
placeholder={placeholder}
placeholder={placeholder || `Enter ${title.toLowerCase()}`}
autoComplete={isPasswordField ? "current-password" : "on"}
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",
}}
className="flex-1 bg-transparent outline-none border-none text-blue-950 text-[16px] font-inherit"
{...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,
}}
onClick={() => setShowPassword((prev) => !prev)}
aria-pressed={showPassword}
aria-label={showPassword ? "Hide password" : "Show password"}
className="ml-2 text-gray-600 hover:text-gray-800 focus:outline-none font-montserrat font-medium text-[16px]"
>
{showPassword ? "Hide" : "Show"}
</button>

View File

@ -1,90 +1,38 @@
import React, { useState, useEffect } from "react";
"use client";
import React from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { ChevronLeft, Layers } from "lucide-react";
import { useTimer } from "@/context/TimerContext";
import styles from "@/css/Header.module.css";
import { ChevronLeft, Layers, RefreshCcw } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useModal } from "@/context/ModalContext";
import { useAuthStore } from "@/stores/authStore";
import { useTimerStore } from "@/stores/timerStore";
import { useExamStore } from "@/stores/examStore";
import { BsPatchCheckFill } from "react-icons/bs";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000/api";
// You'll need to implement getToken for Next.js - could use cookies, localStorage, etc.
const getToken = async () => {
// Replace with your token retrieval logic
if (typeof window !== "undefined") {
return localStorage.getItem("token") || sessionStorage.getItem("token");
}
return null;
};
interface HeaderProps {
displayUser?: boolean;
displaySubject?: string;
displayTabTitle?: string;
}
const Header = ({
image,
displayUser,
displaySubject,
displayTabTitle,
examDuration,
}) => {
}: HeaderProps) => {
const router = useRouter();
const [totalSeconds, setTotalSeconds] = useState(
examDuration ? parseInt(examDuration) * 60 : 0
);
const { timeRemaining, stopTimer } = useTimer();
const [userData, setUserData] = useState(null);
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 { open } = useModal();
const { cancelExam } = useExamStore();
const { stopTimer, timeRemaining } = useTimerStore();
const { user } = useAuthStore();
const showExitDialog = () => {
const confirmed = window.confirm("Are you sure you want to quit the exam?");
if (confirmed) {
if (stopTimer) {
stopTimer();
}
router.push("/unit");
cancelExam();
router.replace("/categories");
}
};
@ -92,71 +40,96 @@ const Header = ({
router.back();
};
return (
<header className={styles.header}>
{displayUser && (
<div className={styles.profile}>
{image && (
<Image
src={image}
alt="Profile"
width={40}
height={40}
className={styles.profileImg}
/>
)}
<span className={styles.text}>
Hello {userData?.name ? userData.name.split(" ")[0] : ""}
</span>
</div>
)}
// format time from context
const hours = Math.floor(timeRemaining / 3600);
const minutes = Math.floor((timeRemaining % 3600) / 60);
const seconds = timeRemaining % 60;
{displaySubject && (
<div className={styles.profile}>
<button onClick={handleBackClick} className={styles.iconButton}>
<ChevronLeft size={24} color="white" />
</button>
<span className={styles.text}>{displaySubject}</span>
return (
<header className="bg-[#113768] h-[100px] w-full pt-7 px-6 flex items-center justify-between sticky top-0 z-50">
{displayUser && (
<div className="flex items-center gap-3">
<Avatar className="bg-gray-200 w-10 h-10">
<AvatarFallback className="flex items-center justify-center h-10 text-lg">
{user?.username ? (
user.username.charAt(0).toUpperCase()
) : (
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
)}
</AvatarFallback>
</Avatar>
<span className="text-md font-bold text-white flex items-center gap-2">
Hello, {user?.username ? user.username.split(" ")[0] : "User"}{" "}
<BsPatchCheckFill size={20} color="white" />
</span>
</div>
)}
{displayTabTitle && (
<div className={styles.profile}>
<span className={styles.text}>{displayTabTitle}</span>
<div className="flex justify-between items-center w-full">
<div className="flex items-center gap-3">
<button
onClick={handleBackClick}
className="bg-none border-none p-1"
>
<ChevronLeft size={24} color="white" />
</button>
<span className="text-md font-bold text-white">
{displayTabTitle}
</span>
</div>
</div>
)}
{examDuration && (
<div className={styles.examHeader}>
<button onClick={showExitDialog} className={styles.iconButton}>
{displaySubject && (
<div className="flex items-center gap-3">
<span className="text-md font-bold text-white">{displaySubject}</span>
</div>
)}
{/* Exam timer header */}
{timeRemaining > 0 && (
<div className="flex justify-between w-full items-center">
<button
onClick={showExitDialog}
className="bg-none border-none cursor-pointer p-1 flex items-center justify-center"
>
<ChevronLeft size={30} color="white" />
</button>
<div className={styles.timer}>
<div className={styles.timeUnit}>
<span className={styles.timeValue}>
<div className="w-40 h-14 bg-white flex justify-around items-center rounded-2xl ">
<div className="flex flex-col items-center w-full">
<span className="font-medium text-md text-[#082E5E]">
{String(hours).padStart(2, "0")}
</span>
<span className={styles.timeLabel}>Hrs</span>
<span className="font-medium text-[12px] text-[#082E5E]">
Hrs
</span>
</div>
<div className={styles.timeUnit}>
<span className={styles.timeValue}>
<div className="flex flex-col items-center w-full">
<span className="font-medium text-md text-[#082E5E]">
{String(minutes).padStart(2, "0")}
</span>
<span className={styles.timeLabel}>Mins</span>
<span className="font-medium text-[12px] text-[#082E5E]">
Mins
</span>
</div>
<div className={styles.timeUnit}>
<span className={styles.timeValue}>
<div
className="flex flex-col items-center w-full"
style={{ borderRight: "none" }}
>
<span className="font-medium text-md text-[#082E5E]">
{String(seconds).padStart(2, "0")}
</span>
<span className={styles.timeLabel}>Secs</span>
<span className="font-medium text-[12px] text-[#082E5E]">
Secs
</span>
</div>
</div>
<button
disabled
onClick={() => router.push("/exam/modal")}
className={`${styles.iconButton} ${styles.disabled}`}
onClick={open}
className="bg-none border-none cursor-pointer p-1 flex items-center justify-center"
>
<Layers size={30} color="white" />
</button>

View File

@ -0,0 +1,207 @@
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { UserData } from "@/types/auth";
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 | number) => {
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
};
return (
<div className="mx-auto">
<div className="space-y-4">
{/* Full Name */}
<h1 className="text-xl font-semibold tracking-tight">
Personal Information
</h1>
<div className="space-y-2">
<Label
htmlFor="full_name"
className="text-sm font-semibold text-gray-700"
>
Full Name
</Label>
<Input
id="full_name"
type="text"
value={userData.full_name}
onChange={(e) => handleChange("full_name", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2">
<Label
htmlFor="username"
className="text-sm font-semibold text-gray-700"
>
Username
</Label>
<Input
id="username"
type="text"
value={userData.username}
onChange={(e) => handleChange("username", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
{/* SSC & HSC Rolls */}
{/* Email */}
<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>
{/* Phone */}
<div className="space-y-2">
<Label
htmlFor="phone_number"
className="text-sm font-semibold text-gray-700"
>
Phone
</Label>
<Input
id="phone_number"
type="tel"
value={userData.phone_number}
onChange={(e) => handleChange("phone_number", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<h1 className="text-xl tracking-tight font-semibold">
Educational Background
</h1>
<div className="space-y-2">
<Label
htmlFor="preparation_unit"
className="text-sm font-semibold text-gray-700"
>
Unit
</Label>
<Input
id="preparation_unit"
type="text"
value={userData.preparation_unit}
onChange={(e) => handleChange("preparation_unit", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2">
<Label
htmlFor="college"
className="text-sm font-semibold text-gray-700"
>
College
</Label>
<Input
id="college"
type="text"
value={userData.college}
onChange={(e) => handleChange("college", 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="ssc_roll"
className="text-sm font-semibold text-gray-700"
>
SSC Roll
</Label>
<Input
id="ssc_roll"
type="number"
value={userData.ssc_roll}
onChange={(e) => handleChange("ssc_roll", Number(e.target.value))}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2 w-full">
<Label
htmlFor="ssc_board"
className="text-sm font-semibold text-gray-700"
>
SSC Board
</Label>
<Input
id="ssc_board"
type="text"
value={userData.ssc_board}
onChange={(e) => handleChange("ssc_board", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
</div>
<div className="flex gap-4">
<div className="space-y-2 w-full">
<Label
htmlFor="hsc_roll"
className="text-sm font-semibold text-gray-700"
>
HSC Roll
</Label>
<Input
id="hsc_roll"
type="number"
value={userData.hsc_roll}
onChange={(e) => handleChange("hsc_roll", Number(e.target.value))}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
<div className="space-y-2 w-full">
<Label
htmlFor="hsc_board"
className="text-sm font-semibold text-gray-700"
>
HSC Board
</Label>
<Input
id="hsc_board"
type="text"
value={userData.hsc_board}
onChange={(e) => handleChange("hsc_board", e.target.value)}
className="bg-gray-50 py-6"
readOnly={!edit}
/>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,83 @@
"use client";
import React from "react";
import { Question, Answer } from "@/types/exam";
import { Bookmark } from "lucide-react";
interface QuestionItemProps {
question: Question;
index: number;
selectedAnswer: Answer;
onSelect: (answer: Answer) => void;
userAnswer?: Answer;
correctAnswer?: Answer;
showResults?: boolean;
}
const letters = ["A", "B", "C", "D"]; // extend if needed
const QuestionItem: React.FC<QuestionItemProps> = ({
question,
index,
selectedAnswer,
onSelect,
userAnswer,
correctAnswer,
showResults = false,
}) => {
return (
<div className="border border-blue-100 p-6 bg-slate-100 rounded-3xl mb-6">
<p className="text-lg font-semibold mb-3">
{index + 1}. {question.question}
</p>
{!showResults && (
<div className="w-full flex justify-between">
<div></div>
<Bookmark size={24} />
</div>
)}
<div className="flex flex-col gap-3">
{question.options.map((opt, optIdx) => {
const isSelected = selectedAnswer === optIdx;
// ✅ logic for coloring
let btnClasses = "bg-gray-100 text-gray-900 border-gray-400";
if (isSelected) {
btnClasses = "bg-blue-600 text-white border-blue-600";
}
if (showResults && correctAnswer !== undefined) {
if (userAnswer === optIdx && userAnswer !== correctAnswer) {
btnClasses = "bg-red-500 text-white border-red-600"; // wrong
}
if (correctAnswer === optIdx) {
btnClasses = "bg-green-500 text-white border-green-600"; // correct
}
}
return (
<div key={optIdx} className="flex items-center gap-3">
<button
onClick={() => {
if (showResults) return; // disable selection in results mode
onSelect(optIdx); // always a number
}}
className={`w-7 h-7 rounded-full border font-bold
flex items-center justify-center
${btnClasses}
transition-colors`}
>
{letters[optIdx]}
</button>
<span className="text-gray-900">{opt}</span>
</div>
);
})}
</div>
</div>
);
};
export default QuestionItem;

View File

@ -1,69 +1,183 @@
import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import styles from "../css/SlidingGallery.module.css";
import React, {
useState,
useRef,
useEffect,
useCallback,
UIEvent,
} from "react";
import { GalleryViews } from "@/types/gallery";
const views = [
{
id: "1",
content: (
<Link
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
className={styles.link}
>
<div className={styles.facebook}>
<div className={styles.textView}>
<h3 className={styles.facebookOne}>Meet, Share, and Learn!</h3>
<p className={styles.facebookTwo}>Join Facebook Community</p>
</div>
<div className={styles.logoView}>
<Image
src="/images/static/facebook-logo.png"
alt="Facebook Logo"
width={120}
height={120}
/>
</div>
</div>
</Link>
),
},
];
interface SlidingGalleryProps {
views: GalleryViews[] | undefined;
className?: string;
showPagination?: boolean;
autoScroll?: boolean;
autoScrollInterval?: number;
onSlideChange?: (currentIndex: number) => void;
height?: string | number;
}
const SlidingGallery = () => {
const [activeIdx, setActiveIdx] = useState(0);
const scrollRef = useRef(null);
const SlidingGallery = ({
views,
className = "",
showPagination = true,
autoScroll = false,
autoScrollInterval = 5000,
onSlideChange = () => {},
height = "100vh",
}: SlidingGalleryProps) => {
const [activeIdx, setActiveIdx] = useState<number>(0);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const handleScroll = (event) => {
const scrollLeft = event.target.scrollLeft;
const slideWidth = event.target.clientWidth;
const scrollRef = useRef<HTMLDivElement | null>(null);
const galleryRef = useRef<HTMLDivElement | null>(null);
const autoScrollRef = useRef<NodeJS.Timeout | null>(null);
const handleScroll = (event: UIEvent<HTMLDivElement>) => {
handleUserInteraction();
const scrollLeft = event.currentTarget.scrollLeft;
const slideWidth = dimensions.width;
const index = Math.round(scrollLeft / slideWidth);
if (index !== activeIdx) {
setActiveIdx(index);
onSlideChange(index);
}
};
const goToSlide = useCallback(
(index: number) => {
if (scrollRef.current) {
scrollRef.current.scrollTo({
left: index * dimensions.width,
behavior: "smooth",
});
}
},
[dimensions.width]
);
const handleDotClick = (index: number) => {
handleUserInteraction();
goToSlide(index);
setActiveIdx(index);
onSlideChange(index);
};
// Auto-scroll functionality
useEffect(() => {
if (autoScroll && views && 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, goToSlide, views]);
// Clear auto-scroll on user interaction
const handleUserInteraction = () => {
if (autoScrollRef.current) {
clearInterval(autoScrollRef.current);
autoScrollRef.current = null;
}
};
// Update dimensions
useEffect(() => {
const updateDimensions = () => {
if (galleryRef.current) {
setDimensions({
width: galleryRef.current.clientWidth,
height: galleryRef.current.clientHeight,
});
}
};
updateDimensions();
window.addEventListener("resize", updateDimensions);
return () => window.removeEventListener("resize", updateDimensions);
}, []);
// Recalculate index when dimension changes
useEffect(() => {
if (scrollRef.current && dimensions.width > 0) {
const scrollLeft = scrollRef.current.scrollLeft;
const slideWidth = dimensions.width;
const index = Math.round(scrollLeft / slideWidth);
setActiveIdx(index);
}
}, [dimensions]);
if (!views || views.length === 0) {
return (
<div className={styles.gallery}>
<div
className={styles.scrollContainer}
className={`relative w-full h-screen overflow-hidden flex flex-col ${className}`}
>
<div className="flex-1 flex items-center justify-center text-slate-400 text-lg">
<p>No content to display</p>
</div>
</div>
);
}
return (
<div
className={`relative w-full h-screen overflow-hidden flex flex-col ${className}`}
ref={galleryRef}
style={{ height }}
>
<div
className="flex-1 flex overflow-x-auto"
ref={scrollRef}
onScroll={handleScroll}
style={{
width: "100%",
height: "100%",
overflowX: "scroll",
display: "flex",
scrollSnapType: "x mandatory",
scrollbarWidth: "none",
msOverflowStyle: "none",
}}
>
{views.map((item) => (
<div key={item.id} className={styles.slide}>
<div
key={item.id}
className="min-w-full flex items-center justify-center px-2 box-border"
style={{
width: dimensions.width,
height: "100%",
flexShrink: 0,
scrollSnapAlign: "start",
}}
>
{item.content}
</div>
))}
</div>
<div className={styles.pagination}>
{showPagination && views.length > 1 && (
<div className="absolute bottom-[15px] left-1/2 -translate-x-1/2 flex gap-1.5 z-10">
{views.map((_, index) => (
<div
key={index}
className={`${styles.dot} ${
activeIdx === index ? styles.activeDot : styles.inactiveDot
className={`w-2 h-2 rounded-full transition-all duration-300 ease-in ${
activeIdx === index ? "bg-[#113768]" : "bg-[#b1d3ff]"
}`}
onClick={() => handleDotClick(index)}
/>
))}
</div>
)}
</div>
);
};

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 }

View File

@ -0,0 +1,77 @@
"use client";
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { MinusIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string;
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-otp-group"
className={cn("flex items-center", className)}
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number;
}) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-14 w-14 items-center justify-center border-y border-r text-lg font-bold shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

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 }

View File

@ -1,109 +0,0 @@
"use client";
import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter } 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();
// 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");
if (storedToken) {
setTokenState(storedToken);
// Only redirect if we're on login/register pages
if (
router.pathname === "/" ||
router.pathname === "/login" ||
router.pathname === "/register"
) {
router.replace("/home");
}
} else {
// Only redirect to login if we're on a protected page
const publicPages = ["/", "/login", "/register"];
if (!publicPages.includes(router.pathname)) {
router.replace("/");
}
}
setIsLoading(false);
};
// Small delay to ensure router is ready
const timer = setTimeout(initializeAuth, 100);
return () => clearTimeout(timer);
}, [router.pathname]);
// 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;
};

41
context/ModalContext.tsx Normal file
View File

@ -0,0 +1,41 @@
"use client";
import { createContext, useContext, useState } from "react";
// Define the context type
interface ModalContextType {
isOpen: boolean;
open: () => void;
close: () => void;
toggle: () => void;
}
// Create context with default values (no null)
const ModalContext = createContext<ModalContextType>({
isOpen: false,
open: () => {},
close: () => {},
toggle: () => {},
});
export function ModalProvider({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false);
const open = () => setIsOpen(true);
const close = () => setIsOpen(false);
const toggle = () => setIsOpen((prev) => !prev);
const value: ModalContextType = {
isOpen,
open,
close,
toggle,
};
return (
<ModalContext.Provider value={value}>{children}</ModalContext.Provider>
);
}
export function useModal(): ModalContextType {
return useContext(ModalContext);
}

View File

@ -1,70 +0,0 @@
"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;
};

View File

@ -29,7 +29,7 @@
}
.text {
font-size: 24px;
font-size: 20px ;
font-family: 'Montserrat', sans-serif;
font-weight: 700;
color: #fff;
@ -79,6 +79,8 @@
display: flex;
flex-direction: column;
align-items: center;
border-right: 1px solid #000;
width: 100%;
}
.timeValue {
@ -133,14 +135,14 @@
@media (max-width: 480px) {
.header {
height: 80px;
height: 100px;
padding-top: 15px;
padding-left: 15px;
padding-right: 15px;
}
.text {
font-size: 14px;
font-size: 17px;
}
.profile {
@ -148,22 +150,22 @@
}
.profileImg {
width: 30px;
height: 30px;
width: 40px;
height: 40px;
}
.timer {
width: 120px;
height: 40px;
width: 180px;
height: 60px;
padding: 0 5px;
}
.timeValue {
font-size: 14px;
font-size: 18px;
}
.timeLabel {
font-size: 10px;
font-size: 12px;
}
.examHeader {

View File

@ -70,6 +70,7 @@
.categoriesContainer {
display: flex;
flex-direction: column;
justify-content: space-evenly;
gap: 16px;
padding-top: 25px;
}
@ -228,7 +229,7 @@
}
.categoryButtonText {
font-size: 12px;
font-size: 14px;
}
.categoryRow {
@ -246,11 +247,11 @@
}
.sectionTitle {
font-size: 18px;
font-size: 22px;
}
.categoryButton {
height: 100px;
height: 200px;
}
.mainContent {
@ -258,7 +259,7 @@
}
.categoryRow {
flex-direction: column;
flex-direction: row;
}
.categoryButton {

View File

@ -1,119 +0,0 @@
.gallery {
height: 200px;
width: 100%;
border: 1px solid #113768;
border-radius: 25px;
position: relative;
overflow: hidden;
}
.scrollContainer {
display: flex;
height: 100%;
overflow-x: auto;
scroll-behavior: smooth;
scroll-snap-type: x mandatory;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* Internet Explorer 10+ */
}
.scrollContainer::-webkit-scrollbar {
display: none; /* WebKit */
}
.slide {
min-width: calc(100% - 72px);
display: flex;
justify-content: center;
align-items: center;
scroll-snap-align: start;
padding: 0 36px;
}
.link {
text-decoration: none;
color: inherit;
width: 100%;
}
.facebook {
flex: 1;
display: flex;
justify-content: space-between;
flex-direction: row;
height: 100%;
background-color: #fff;
border-radius: 25px;
padding: 20px;
box-sizing: border-box;
}
.facebookOne {
font-family: 'Montserrat', sans-serif;
font-weight: 900;
color: #113768;
font-size: 20px;
margin: 0;
}
.facebookTwo {
font-family: 'Montserrat', sans-serif;
font-weight: 600;
color: #113768;
font-size: 13px;
margin: 0;
}
.pagination {
display: flex;
flex-direction: row;
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.dot {
width: 10px;
height: 10px;
border-radius: 5px;
margin: 0 5px;
}
.activeDot {
background-color: #113768;
}
.inactiveDot {
background-color: #ccc;
}
.textView {
width: 60%;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.logoView {
width: 40%;
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.slide {
min-width: calc(100% - 40px);
padding: 0 20px;
}
.facebookOne {
font-size: 18px;
}
.facebookTwo {
font-size: 12px;
}
}

View File

@ -11,6 +11,15 @@ const compat = new FlatCompat({
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
rules: {
// Disable the no-explicit-any rule
"@typescript-eslint/no-explicit-any": "off",
// Alternative: Make it a warning instead of error
// "@typescript-eslint/no-explicit-any": "warn",
},
},
];
export default eslintConfig;

41
hooks/useNavGuard.ts Normal file
View File

@ -0,0 +1,41 @@
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { useExamStore } from "@/stores/examStore";
import { useTimerStore } from "@/stores/timerStore";
export function useNavGuard(type: string) {
const { status, setStatus, cancelExam } = useExamStore();
const router = useRouter();
const { stopTimer } = useTimerStore();
// Guard page render: always redirect if status invalid
useEffect(() => {
if (status !== "in-progress") {
router.replace(`/categories/${type}s`);
}
}, [status, router, type]);
// Confirm before leaving page / tab close
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (status === "in-progress") {
e.preventDefault();
e.returnValue = ""; // shows native browser dialog
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [status]);
// Call this to quit exam manually
const showExitDialog = () => {
if (window.confirm("Are you sure you want to quit the exam?")) {
setStatus("finished");
stopTimer();
cancelExam();
router.replace(`/categories/${type}s`);
}
};
return { showExitDialog };
}

View File

@ -1,21 +1,43 @@
export const API_URL = "https://examjam-api.pptx704.com";
import { LoginForm, RegisterForm } from "@/types/auth";
// Cookie utility functions
const setCookie = (name, value, days = 7) => {
export const API_URL = process.env.NEXT_PUBLIC_EXAMJAM_API_URL;
// Cookie utility function
const setCookie = (name: string, value: string | null, days: number = 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`;
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax;`; //SameSite=Strict; Secure in production
} 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`;
document.cookie = `${name}=${encodeURIComponent(
value
)}; expires=${expires.toUTCString()}; path=/; SameSite=Lax;`; //SameSite=Strict; Secure in production
}
};
export const login = async (form, setToken) => {
const response = await fetch(`${API_URL}/auth/login`, {
export const getToken = async (): Promise<string | null> => {
if (typeof window === "undefined") {
return null;
}
const match = document.cookie.match(/(?:^|;\s*)authToken=([^;]*)/);
return match ? decodeURIComponent(match[1]) : null;
};
type SetTokenFn = (token: string) => void;
// Optional: Create a custom error type to carry extra data
interface APIError extends Error {
response?: any;
}
export const login = async (
form: LoginForm,
setToken: SetTokenFn
): Promise<void> => {
const response = await fetch(`${API_URL}/auth/login/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -29,28 +51,15 @@ export const login = async (form, setToken) => {
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
setToken(data.token);
};
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`, {
export const register = async (
form: RegisterForm,
setToken: SetTokenFn
): Promise<void> => {
const response = await fetch(`${API_URL}/auth/register/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -58,33 +67,14 @@ export const register = async (form, setToken) => {
body: JSON.stringify(form),
});
const data = await response.json(); // Parse the response JSON
const data = await 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
const error: APIError = new Error(data?.detail || "Registration failed");
error.response = data;
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);
setToken(data.token);
};

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

@ -0,0 +1,130 @@
// lib/gallery-views.tsx
import Link from "next/link";
import Image from "next/image";
import { GalleryViews } from "@/types/gallery";
import { ExamResult } from "@/types/exam";
export const getResultViews = (examResults: ExamResult | 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.correct_answers_count /
examResults.user_questions.length) *
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.user_questions.length -
examResults.correct_answers_count) /
examResults.user_questions.length) *
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.user_answers.length /
examResults.user_questions.length) *
100
).toFixed(1)
: "0"}
%
</h2>
</div>
</div>
</div>
),
},
];
export const getLinkedViews = (): GalleryViews[] => [
{
id: 1,
content: (
<Link
href="https://www.facebook.com/share/g/15jdqESvWV/?mibextid=wwXIfr"
className=" block"
>
<div className="w-full h-full p-6 flex text-black bg-blue-50 rounded-3xl 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 }] : [];
};

38
lib/utils.ts Normal file
View File

@ -0,0 +1,38 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
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);
}
};

View File

@ -1,7 +1,5 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
const nextConfig: NextConfig = {};
export default nextConfig;

4045
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,19 +4,32 @@
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"build": "next build ",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"build:export": "npx next build && npm run export"
},
"dependencies": {
"@capacitor/android": "^7.4.2",
"@capacitor/core": "^7.4.2",
"@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",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"input-otp": "^1.4.2",
"lucide-react": "^0.523.0",
"next": "15.3.2",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"react-dom": "^19.0.0",
"react-icons": "^5.5.0",
"tailwind-merge": "^3.3.1",
"uuid": "^11.1.0",
"zustand": "^5.0.8"
},
"devDependencies": {
"@capacitor/cli": "^7.4.2",
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",

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"
}
}
]

175
public/data/questions.json Normal file
View File

@ -0,0 +1,175 @@
{
"questions": [
{
"correct_answer": "Assets = Liabilities + Equity",
"difficulty": "Easy",
"explanation": "This is the basic accounting equation.",
"is_randomized": true,
"options": [
"Assets = Liabilities + Equity",
"Assets = Revenue - Expenses",
"Assets = Liabilities - Equity",
"Assets = Equity - Liabilities"
],
"question": "What is the basic accounting equation?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "a1b2c3d4-e5f6-7890-abcd-1234567890ab",
"type": "Single"
},
{
"correct_answer": "Balance Sheet",
"difficulty": "Easy",
"explanation": "A balance sheet shows a company's assets, liabilities, and equity at a specific point in time.",
"is_randomized": true,
"options": [
"Balance Sheet",
"Income Statement",
"Cash Flow Statement",
"Statement of Retained Earnings"
],
"question": "Which financial statement shows a company's assets, liabilities, and equity?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "b2c3d4e5-f678-9012-abcd-2345678901bc",
"type": "Single"
},
{
"correct_answer": "Revenue - Expenses",
"difficulty": "Easy",
"explanation": "Net income is calculated by subtracting expenses from revenue.",
"is_randomized": true,
"options": [
"Revenue - Expenses",
"Assets - Liabilities",
"Equity + Liabilities",
"Revenue + Expenses"
],
"question": "How is net income calculated?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "c3d4e5f6-7890-1234-abcd-3456789012cd",
"type": "Single"
},
{
"correct_answer": "Accounts Receivable",
"difficulty": "Easy",
"explanation": "Accounts receivable represents money owed to a company by its customers.",
"is_randomized": true,
"options": [
"Accounts Receivable",
"Accounts Payable",
"Inventory",
"Prepaid Expenses"
],
"question": "Which account represents money owed to a company by its customers?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "d4e5f678-9012-3456-abcd-4567890123de",
"type": "Single"
},
{
"correct_answer": "Depreciation",
"difficulty": "Medium",
"explanation": "Depreciation is the allocation of the cost of a tangible asset over its useful life.",
"is_randomized": true,
"options": [
"Depreciation",
"Amortization",
"Depletion",
"Appreciation"
],
"question": "What is the allocation of the cost of a tangible asset over its useful life called?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "e5f67890-1234-5678-abcd-5678901234ef",
"type": "Single"
},
{
"correct_answer": "Accrual Basis",
"difficulty": "Medium",
"explanation": "Accrual basis accounting recognizes revenues and expenses when they are incurred, not when cash is exchanged.",
"is_randomized": true,
"options": [
"Accrual Basis",
"Cash Basis",
"Modified Cash Basis",
"Tax Basis"
],
"question": "Which accounting method recognizes revenues and expenses when they are incurred, regardless of when cash is exchanged?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "f6789012-3456-7890-abcd-6789012345fa",
"type": "Single"
},
{
"correct_answer": "Liabilities",
"difficulty": "Easy",
"explanation": "Liabilities are obligations that a company owes to outside parties.",
"is_randomized": true,
"options": [
"Liabilities",
"Assets",
"Equity",
"Revenue"
],
"question": "What are obligations that a company owes to outside parties called?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "a7890123-4567-8901-abcd-7890123456ab",
"type": "Single"
},
{
"correct_answer": "Double-entry",
"difficulty": "Medium",
"explanation": "Double-entry accounting means every transaction affects at least two accounts.",
"is_randomized": true,
"options": [
"Double-entry",
"Single-entry",
"Triple-entry",
"Quadruple-entry"
],
"question": "What is the accounting system called where every transaction affects at least two accounts?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "b8901234-5678-9012-abcd-8901234567bc",
"type": "Single"
},
{
"correct_answer": "Owner's Equity",
"difficulty": "Easy",
"explanation": "Owner's equity represents the owner's claims to the assets of the business.",
"is_randomized": true,
"options": [
"Owner's Equity",
"Liabilities",
"Revenue",
"Expenses"
],
"question": "What is the owner's claim to the assets of a business called?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "c9012345-6789-0123-abcd-9012345678cd",
"type": "Single"
},
{
"correct_answer": "Matching Principle",
"difficulty": "Medium",
"explanation": "The matching principle requires that expenses be matched with related revenues.",
"is_randomized": true,
"options": [
"Matching Principle",
"Revenue Recognition Principle",
"Cost Principle",
"Conservatism Principle"
],
"question": "Which accounting principle requires that expenses be matched with related revenues?",
"source_type": "Mock",
"subject_id": "f1c1d54a-0b29-44e2-8f95-ecf9f9e6d8b7",
"topic_id": "d0123456-7890-1234-abcd-0123456789de",
"type": "Single"
}
]
}

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

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

147
stores/authStore.ts Normal file
View File

@ -0,0 +1,147 @@
"use client";
import { create } from "zustand";
import { LoginForm, RegisterForm, UserData } from "@/types/auth";
import { API_URL } from "@/lib/auth";
// Cookie utilities
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) {
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`;
}
};
interface APIError extends Error {
response?: any;
}
interface AuthState {
token: string | null;
isLoading: boolean;
hydrated: boolean;
user: UserData | null;
error: string | null;
login: (form: LoginForm) => Promise<void>;
register: (form: RegisterForm) => Promise<void>;
setToken: (token: string | null) => void;
logout: () => void;
initializeAuth: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set, get) => ({
token: null,
isLoading: true,
hydrated: false,
error: null,
user: null,
setToken: (newToken) => {
set({ token: newToken });
setCookie("authToken", newToken);
},
login: async (form: LoginForm) => {
set({ isLoading: true, error: null });
try {
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");
}
const token = data.token;
setCookie("authToken", token);
set({ token });
// Automatically fetch user info after login
const userRes = await fetch(`${API_URL}/me/profile/`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!userRes.ok) {
throw new Error("Failed to fetch user info after login");
}
const userData: UserData = await userRes.json();
set({ user: userData, isLoading: false });
} catch (err: any) {
console.error("Login error:", err);
set({
error: err?.message || "Login failed",
isLoading: false,
});
throw err;
}
},
register: async (form: RegisterForm) => {
set({ isLoading: true, error: null });
try {
const response = await fetch(`${API_URL}/auth/register/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
const data = await response.json();
if (!response.ok) {
const error: APIError = new Error(
data?.detail || "Registration failed"
);
error.response = data;
throw error;
}
setCookie("authToken", data.token);
set({ token: data.token, isLoading: false });
} catch (err: any) {
set({
error: err?.message || "Registration failed",
isLoading: false,
});
throw err;
}
},
logout: () => {
set({ token: null, user: null });
setCookie("authToken", null);
},
initializeAuth: async () => {
const storedToken = getCookie("authToken");
if (storedToken) {
set({ token: storedToken });
}
set({ isLoading: false, hydrated: true });
},
}));

106
stores/examStore.ts Normal file
View File

@ -0,0 +1,106 @@
"use client";
import { create } from "zustand";
import { Test, Answer } from "@/types/exam";
import { API_URL, getToken } from "@/lib/auth";
import { ExamResult } from "@/types/exam";
type ExamStatus = "not-started" | "in-progress" | "finished";
interface ExamState {
test: Test | null;
answers: Answer[];
result: ExamResult | null;
status: ExamStatus;
setStatus: (status: ExamStatus) => void;
startExam: (testType: string, testId: string) => Promise<Test | null>;
setAnswer: (questionIndex: number, answer: Answer) => void;
submitExam: (testType: string) => Promise<ExamResult | null>;
cancelExam: () => void;
clearResult: () => void;
}
export const useExamStore = create<ExamState>((set, get) => ({
test: null,
answers: [],
result: null,
status: "not-started",
setStatus: (status) => set({ status }),
// start exam
startExam: async (testType: string, testId: string) => {
try {
const token = await getToken();
const res = await fetch(`${API_URL}/tests/${testType}/${testId}`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!res.ok) throw new Error(`Failed to fetch test: ${res.status}`);
const data: Test = await res.json();
set({
test: data,
answers: Array(data.questions.length).fill(null),
result: null, // clear old result
});
return data;
} catch (err) {
console.error("startExam error:", err);
return null;
}
},
// set an answer
setAnswer: (questionIndex: number, answer: Answer) => {
set((state) => {
const updated = [...state.answers];
updated[questionIndex] = answer;
return { answers: updated };
});
},
// submit exam
submitExam: async (testType: string) => {
const { test, answers } = get();
if (!test) throw new Error("No test to submit");
const token = await getToken();
const { test_id, attempt_id } = test.metadata;
const res = await fetch(
`${API_URL}/tests/${testType}/${test_id}/${attempt_id}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ answers }),
}
);
if (!res.ok) throw new Error("Failed to submit exam");
const result: ExamResult = await res.json();
// save result only
set({ result });
return result;
},
// cancel exam
cancelExam: () => {
set({ test: null, answers: [], result: null });
},
// clear result manually (e.g., when leaving results page)
clearResult: () => {
set({ result: null });
},
}));

48
stores/timerStore.ts Normal file
View File

@ -0,0 +1,48 @@
"use client";
import { create } from "zustand";
interface TimerState {
timeRemaining: number;
timerRef: NodeJS.Timeout | null;
resetTimer: (duration: number, onComplete?: () => void) => void;
stopTimer: () => void;
setInitialTime: (duration: number) => void;
}
export const useTimerStore = create<TimerState>((set, get) => ({
timeRemaining: 0,
timerRef: null,
resetTimer: (duration, onComplete) => {
const { timerRef } = get();
if (timerRef) clearInterval(timerRef);
const newRef = setInterval(() => {
set((state) => {
if (state.timeRemaining <= 1) {
clearInterval(newRef);
if (onComplete) onComplete(); // ✅ call callback when timer ends
return { timeRemaining: 0, timerRef: null };
}
return { timeRemaining: state.timeRemaining - 1 };
});
}, 1000);
set({ timeRemaining: duration, timerRef: newRef });
},
stopTimer: () => {
const { timerRef } = get();
if (timerRef) clearInterval(timerRef);
set({ timeRemaining: 0, timerRef: null });
},
setInitialTime: (duration) => {
const { timerRef } = get();
if (timerRef) clearInterval(timerRef);
set({ timeRemaining: duration, timerRef: null });
},
}));

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

@ -0,0 +1,33 @@
export interface UserData {
user_id: string;
username: string;
full_name: string;
email: string;
is_verified: boolean;
phone_number: string;
ssc_roll: number;
ssc_board: string;
hsc_roll: number;
hsc_board: string;
college: string;
preparation_unit: "Science" | "Humanities" | "Business" | string;
}
export interface RegisterForm {
full_name: string;
username: string;
email: string;
password: string;
phone_number: string;
ssc_roll: number;
ssc_board: string;
hsc_roll: number;
hsc_board: string;
college: string;
preparation_unit: "Science" | "Humanities" | "Business" | string;
}
export interface LoginForm {
identifier: string;
password: string;
}

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

@ -0,0 +1,43 @@
export interface Metadata {
attempt_id: string;
test_id: string;
type: string;
total_possible_score: number;
deduction?: string;
num_questions: number;
name: string;
start_time: string; // keep ISO string for consistency
time_limit_minutes?: number;
}
export type Question = {
question_id: string;
question: string;
options: string[];
type: "Single" | "Multiple";
};
export interface Test {
metadata: Metadata;
questions: Question[];
}
export type Answer = number | null;
export type AnswersMap = Record<string, Answer>;
export interface ExamResult {
user_id: string;
test_id: string;
subject_id: string;
topic_id: string;
test_type: string;
attempt_id: string;
start_time: string;
end_time: string;
user_questions: Question[];
user_answers: (number | null)[];
correct_answers: number[];
correct_answers_count: number;
wrong_answers_count: number;
skipped_questions_count: number;
}

4
types/gallery.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
export interface GalleryViews {
id: number;
content: React.JSX.Element;
}