import BreadCrumb from "../../../../components/dashboard/common/BreadCrumb";
import CopyrightFooter from "../../../../components/dashboard/common/CopyrightFooter";
import Seo from "../../../../components/common/Seo";
import PsychometricQuestion from "../../../../components/dashboard/candidate-dashboard/psychometric-test/PsychometricQuestion";
import { useState, useEffect, useRef, useCallback } from "react";
import PsychometricSidebar from "../../../../components/header/PsychometricSidebar";
import PsychometricHeader from "../../../../components/header/PsychometricHeader";
import { usePsychometricApi } from "../../../../utils/hooks/usePsychometricApi";
import { useAuth } from "../../../../contexts/auth";
import { useRouter } from "next/router";
import Swal from "sweetalert2";

interface Answer {
  questionId: number;
  optionId: string | number;
}

interface Topic {
  id: number;
  name: string;
}

const sanitizeAnswersByQuestions = (
  rawAnswers: Answer[],
  questions: any[],
): Answer[] => {
  if (!Array.isArray(rawAnswers) || !Array.isArray(questions)) return [];

  const validQuestionIds = new Set(
    questions
      .map((q) => Number(q?.id))
      .filter((id) => Number.isFinite(id) && id > 0),
  );

  const latestByQuestionId = new Map<number, string | number>();
  rawAnswers.forEach((answer) => {
    const questionId = Number(answer?.questionId);
    const optionId = answer?.optionId;
    const hasValidOptionId =
      (typeof optionId === "number" &&
        Number.isFinite(optionId) &&
        optionId > 0) ||
      (typeof optionId === "string" && optionId.trim().length > 0);

    if (
      Number.isFinite(questionId) &&
      questionId > 0 &&
      validQuestionIds.has(questionId) &&
      hasValidOptionId
    ) {
      latestByQuestionId.set(questionId, optionId);
    }
  });

  return Array.from(latestByQuestionId.entries()).map(
    ([questionId, optionId]) => ({
      questionId,
      optionId,
    }),
  );
};

