"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Question, QuizConfig, QuizAnswer, QuizTheme, QuizMode, QuizAttempt } from "@/types/quiz";
import QuestionRenderer from "@/components/QuestionRenderer";
import Timer from "@/components/Timer";
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
  );
}

function shuffleArray<T>(array: T[]): T[] {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

export default function QuizPlayPage() {
  const router = useRouter();
  const { data: session } = useSession();
  const [questions, setQuestions] = useState<Question[]>([]);
  const [config, setConfig] = useState<QuizConfig | null>(null);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [answers, setAnswers] = useState<Map<string, string[]>>(new Map());
  const [loading, setLoading] = useState(true);
  const [timerKey, setTimerKey] = useState(0);
  const [fadeKey, setFadeKey] = useState(0);
  const [quizTitle, setQuizTitle] = useState("");
  const [checkedQuestions, setCheckedQuestions] = useState<Set<string>>(new Set());
  const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const answersRef = useRef<Map<string, string[]>>(new Map());
  const attemptIdRef = useRef<string | null>(null);
  const initRef = useRef(false);

  useEffect(() => {
    if (initRef.current) return;
    initRef.current = true;

    const configStr = sessionStorage.getItem("quizConfig");
    if (!configStr) {
      router.push("/quiz");
      return;
    }

    const cfg: QuizConfig = JSON.parse(configStr);
    setConfig(cfg);

    sessionStorage.setItem("quizStartedAt", new Date().toISOString());

    Promise.all(
      cfg.templateIds.map((id) =>
        fetch(`/api/templates/${id}`).then((r) => r.json())
      )
    ).then(async (templates) => {
      if (templates.length > 0) {
        setQuizTitle(templates.map((t: { title: string }) => t.title).join(", "));
      }
      const allQuestions = templates.flatMap(
        (t: { questions: Question[] }) => t.questions
      ).filter((q: Question) => !q.hidden);
      const shuffled = shuffleArray(allQuestions);
      const selected = shuffled.slice(0, cfg.questionCount);
      setQuestions(selected);

      // Create server-side attempt for tracking
      try {
        const res = await fetch("/api/quiz/attempts", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ questions: selected, quizMode: cfg.quizMode }),
        });
        if (res.ok) {
          const attempt: QuizAttempt = await res.json();
          attemptIdRef.current = attempt.id;
        }
      } catch {
        // Non-critical: tracking fails silently
      }

      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 (!attemptIdRef.current) return;
    const body = JSON.stringify({ answers: buildAnswersArray() });
    fetch(`/api/user/attempts/${attemptIdRef.current}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body,
    });
  }, [buildAnswersArray]);

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

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

    if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);

    const quizAnswers: QuizAnswer[] = questions.map((q) => ({
      questionId: q.id,
      selectedAnswers: answers.get(q.id) || [],
    }));

    sessionStorage.setItem("quizAnswers", JSON.stringify(quizAnswers));
    sessionStorage.setItem("quizQuestions", JSON.stringify(questions));
    sessionStorage.setItem("quizFinishedAt", new Date().toISOString());

    // Finish server-side attempt
    if (attemptIdRef.current) {
      try {
        await fetch(`/api/user/attempts/${attemptIdRef.current}/finish`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ answers: quizAnswers }),
        });
      } catch {
        // Non-critical
      }
    }

    router.push("/quiz/results");
  }, [questions, answers, router]);

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

  function handleAnswerChange(questionId: string, selected: string[]) {
    setAnswers((prev) => {
      const next = new Map(prev);
      next.set(questionId, selected);
      answersRef.current = next;
      return next;
    });
    // In learning mode, clear feedback when answer changes so user can re-check
    if (quizMode === "learning") {
      setCheckedQuestions((prev) => {
        const next = new Set(prev);
        next.delete(questionId);
        return next;
      });
    }
    // Debounced save to server
    if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
    saveTimeoutRef.current = setTimeout(saveProgress, 300);
  }

  function goToNext() {
    if (currentIndex < questions.length - 1) {
      // In learning mode, first click checks answer, second click navigates
      if (quizMode === "learning" && !checkedQuestions.has(questions[currentIndex].id)) {
        setCheckedQuestions((prev) => new Set(prev).add(questions[currentIndex].id));
        return;
      }
      setCurrentIndex(currentIndex + 1);
      setTimerKey((k) => k + 1);
      setFadeKey((k) => k + 1);
    }
  }

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

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

  function handlePerQuestionTimeUp() {
    if (currentIndex < questions.length - 1) {
      goToNext();
    } else {
      finishQuiz();
    }
  }

  const theme: QuizTheme = config?.quizTheme || "classmaker";

  if (loading || !config) {
    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}
        config={config}
        timerKey={timerKey}
        fadeKey={fadeKey}
        quizTitle={quizTitle}
        userName={session?.user?.name || ""}
        showFeedback={showFeedback}
        quizMode={quizMode}
        checkedQuestions={checkedQuestions}
        onAnswerChange={handleAnswerChange}
        onNext={goToNext}
        onPrev={goToPrev}
        onGoTo={goToQuestion}
        onFinish={finishQuiz}
        onPerQuestionTimeUp={handlePerQuestionTimeUp}
      />
    );
  }

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

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

interface ClassMarkerLayoutProps {
  questions: Question[];
  currentIndex: number;
  currentQuestion: Question;
  currentAnswers: string[];
  answers: Map<string, string[]>;
  config: QuizConfig;
  timerKey: number;
  fadeKey: number;
  quizTitle: string;
  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;
  onPerQuestionTimeUp: () => void;
}

function ClassMarkerLayout({
  questions,
  currentIndex,
  currentQuestion,
  currentAnswers,
  answers,
  config,
  timerKey,
  fadeKey,
  quizTitle,
  userName,
  showFeedback,
  quizMode,
  checkedQuestions,
  onAnswerChange,
  onNext,
  onPrev,
  onGoTo,
  onFinish,
  onPerQuestionTimeUp,
}: 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>

      {/* Quiz title */}
      <div className="px-6 pb-2 max-w-4xl mx-auto">
        <h1 className="text-2xl font-bold text-gray-900">{quizTitle}</h1>
      </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">
          {config.timerMode === "per-question" && (
            <Timer
              key={timerKey}
              seconds={config.perQuestionSeconds}
              onTimeUp={onPerQuestionTimeUp}
              label="Question"
              variant="classmaker"
            />
          )}
          {config.timerMode === "total" && (
            <Timer
              seconds={config.totalSeconds}
              onTimeUp={onFinish}
              label="Total"
              variant="classmaker"
            />
          )}
          {/* 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 (existing design) ─── */

interface ModernLayoutProps {
  questions: Question[];
  currentIndex: number;
  currentQuestion: Question;
  currentAnswers: string[];
  answeredCount: number;
  config: QuizConfig;
  timerKey: 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;
  onPerQuestionTimeUp: () => void;
}

function ModernLayout({
  questions,
  currentIndex,
  currentQuestion,
  currentAnswers,
  answeredCount,
  config,
  timerKey,
  fadeKey,
  answers,
  showFeedback,
  quizMode,
  checkedQuestions,
  onAnswerChange,
  onNext,
  onPrev,
  onGoTo,
  onFinish,
  onPerQuestionTimeUp,
}: 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"
            />
            {config.timerMode === "per-question" && (
              <Timer
                key={timerKey}
                seconds={config.perQuestionSeconds}
                onTimeUp={onPerQuestionTimeUp}
                label="Question"
                variant="modern"
              />
            )}
            {config.timerMode === "total" && (
              <Timer
                seconds={config.totalSeconds}
                onTimeUp={onFinish}
                label="Total"
                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">
            {currentAnswers.length > 0 &&
             currentAnswers.every((a) => currentQuestion.correctAnswers.includes(a)) &&
             currentAnswers.length === currentQuestion.correctAnswers.length ? (
              <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>
  );
}
