"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { Question, QuizAnswer, QuizAttempt, QuizTheme, QuizMode } from "@/types/quiz";
import QuestionRenderer from "@/components/QuestionRenderer";
import ProgressBar from "@/components/ProgressBar";
import Logo from "@/components/Logo";

function isAnswerCorrect(q: Question, selected: string[]): boolean {
  if (q.type === "multiple-dropdown") {
    return (q.subQuestions || []).every((sq) => {
      const entry = selected.find((a) => a.startsWith(sq.id + ":"));
      return entry ? entry.split(":")[1] === sq.correctOptionId : false;
    });
  }
  return (
    selected.length === q.correctAnswers.length &&
    selected.every((a) => q.correctAnswers.includes(a)) &&
    selected.length > 0
  );
}

export default function UserPlayPage() {
  const router = useRouter();
  const [attempt, setAttempt] = useState<QuizAttempt | null>(null);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [answers, setAnswers] = useState<Map<string, string[]>>(new Map());
  const [loading, setLoading] = useState(true);
  const [fadeKey, setFadeKey] = useState(0);
  const [checkedQuestions, setCheckedQuestions] = useState<Set<string>>(new Set());
  const [userName, setUserName] = useState("");
  const [theme, setTheme] = useState<QuizTheme>("classmaker");

  const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const answersRef = useRef<Map<string, string[]>>(new Map());

  useEffect(() => {
    const attemptStr = sessionStorage.getItem("userAttempt");
    const userStr = sessionStorage.getItem("quizUser");
    const themeStr = sessionStorage.getItem("userQuizTheme");

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

    const att: QuizAttempt = JSON.parse(attemptStr);
    setAttempt(att);
    setQuestions(att.questions);
    setTheme((themeStr as QuizTheme) || "classmaker");

    if (userStr) {
      setUserName(JSON.parse(userStr).name);
    }

    // Restore any existing answers
    const answerMap = new Map<string, string[]>();
    for (const a of att.answers) {
      answerMap.set(a.questionId, a.selectedAnswers);
    }
    setAnswers(answerMap);
    answersRef.current = answerMap;
    setLoading(false);
  }, [router]);

  const buildAnswersArray = useCallback((): QuizAnswer[] => {
    return questions.map((q) => ({
      questionId: q.id,
      selectedAnswers: answersRef.current.get(q.id) || [],
    }));
  }, [questions]);

  const saveProgress = useCallback(() => {
    if (!attempt) return;
    const body = JSON.stringify({ answers: buildAnswersArray() });
    fetch(`/api/user/attempts/${attempt.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body,
    });
  }, [attempt, buildAnswersArray]);

  // Save on unload
  useEffect(() => {
    function handleBeforeUnload() {
      if (!attempt) return;
      const body = JSON.stringify({ answers: buildAnswersArray() });
      navigator.sendBeacon(
        `/api/user/attempts/${attempt.id}`,
        new Blob([body], { type: "application/json" })
      );
    }
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [attempt, buildAnswersArray]);

  const quizMode: QuizMode = attempt?.quizMode || "testing";

  function handleAnswerChange(questionId: string, selected: string[]) {
    setAnswers((prev) => {
      const next = new Map(prev);
      next.set(questionId, selected);
      answersRef.current = next;
      return next;
    });

    if (quizMode === "learning") {
      setCheckedQuestions((prev) => {
        const next = new Set(prev);
        next.delete(questionId);
        return next;
      });
    }

    // Debounced save
    if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
    saveTimeoutRef.current = setTimeout(saveProgress, 300);
  }

  function goToNext() {
    if (currentIndex < questions.length - 1) {
      if (quizMode === "learning" && !checkedQuestions.has(questions[currentIndex].id)) {
        setCheckedQuestions((prev) => new Set(prev).add(questions[currentIndex].id));
        return;
      }
      setCurrentIndex(currentIndex + 1);
      setFadeKey((k) => k + 1);
    }
  }

  function goToPrev() {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
      setFadeKey((k) => k + 1);
    }
  }

  function goToQuestion(i: number) {
    setCurrentIndex(i);
    setFadeKey((k) => k + 1);
  }

  const finishQuiz = useCallback(async () => {
    if (!attempt || questions.length === 0) return;

    // Clear any pending debounced save
    if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);

    const finalAnswers = buildAnswersArray();

    const res = await fetch(`/api/user/attempts/${attempt.id}/finish`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ answers: finalAnswers }),
    });

    if (res.ok) {
      const completed: QuizAttempt = await res.json();
      sessionStorage.setItem("userAttempt", JSON.stringify(completed));
      sessionStorage.setItem("userQuizAnswers", JSON.stringify(finalAnswers));
      sessionStorage.setItem("userQuizQuestions", JSON.stringify(questions));
      router.push("/user/results");
    }
  }, [attempt, questions, buildAnswersArray, router]);

  if (loading || !attempt) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <p className="text-gray-400">Loading quiz...</p>
      </div>
    );
  }

  const currentQuestion = questions[currentIndex];
  const currentAnswers = answers.get(currentQuestion.id) || [];
  const answeredCount = Array.from(answers.values()).filter((a) => a.length > 0).length;
  const showFeedback = quizMode === "learning" && checkedQuestions.has(currentQuestion.id);

  if (theme === "classmaker") {
    return (
      <ClassMarkerLayout
        questions={questions}
        currentIndex={currentIndex}
        currentQuestion={currentQuestion}
        currentAnswers={currentAnswers}
        answers={answers}
        fadeKey={fadeKey}
        userName={userName}
        showFeedback={showFeedback}
        quizMode={quizMode}
        checkedQuestions={checkedQuestions}
        onAnswerChange={handleAnswerChange}
        onNext={goToNext}
        onPrev={goToPrev}
        onGoTo={goToQuestion}
        onFinish={finishQuiz}
      />
    );
  }

  return (
    <ModernLayout
      questions={questions}
      currentIndex={currentIndex}
      currentQuestion={currentQuestion}
      currentAnswers={currentAnswers}
      answeredCount={answeredCount}
      fadeKey={fadeKey}
      answers={answers}
      showFeedback={showFeedback}
      quizMode={quizMode}
      checkedQuestions={checkedQuestions}
      onAnswerChange={handleAnswerChange}
      onNext={goToNext}
      onPrev={goToPrev}
      onGoTo={goToQuestion}
      onFinish={finishQuiz}
    />
  );
}

/* ─── ClassMarker Theme ─── */

interface ClassMarkerLayoutProps {
  questions: Question[];
  currentIndex: number;
  currentQuestion: Question;
  currentAnswers: string[];
  answers: Map<string, string[]>;
  fadeKey: number;
  userName: string;
  showFeedback: boolean;
  quizMode: QuizMode;
  checkedQuestions: Set<string>;
  onAnswerChange: (questionId: string, selected: string[]) => void;
  onNext: () => void;
  onPrev: () => void;
  onGoTo: (i: number) => void;
  onFinish: () => void;
}

function ClassMarkerLayout({
  questions,
  currentIndex,
  currentQuestion,
  currentAnswers,
  answers,
  fadeKey,
  userName,
  showFeedback,
  quizMode,
  checkedQuestions,
  onAnswerChange,
  onNext,
  onPrev,
  onGoTo,
  onFinish,
}: ClassMarkerLayoutProps) {
  const [showAllQuestions, setShowAllQuestions] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [expandedQuestion, setExpandedQuestion] = useState<string | null>(null);

  function toggleFullscreen() {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
      setIsFullscreen(true);
    } else {
      document.exitFullscreen();
      setIsFullscreen(false);
    }
  }

  function handleGoToFromModal(i: number) {
    onGoTo(i);
    setShowAllQuestions(false);
  }

  return (
    <div className="min-h-screen bg-white">
      {/* ClassMarker logo */}
      <div className="px-6 pt-5 pb-3 max-w-4xl mx-auto">
        <Logo height={36} />
      </div>

      {/* User info row with See all questions & fullscreen */}
      <div className="px-6 pb-4 max-w-4xl mx-auto flex items-center justify-between">
        <div className="flex items-center gap-2 text-sm text-gray-600">
          <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
          </svg>
          <span>{userName}</span>
        </div>
        <div className="flex items-center gap-3">
          {/* See all questions button */}
          <button
            onClick={() => setShowAllQuestions(true)}
            className="flex items-center gap-1.5 text-sm text-[#c0392b] hover:text-[#a93226] font-medium"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM3.75 12h.007v.008H3.75V12zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm-.375 5.25h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" />
            </svg>
            See all questions
          </button>
          {/* Fullscreen button */}
          <button
            onClick={toggleFullscreen}
            className="text-gray-400 hover:text-gray-600"
            title={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
          >
            {isFullscreen ? (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25" />
              </svg>
            ) : (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15" />
              </svg>
            )}
          </button>
        </div>
      </div>

      {/* Question card */}
      <div className="px-6 max-w-4xl mx-auto">
        <div
          key={fadeKey}
          className="question-fade-in bg-[#f0f5f9] border border-gray-200 rounded-xl overflow-hidden"
        >
          {/* Card header */}
          <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
            <span className="text-base font-semibold text-gray-900">
              Question {currentIndex + 1} of {questions.length}
            </span>
            <svg className="w-5 h-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0111.186 0z" />
            </svg>
          </div>

          {/* Card body */}
          <div className="px-6 py-6">
            <QuestionRenderer
              question={currentQuestion}
              selectedAnswers={currentAnswers}
              onAnswerChange={(selected) =>
                onAnswerChange(currentQuestion.id, selected)
              }
              variant="classmaker"
              showFeedback={showFeedback}
            />
          </div>
        </div>
      </div>

      {/* Learning mode feedback banner */}
      {showFeedback && (
        <div className="px-6 mt-4 max-w-4xl mx-auto">
          {isAnswerCorrect(currentQuestion, currentAnswers) ? (
            <div className="flex items-center gap-2 px-4 py-3 bg-green-50 border border-green-200 rounded-lg text-green-800 text-sm font-medium">
              <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Correct! Click Next to continue.
            </div>
          ) : (
            <div className="flex items-center gap-2 px-4 py-3 bg-red-50 border border-red-200 rounded-lg text-red-800 text-sm font-medium">
              <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Incorrect. Review the correct answer above, then click Next or go back to try again.
            </div>
          )}
        </div>
      )}

      {/* Navigation buttons */}
      <div className="px-6 py-8 max-w-4xl mx-auto">
        <div className="flex items-center justify-between">
          <button
            onClick={onPrev}
            disabled={currentIndex === 0}
            className="px-5 py-2.5 bg-[#c0392b] text-white rounded-md text-sm font-semibold hover:bg-[#a93226] disabled:opacity-30 disabled:cursor-not-allowed flex items-center gap-1.5"
          >
            <span>&#8249;</span> Previous
          </button>

          <button
            onClick={onNext}
            disabled={currentIndex === questions.length - 1}
            className="px-5 py-2.5 bg-[#c0392b] text-white rounded-md text-sm font-semibold hover:bg-[#a93226] disabled:opacity-30 disabled:cursor-not-allowed flex items-center gap-1.5"
          >
            {quizMode === "learning" && !checkedQuestions.has(currentQuestion.id) ? "Check" : "Next"} <span>&#8250;</span>
          </button>
        </div>

        <div className="flex justify-center mt-4">
          <button
            onClick={onFinish}
            className="px-6 py-2.5 bg-[#3d5a5a] text-white rounded-md text-sm font-semibold hover:bg-[#334d4d]"
          >
            Finish now
          </button>
        </div>
      </div>

      {/* See All Questions Modal */}
      {showAllQuestions && (
        <div
          className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4"
          onClick={() => setShowAllQuestions(false)}
        >
          <div
            className="bg-white rounded-xl shadow-2xl w-full max-w-xl max-h-[80vh] flex flex-col"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal header */}
            <div className="flex items-center justify-end px-5 pt-4 pb-2">
              <button
                onClick={() => setShowAllQuestions(false)}
                className="text-gray-400 hover:text-gray-600"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Tabs */}
            <div className="px-5 flex items-center border-b border-gray-200">
              <button className="pb-2.5 text-sm font-semibold text-[#c0392b] border-b-2 border-[#c0392b]">
                All Questions
              </button>
            </div>

            {/* Question list */}
            <div className="flex-1 overflow-y-auto">
              {questions.map((q, i) => {
                const isAnswered =
                  answers.has(q.id) && (answers.get(q.id)?.length ?? 0) > 0;
                const isExpanded = expandedQuestion === q.id;
                const selectedForQ = answers.get(q.id) || [];

                return (
                  <div key={q.id} className="border-b border-gray-100">
                    {/* Row */}
                    <div className="flex items-center px-5 py-3.5 hover:bg-gray-50 transition-colors">
                      {/* Bookmark icon */}
                      <svg className="w-5 h-5 text-gray-300 flex-shrink-0 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0111.186 0z" />
                      </svg>

                      {/* Chevron toggle */}
                      <button
                        onClick={() => setExpandedQuestion(isExpanded ? null : q.id)}
                        className="mr-2 text-gray-400 hover:text-gray-600 flex-shrink-0"
                      >
                        <svg
                          className={`w-4 h-4 transition-transform ${isExpanded ? "rotate-180" : ""}`}
                          fill="none" stroke="currentColor" viewBox="0 0 24 24"
                        >
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                        </svg>
                      </button>

                      {/* Question label */}
                      <span className="text-sm text-gray-800 font-medium mr-3">
                        Question {i + 1}
                      </span>

                      {/* Status badge */}
                      {isAnswered ? (
                        <span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded">
                          Answered
                        </span>
                      ) : (
                        <span className="text-xs text-[#c0392b] bg-red-50 px-2 py-0.5 rounded border border-red-200">
                          Unanswered
                        </span>
                      )}

                      {/* Go-to arrow */}
                      <button
                        onClick={() => handleGoToFromModal(i)}
                        className="ml-auto text-gray-400 hover:text-gray-600 flex-shrink-0"
                      >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12.75 15l3-3m0 0l-3-3m3 3h-7.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                      </button>
                    </div>

                    {/* Expanded question preview (read-only) */}
                    {isExpanded && (
                      <div className="px-5 pb-4 pt-1 bg-gray-50">
                        <p className="text-sm text-gray-700 mb-3">{q.text}</p>
                        <div className="space-y-1.5">
                          {q.options.map((opt, optIdx) => {
                            const wasSelected = selectedForQ.includes(opt.id);
                            const isMulti = q.type === "multiple-answer";
                            return (
                              <div key={opt.id} className="flex items-center gap-2.5 text-sm">
                                <div
                                  className={`w-4 h-4 flex items-center justify-center border-2 flex-shrink-0 ${
                                    isMulti ? "rounded-sm" : "rounded-full"
                                  } ${
                                    wasSelected
                                      ? "border-blue-600 bg-blue-600"
                                      : "border-gray-300"
                                  }`}
                                >
                                  {wasSelected && !isMulti && (
                                    <div className="w-1.5 h-1.5 rounded-full bg-white" />
                                  )}
                                  {wasSelected && isMulti && (
                                    <span className="text-[10px] text-white leading-none">&#10003;</span>
                                  )}
                                </div>
                                <span className={wasSelected ? "text-gray-900" : "text-gray-500"}>
                                  {String.fromCharCode(65 + optIdx)}. {opt.label}
                                </span>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ─── Modern Theme ─── */

interface ModernLayoutProps {
  questions: Question[];
  currentIndex: number;
  currentQuestion: Question;
  currentAnswers: string[];
  answeredCount: number;
  fadeKey: number;
  answers: Map<string, string[]>;
  showFeedback: boolean;
  quizMode: QuizMode;
  checkedQuestions: Set<string>;
  onAnswerChange: (questionId: string, selected: string[]) => void;
  onNext: () => void;
  onPrev: () => void;
  onGoTo: (i: number) => void;
  onFinish: () => void;
}

function ModernLayout({
  questions,
  currentIndex,
  currentQuestion,
  currentAnswers,
  answeredCount,
  fadeKey,
  answers,
  showFeedback,
  quizMode,
  checkedQuestions,
  onAnswerChange,
  onNext,
  onPrev,
  onGoTo,
  onFinish,
}: ModernLayoutProps) {
  return (
    <div className="min-h-screen bg-white">
      {/* Blue header */}
      <header className="bg-[#2b579a] text-white px-6 py-3 shadow-md">
        <div className="max-w-4xl mx-auto flex items-center justify-between">
          <Logo height={28} />
          <div className="flex items-center gap-4">
            <ProgressBar
              current={answeredCount}
              total={questions.length}
              variant="modern"
            />
          </div>
        </div>
      </header>

      {/* Question counter bar */}
      <div className="border-b border-gray-200 bg-gray-50 px-6 py-2">
        <div className="max-w-4xl mx-auto flex items-center justify-between">
          <span className="text-sm text-gray-600">
            Question {currentIndex + 1} of {questions.length}
          </span>
          <span className="text-xs text-gray-400 uppercase tracking-wide">
            {currentQuestion.type.replace("-", " ")}
          </span>
        </div>
      </div>

      <main className="max-w-4xl mx-auto p-6">
        {/* Question card with fade transition */}
        <div
          key={fadeKey}
          className="question-fade-in bg-white border border-gray-200 rounded-lg shadow-sm p-6 mb-4"
        >
          <QuestionRenderer
            question={currentQuestion}
            selectedAnswers={currentAnswers}
            onAnswerChange={(selected) =>
              onAnswerChange(currentQuestion.id, selected)
            }
            variant="modern"
            showFeedback={showFeedback}
          />
        </div>

        {/* Learning mode feedback banner */}
        {showFeedback && (
          <div className="mb-6">
            {isAnswerCorrect(currentQuestion, currentAnswers) ? (
              <div className="flex items-center gap-2 px-4 py-3 bg-green-50 border border-green-200 rounded-lg text-green-800 text-sm font-medium">
                <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Correct! Click Next to continue.
              </div>
            ) : (
              <div className="flex items-center gap-2 px-4 py-3 bg-red-50 border border-red-200 rounded-lg text-red-800 text-sm font-medium">
                <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Incorrect. Review the correct answer above, then click Next or go back to try again.
              </div>
            )}
          </div>
        )}

        {/* Navigation dots */}
        <div className="flex flex-wrap gap-1 justify-center mb-6">
          {questions.map((_, i) => {
            const isAnswered =
              answers.has(questions[i].id) &&
              (answers.get(questions[i].id)?.length ?? 0) > 0;
            return (
              <button
                key={i}
                onClick={() => onGoTo(i)}
                className={`w-8 h-8 rounded text-xs font-medium border transition-colors ${
                  i === currentIndex
                    ? "bg-[#2b579a] text-white border-[#2b579a]"
                    : isAnswered
                    ? "bg-green-50 text-green-700 border-green-300"
                    : "bg-white text-gray-500 border-gray-300 hover:border-gray-400"
                }`}
              >
                {i + 1}
              </button>
            );
          })}
        </div>

        {/* Navigation buttons */}
        <div className="flex items-center justify-between">
          <button
            onClick={onPrev}
            disabled={currentIndex === 0}
            className="px-5 py-2 border border-gray-300 rounded text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-30 disabled:cursor-not-allowed"
          >
            Previous
          </button>

          {currentIndex === questions.length - 1 ? (
            <button
              onClick={onFinish}
              className="px-5 py-2 bg-green-600 text-white rounded text-sm font-medium hover:bg-green-700"
            >
              Finish Quiz
            </button>
          ) : (
            <button
              onClick={onNext}
              className="px-5 py-2 bg-[#2b579a] text-white rounded text-sm font-medium hover:bg-[#1e3f73]"
            >
              {quizMode === "learning" && !checkedQuestions.has(currentQuestion.id) ? "Check" : "Next"}
            </button>
          )}
        </div>
      </main>
    </div>
  );
}