const QuestionPage: React.FC = () => {
  const [getIsSidebarOpen, setIsSidebarOpen] = useState(false);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState<Answer[]>([]);
  const [questions, setQuestions] = useState<any[]>([]);
  const [topics, setTopics] = useState<Topic[]>([]);
  const [currentTopicId, setCurrentTopicId] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [performanceId, setPerformanceId] = useState<number | null>(null);
  const [examDuration, setExamDuration] = useState<number | null>(null);

  const {
    getTest,
    submitTest,
    startTest,
    saveExamAnswers,
    loadExamAnswers,
    clearExamAnswers,
  } = usePsychometricApi();
  const {
    isAuthenticated,
    loading: authLoading,
    userRole,
    user,
  } = useAuth() as any;
  const router = useRouter();

  // Ref to prevent duplicate timer setup
  const timerStartedRef = useRef(false);

  // Refs for latest state values — prevents stale closures in timer callback
  const answersRef = useRef<Answer[]>([]);
  const performanceIdRef = useRef<number | null>(null);

  // Refs for functions that may change between renders — prevents timer reset
  const submitTestRef = useRef(submitTest);
  const clearExamAnswersRef = useRef(clearExamAnswers);
  const routerRef = useRef(router);
  const hasSubmittedRef = useRef(false);
  const isExitSubmittingRef = useRef(false);

  // Keep function refs in sync without triggering timer re-setup
  useEffect(() => {
    submitTestRef.current = submitTest;
  }, [submitTest]);

  useEffect(() => {
    clearExamAnswersRef.current = clearExamAnswers;
  }, [clearExamAnswers]);

  useEffect(() => {
    routerRef.current = router;
  }, [router]);

  // Keep data refs in sync
  useEffect(() => {
    answersRef.current = answers;
  }, [answers]);

  useEffect(() => {
    performanceIdRef.current = performanceId;
  }, [performanceId]);

  const buildSubmitPayload = useCallback(() => {
    const currentAnswers = sanitizeAnswersByQuestions(
      answersRef.current,
      questions,
    );
    const answersObject: Record<string, string | number> = {};
    currentAnswers.forEach((a) => {
      answersObject[String(a.questionId)] = a.optionId;
    });

    const currentPerformanceId = performanceIdRef.current;
    const testId = Number(routerRef.current.query.id);
    if (currentPerformanceId) {
      return {
        performanceId: currentPerformanceId,
        answers: answersObject,
      };
    }

    return {
      psychometricExamId: testId,
      answers: answersObject,
    };
  }, [questions]);

  const submitOnExit = useCallback(() => {
    if (hasSubmittedRef.current || isExitSubmittingRef.current) return;
    if (!routerRef.current?.isReady) return;
    if (loading || error) return;

    const payload = buildSubmitPayload();
    const hasAtLeastOneAnswer = Object.keys(payload.answers || {}).length > 0;
    if (!hasAtLeastOneAnswer) return;

    hasSubmittedRef.current = true;
    isExitSubmittingRef.current = true;

    try {
      submitTestRef.current(payload as any).catch(() => {});

      clearExamAnswersRef.current("psychometric");
    } catch {
      // ignore — page is closing
    }
  }, [buildSubmitPayload, error, loading]);

  // Fetch test questions from backend using hook
  useEffect(() => {
    if (authLoading) return;
    if (!router.isReady) return;

    if (!isAuthenticated) {
      router.push("/login");
      return;
    }

    // Check if user is a candidate
    if (userRole && userRole.toLowerCase() !== "candidate") {
      router.push("/dashboard");
      return;
    }

    const { id: testId } = router.query;
    if (!testId) {
      setError("Invalid test ID.");
      setLoading(false);
      return;
    }

    const loadQuestions = async () => {
      try {
        setLoading(true);
        setError(null);
        console.log("Fetching test", testId, "questions from backend...");

        const testData = await getTest(Number(testId));
        console.log("Fetched test data:", testData);

        // Extract questions
        let questionsArray = testData?.questions || [];
        if (!questionsArray || questionsArray.length === 0) {
          questionsArray =
            testData?.psychometricQuestionLibrary?.questions || [];
        }

        if (!questionsArray || questionsArray.length === 0) {
          setError("No questions found in this test.");
          setLoading(false);
          return;
        }

        setQuestions(questionsArray);

        // Extract duration if available
        if (testData?.duration) {
          console.log("[examDuration] Set to:", testData.duration);
          setExamDuration(testData.duration);
        }

        // Try to start the test to get a performanceId required by backend
        try {
          const startResp = await startTest({
            psychometricExamId: Number(testId),
          });
          // startResp should include performanceId
          const pid = startResp?.performanceId ?? null;
          console.log("startTest response:", startResp, "performanceId:", pid);
          if (pid) {
            setPerformanceId(Number(pid));
            console.log("Successfully set performanceId:", pid);
          }

          // Also check if startResp contains duration
          if (startResp?.exam?.duration && !testData?.duration) {
            console.log(
              "[examDuration] Set from startTest:",
              startResp.exam.duration,
            );
            setExamDuration(startResp.exam.duration);
          }
        } catch (startErr: any) {
          console.error("startTest failed - full error:", startErr);
          console.error("startTest error response:", startErr?.response?.data);
          await Swal.fire({
            icon: "error",
            title: "Failed to start test",
            text: startErr?.response?.data?.message || startErr?.message,
          });
        }

        // Extract unique topics from questions
        const topicsMap = new Map<string, Topic>();
        let topicIdCounter = 1;

        questionsArray.forEach((question: any) => {
          const topicName = question.topic;

          if (topicName && typeof topicName === "string") {
            if (!topicsMap.has(topicName)) {
              topicsMap.set(topicName, {
                id: topicIdCounter++,
                name: topicName,
              });
            }
          }
        });

        const uniqueTopics = Array.from(topicsMap.values());
        console.log("Extracted topics:", uniqueTopics);
        setTopics(uniqueTopics);

        // Set current topic based on first question
        if (questionsArray.length > 0 && questionsArray[0].topic) {
          const firstTopicName = questionsArray[0].topic;
          const firstTopic = topicsMap.get(firstTopicName);
          if (firstTopic) {
            setCurrentTopicId(firstTopic.id);
          }
        }
      } catch (err: any) {
        console.error("Failed to load questions:", err);

        let errorMessage = "Failed to load test questions. Please try again.";
        if (err?.response?.data?.errors?.[0]?.message) {
          errorMessage = err.response.data.errors[0].message;
        } else if (err?.response?.data?.message) {
          errorMessage = err.response.data.message;
        } else if (err?.message) {
          errorMessage = err.message;
        }

        setError(errorMessage);
      } finally {
        setLoading(false);
      }
    };

    loadQuestions();
  }, [authLoading, isAuthenticated, router.isReady, router.query]);

  // Load saved answers when questions are loaded
  useEffect(() => {
    if (questions.length > 0) {
      const testId = Number(router.query.id);
      const savedAnswers = loadExamAnswers(testId, "psychometric", user?.id);
      if (savedAnswers) {
        console.log("Loading saved psychometric answers:", savedAnswers);
        // Convert saved answers object to Answer array format
        const answersArray: Answer[] = Object.entries(savedAnswers).map(
          ([questionId, optionId]) => ({
            questionId: Number(questionId),
            optionId: optionId as string | number,
          }),
        );
        setAnswers(sanitizeAnswersByQuestions(answersArray, questions));
      }
    }
  }, [questions.length, router.query.id, user?.id, loadExamAnswers]);

  // Save answers to localStorage whenever answers change
  useEffect(() => {
    const sanitizedAnswers = sanitizeAnswersByQuestions(answers, questions);
    if (sanitizedAnswers.length > 0) {
      const testId = Number(router.query.id);
      const answersObject: Record<string, any> = {};
      sanitizedAnswers.forEach((answer) => {
        answersObject[String(answer.questionId)] = answer.optionId;
      });
      saveExamAnswers(
        testId,
        "psychometric",
        answersObject,
        performanceId || undefined,
        user?.id,
      );
    }
  }, [
    answers,
    questions,
    router.query.id,
    performanceId,
    user?.id,
    saveExamAnswers,
  ]);

  // Update current topic when question changes
  useEffect(() => {
    if (
      questions.length > 0 &&
      questions[currentQuestionIndex] &&
      topics.length > 0
    ) {
      const currentQuestion = questions[currentQuestionIndex];
      const topicName = currentQuestion.topic;

      if (topicName && typeof topicName === "string") {
        const matchedTopic = topics.find((t) => t.name === topicName);
        if (matchedTopic) {
          setCurrentTopicId(matchedTopic.id);
        }
      }
    }
  }, [currentQuestionIndex, questions, topics]);

  // Auto-submit when candidate exits in between exam.
  useEffect(() => {
    if (!router.isReady) return;

    const handleBeforeUnload = () => {
      submitOnExit();
    };

    const handlePageHide = () => {
      submitOnExit();
    };

    const handleRouteChangeStart = (url: string) => {
      const currentPath = router.asPath || "";
      if (url !== currentPath) {
        submitOnExit();
      }
    };

    window.addEventListener("beforeunload", handleBeforeUnload);
    window.addEventListener("pagehide", handlePageHide);
    router.events.on("routeChangeStart", handleRouteChangeStart);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
      window.removeEventListener("pagehide", handlePageHide);
      router.events.off("routeChangeStart", handleRouteChangeStart);
    };
  }, [router, submitOnExit]);

  // Anti-cheat: Auto-submit when candidate switches tabs
  useEffect(() => {
    if (!router.isReady || loading || error) return;

    const handleVisibilityChange = () => {
      if (document.hidden) {
        console.log(
          "[Anti-cheat] Tab switch detected — auto-submitting psychometric exam",
        );
        submitOnExit();
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [router.isReady, loading, error, submitOnExit]);

  // Anti-cheat: Fullscreen enforcement
  useEffect(() => {
    if (!router.isReady || loading || error || questions.length === 0) return;

    // Request fullscreen when exam loads
    const requestFullscreen = async () => {
      try {
        if (!document.fullscreenElement) {
          await document.documentElement.requestFullscreen();
          console.log("[Anti-cheat] Entered fullscreen mode");
        }
      } catch (err) {
        console.warn("[Anti-cheat] Fullscreen request failed:", err);
        // Don't block the exam if fullscreen is denied (e.g., mobile browsers)
      }
    };

    requestFullscreen();

    const handleFullscreenChange = () => {
      if (!document.fullscreenElement && !hasSubmittedRef.current) {
        console.log(
          "[Anti-cheat] Exited fullscreen — auto-submitting psychometric exam",
        );
        submitOnExit();
      }
    };

    document.addEventListener("fullscreenchange", handleFullscreenChange);

    return () => {
      document.removeEventListener("fullscreenchange", handleFullscreenChange);
      // Exit fullscreen on cleanup (unmount)
      if (document.fullscreenElement) {
        document.exitFullscreen().catch(() => {});
      }
    };
  }, [router.isReady, loading, error, questions.length, submitOnExit]);

  // Auto-submission when time is up.
  //
  // Only depends on `examDuration` — all other values accessed via refs so
  // the timer is never reset by re-renders in production. timerStartedRef
  // prevents a second timer even if examDuration changes after being set.
  useEffect(() => {
    if (!examDuration || examDuration <= 0 || timerStartedRef.current) return;

    timerStartedRef.current = true;
    console.log(
      `[Timer] Started — will fire in ${examDuration} minute(s) (${examDuration * 60 * 1000} ms)`,
    );

    const timer = setTimeout(
      async () => {
        console.log("[Timer] Fired — auto-submitting exam");

        await Swal.fire({
          icon: "info",
          title: "Time's Up!",
          text: "The exam time has expired. Your answers will be submitted automatically.",
          timer: 3000,
          showConfirmButton: false,
        });

        // Read latest values from refs — never stale
        const currentAnswers = answersRef.current;
        const currentPerformanceId = performanceIdRef.current;
        const testId = Number(routerRef.current.query.id);

        try {
          if (hasSubmittedRef.current) {
            return;
          }
          hasSubmittedRef.current = true;
          setSubmitting(true);

          const sanitizedAnswers = sanitizeAnswersByQuestions(
            currentAnswers,
            questions,
          );
          const answersObject: Record<string, string | number> = {};
          sanitizedAnswers.forEach((a) => {
            answersObject[String(a.questionId)] = a.optionId;
          });

          let payload: any = { answers: answersObject };

          if (currentPerformanceId) {
            payload.performanceId = currentPerformanceId;
          } else {
            payload.psychometricExamId = testId;
          }

          console.log("[Timer] Auto-submitting with payload:", payload);

          // Use refs so this closure never captures stale function references
          const result = await submitTestRef.current(payload as any);

          clearExamAnswersRef.current("psychometric");

          const submittedPerformanceId =
            (result as any)?.performance?.id ??
            (result as any)?.data?.performance?.id ??
            (result as any)?.id ??
            currentPerformanceId ??
            null;

          if (submittedPerformanceId) {
            routerRef.current.push(
              `/dashboard/psychometic-test/result?performanceId=${submittedPerformanceId}`,
            );
          } else {
            routerRef.current.push(`/dashboard/psychometic-test/result`);
          }
        } catch (err: any) {
          hasSubmittedRef.current = false;
          console.error("[Timer] Auto-submit failed:", err);
          await Swal.fire({
            icon: "error",
            title: "Submission Error",
            text: "Failed to submit your exam automatically. Please try submitting manually.",
          });
          setSubmitting(false);
        }
      },
      examDuration * 60 * 1000,
    );

    return () => {
      console.log("[Timer] Cleared on unmount");
      clearTimeout(timer);
    };
  }, [examDuration]); // eslint-disable-line react-hooks/exhaustive-deps
  // ^ Intentionally omitting router, submitTest, clearExamAnswers etc. from
  //   deps — they are accessed via refs above to prevent timer resets.

  const handleAnswerChange = (
    questionId: number,
    optionId: string | number,
  ) => {
    setAnswers((prevAnswers) => {
      const updatedAnswers = [...prevAnswers];
      const answerIndex = updatedAnswers.findIndex(
        (answer) => answer.questionId === questionId,
      );

      if (answerIndex > -1) {
        updatedAnswers[answerIndex] = { questionId, optionId };
      } else {
        updatedAnswers.push({ questionId, optionId });
      }

      return updatedAnswers;
    });
  };

  const handleNextQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
    }
  };

  const handlePreviousQuestion = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(currentQuestionIndex - 1);
    }
  };

  const handleTopicClick = (topicId: number) => {
    // Find the first question with this topic
    const topicToFind = topics.find((t) => t.id === topicId);
    if (!topicToFind) return;

    const firstQuestionIndex = questions.findIndex(
      (q) => q.topic === topicToFind.name,
    );
    if (firstQuestionIndex !== -1) {
      setCurrentQuestionIndex(firstQuestionIndex);
      setCurrentTopicId(topicId);
    }
  };

  const handleSubmit = async () => {
    try {
      const isSure = await Swal.fire({
        title: "Submit Test?",
        text: "Are you sure you want to submit your answers? You won't be able to change them after submission.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes, submit!",
        cancelButtonText: "Cancel",
      });
      if (!isSure.isConfirmed) {
        return;
      }

      if (hasSubmittedRef.current) {
        return;
      }
      hasSubmittedRef.current = true;
      setSubmitting(true);
      console.log("Submitting test with answers:", answers);

      const testId = Number(router.query.id);
      const sanitizedAnswers = sanitizeAnswersByQuestions(answers, questions);
      const answersObject: Record<string, string | number> = {};
      sanitizedAnswers.forEach((a) => {
        answersObject[String(a.questionId)] = a.optionId;
      });

      // Try submitting with performanceId if available, otherwise use exam ID
      let payload: any = {
        answers: answersObject,
      };

      if (performanceId) {
        payload.performanceId = performanceId;
      } else {
        // Backend may accept psychometricExamId or examId instead
        payload.psychometricExamId = testId;
      }

      const result = await submitTest(payload as any);

      // Clear localStorage answers after successful submission
      clearExamAnswers("psychometric");

      const submittedPerformanceId =
        (result as any)?.performance?.id ??
        (result as any)?.data?.performance?.id ??
        (result as any)?.id ??
        performanceId ??
        null;

      if (submittedPerformanceId) {
        router.push(
          `/dashboard/psychometic-test/result?performanceId=${submittedPerformanceId}`,
        );
      } else {
        router.push(`/dashboard/psychometic-test/result`);
      }
    } catch (err: any) {
      hasSubmittedRef.current = false;
      console.error("Failed to submit test:", err);
      const message =
        err?.response?.data?.errors?.[0]?.message ||
        err?.message ||
        "Failed to submit test. Please try again.";
      await Swal.fire({
        icon: "error",
        title: "Submission Failed",
        text: message,
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <>
        <Seo pageTitle="Loading Test" />
        <div className="page-wrapper dashboard psychometric_questions_wrapper">
          <span className="header-span"></span>
          <PsychometricHeader />
          <PsychometricSidebar
            activeId={currentTopicId}
            topics={topics}
            getIsSidebarOpen={getIsSidebarOpen}
            setIsSidebarOpen={setIsSidebarOpen}
            onTopicClick={handleTopicClick}
          />
          <section className="user-dashboard">
            <div className="dashboard-outer">
              <div className="row">
                <div className="col-lg-12">
                  <div className="ls-widget">
                    <div className="tabs-box">
                      <div className="widget-content text-center py-8">
                        <div className="spinner mb-4"></div>
                        <p>Loading test questions...</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
          <CopyrightFooter />
        </div>
      </>
    );
  }

  if (error || questions.length === 0) {
    return (
      <>
        <Seo pageTitle="Error - Test" />
        <div className="page-wrapper dashboard psychometric_questions_wrapper">
          <span className="header-span"></span>
          <PsychometricHeader />
          <PsychometricSidebar
            activeId={currentTopicId}
            topics={topics}
            getIsSidebarOpen={getIsSidebarOpen}
            setIsSidebarOpen={setIsSidebarOpen}
            onTopicClick={handleTopicClick}
          />
          <section className="user-dashboard">
            <div className="dashboard-outer">
              <BreadCrumb
                title="Psychometric Test"
                getIsSidebarOpen={getIsSidebarOpen}
                setIsSidebarOpen={setIsSidebarOpen}
              />
              <div className="row">
                <div className="col-lg-12">
                  <div className="ls-widget">
                    <div className="tabs-box">
                      <div className="widget-content">
                        <div className="alert alert-danger">
                          {error || "No questions available"}
                        </div>
                        <button
                          className="theme-btn btn-style-one d-inline-block"
                          onClick={() => router.back()}
                        >
                          Go Back
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
          <CopyrightFooter />
        </div>
      </>
    );
  }

  const currentQuestion = questions[currentQuestionIndex];
  const answeredCount = sanitizeAnswersByQuestions(answers, questions).length;
  const progressPercent =
    questions.length > 0
      ? Math.round(((currentQuestionIndex + 1) / questions.length) * 100)
      : 0;
  const isAnswered = answers.some((a) => a.questionId === currentQuestion?.id);

  // Get the selected answer for the current question
  const currentAnswer = answers.find(
    (a) => a.questionId === currentQuestion?.id,
  );

  return (
    <>
      <Seo pageTitle={`Question ${currentQuestionIndex + 1}`} />
      <div className="page-wrapper dashboard psychometric_questions_wrapper">
        <span className="header-span"></span>
        <PsychometricHeader />
        <PsychometricSidebar
          activeId={currentTopicId}
          topics={topics}
          getIsSidebarOpen={getIsSidebarOpen}
          setIsSidebarOpen={setIsSidebarOpen}
          onTopicClick={handleTopicClick}
          examDuration={examDuration}
        />
        <section className="user-dashboard">
          <div className="dashboard-outer">
            <BreadCrumb
              title="Psychometric Test"
              getIsSidebarOpen={getIsSidebarOpen}
              setIsSidebarOpen={setIsSidebarOpen}
            />
            <div className="row">
              <div className="col-lg-12">
                <div className="ls-widget">
                  <div className="tabs-box">
                    {/* Progress Section */}
                    <div className="mb-4">
                      <div
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                          marginBottom: "8px",
                        }}
                      >
                        <span style={{ fontSize: "14px", fontWeight: "600" }}>
                          Progress
                        </span>
                        <span style={{ fontSize: "14px", fontWeight: "600" }}>
                          {progressPercent}%
                        </span>
                      </div>
                      <div
                        style={{
                          width: "100%",
                          backgroundColor: "#e0e0e0",
                          borderRadius: "8px",
                          height: "8px",
                        }}
                      >
                        <div
                          style={{
                            backgroundColor: "#146e79ff",
                            height: "8px",
                            borderRadius: "8px",
                            width: `${progressPercent}%`,
                            transition: "width 0.3s ease",
                          }}
                        ></div>
                      </div>
                    </div>

                    {/* Question Title */}
                    <div className="widget-title">
                      <h4>
                        Question {currentQuestionIndex + 1} of{" "}
                        {questions.length}
                        {isAnswered && (
                          <span
                            style={{ color: "#28a839ff", marginLeft: "8px" }}
                          >
                            ✓
                          </span>
                        )}
                      </h4>
                    </div>

                    {/* Question Content */}
                    <div className="widget-content">
                      {currentQuestion && (
                        <PsychometricQuestion
                          question={currentQuestion}
                          questionNo={currentQuestionIndex + 1}
                          onAnswerChange={handleAnswerChange}
                          selectedAnswer={currentAnswer?.optionId}
                        />
                      )}

                      {/* Navigation Buttons */}
                      <div
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                          paddingTop: "24px",
                          paddingBottom: "24px",
                          gap: "12px",
                          flexWrap: "wrap",
                        }}
                      >
                        <button
                          className="theme-btn btn-style-one d-inline-block"
                          onClick={handlePreviousQuestion}
                          disabled={currentQuestionIndex === 0}
                          style={{
                            opacity: currentQuestionIndex === 0 ? 0.6 : 1,
                            cursor:
                              currentQuestionIndex === 0
                                ? "not-allowed"
                                : "pointer",
                          }}
                        >
                          Previous
                        </button>
                        {currentQuestionIndex < questions.length - 1 ? (
                          <button
                            className="theme-btn btn-style-one d-inline-block"
                            onClick={handleNextQuestion}
                          >
                            Next
                          </button>
                        ) : (
                          <button
                            className="theme-btn btn-style-one d-inline-block bg-green-600 hover:bg-green-700"
                            onClick={handleSubmit}
                            disabled={submitting || answeredCount === 0}
                          >
                            {submitting ? "Submitting..." : "Submit Test"}
                          </button>
                        )}
                      </div>

                      {/* Answered Questions Indicator */}
                      <p style={{ fontSize: "14px", fontWeight: "600" }}>
                        Answered: {answeredCount} of {questions.length}{" "}
                        questions
                      </p>
                      <div
                        style={{
                          width: "100%",
                          backgroundColor: "#e0e0e0",
                          borderRadius: "8px",
                          height: "8px",
                          marginTop: "8px",
                        }}
                      >
                        <div
                          style={{
                            backgroundColor: "#28a745",
                            height: "8px",
                            borderRadius: "8px",
                            width: `${(answeredCount / questions.length) * 100}%`,
                          }}
                        ></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
        <CopyrightFooter />
      </div>
    </>
  );
};

export default QuestionPage;
