"use client";

import React, {
  JSX,
  use,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import axios from "axios";
import AnimatedSection from "@/components/AnimatedSection";
import {
  Brain,
  Trophy,
  RotateCcw,
  ArrowRight,
  ChevronLeft,
  ChevronRight,
  Bookmark,
  Clock,
  Play,
  Pause,
  RotateCw,
  Volume2,
  Video,
} from "lucide-react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import {
  getGuidelines,
  getTestData,
  getTestInstructionData,
  getTestList,
  getTestProgress,
  getTestResult,
  saveTestV2,
  updateTestProgress,
} from "@/lib/api/testSeriesApi";
import QuizSidebar from "./components/QuizSidebar";
import InlineQuiz from "./components/InlineQuiz";
import { GuidelinesModal } from "./components/GuidelinesModal";
import { LanguageModal } from "./components/LanguageModal";
import { InstructionsModal } from "./components/InstructionsModal";
import TestResultUI from "./components/TestResultUI";
import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { decodeHtml } from "@/lib/commonFunctions";
import { useSearchParams } from "next/navigation";
import { set } from "date-fns";
import { getTranslation } from "@/src/hooks/useTranslation";
import { Alert } from "@/components/ui/alert";
import { getStoredLanguage } from "@/lib/language";
import {
  getActiveCourseId,
  getActiveCourseLanguage,
} from "@/lib/courseSelection";

type Lesson = {
  id: number;
  title: string;
  videoSrc?: string;
  audioSrc?: string;
  thumbnail?: string;
  quiz?: {
    questions: {
      question: string;
      options: string[];
      correctAnswer: number;
      explanation: string;
    }[];
  };
};

const LESSONS: Lesson[] = [];

const STORAGE_KEY = "gita_course_progress_v1";

interface Guideline {
  id: string;
  description: string;
}

type ProgressRecord = Record<
  number,
  {
    video?: number;
    audio?: number;
    unlocked?: boolean;
    quizCompleted?: boolean;
  }
>;
type Language = "hindi" | "english";

const LANGUAGES: { label: string; value: Language }[] = [
  { label: "Hindi", value: "hindi" },
  { label: "English", value: "english" },
];

const getLanguageId = (language: Language): "1" | "2" =>
  language === "english" ? "1" : "2";

const getLanguageFromId = (languageId?: string | null): Language | null => {
  if (languageId === "1") return "english";
  if (languageId === "2") return "hindi";
  return null;
};

const getStoredQuizLanguage = (): Language | null => {
  if (typeof window === "undefined") return null;

  const storedLang = localStorage.getItem("quizLanguage");
  return storedLang === "english" || storedLang === "hindi" ? storedLang : null;
};

const PROGRESS_PING_SECONDS = 3;

// Solid gold lock icon (matches the design provided by the client)
const SolidLock = ({ className = "w-5 h-5" }: { className?: string }) => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    className={className}
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="M7 10V7a5 5 0 0 1 10 0v3"
      stroke="#FAA631"
      strokeWidth="2"
      strokeLinecap="round"
    />
    <rect x="3.5" y="10" width="17" height="11" rx="3.5" fill="#FAA631" />
    <circle cx="12" cy="15" r="1.6" fill="#fff" />
    <rect x="11.2" y="15.5" width="1.6" height="3" rx="0.8" fill="#fff" />
  </svg>
);

export default function Quiz(): JSX.Element {
  const [activeCard, setActiveCard] = useState<string | null>(null);
  const [courseLanguage, setCourseLanguage] = useState<Language>(
    () => getActiveCourseLanguage() ?? "english",
  );
  const [selectedLanguage, setSelectedLanguage] = useState<Language>(
    () => getStoredQuizLanguage() ?? getStoredLanguage(),
  );
  const [selectedLesson, setSelectedLesson] = useState<number>(1);
  const [progress, setProgress] = useState<ProgressRecord>({});
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [isQuizActive, setIsQuizActive] = useState(false);
  const [videoReadyToPlay, setVideoReadyToPlay] = useState(false);
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<"lessons" | "more">("lessons");
  const [isOpen, setIsOpen] = useState(false);
  const [showGuidelineContinue, setShowGuidelineContinue] = useState(false);
  const [showLanguageModal, setShowLanguageModal] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [confirmSubmit, setConfirmSubmit] = useState(false);
  const [showSolution, setShowSolution] = useState(false);
  const [showMobileSidebar, setShowMobileSidebar] = useState(false);
  const [hidePreviewBar, setHidePreviewBar] = useState(true);
  const [testEnd, setTestEnd] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [testResult, setTestResult] = useState<any>(null);
  const lesson = LESSONS.find((l) => l.id === selectedLesson)!;
  const [showExplanation, setShowExplanation] = useState(false);
  const [testData, setTestData] = useState<any>(null);
  const { language } = useLanguage();
  const searchParams = useSearchParams();
  const contentId = searchParams.get("contentId");
  const langId = searchParams.get("langId");
  const englishQuestions =
    Array.isArray(testData?.questions) && testData.questions.length > 0
      ? testData.questions
      : [];

  const hindiQuestions =
    Array.isArray(testData?.questions_hindi) &&
    testData.questions_hindi.length > 0
      ? testData.questions_hindi
      : [];

  // 🔁 Language-aware + bidirectional fallback
  const qlist =
    selectedLanguage === "english" ? englishQuestions : hindiQuestions;

  const testInfo = testData?.test_basic ?? {};
  const [answers, setAnswers] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(300); // 5 minutes
  const [marked, setMarked] = useState<boolean[]>([]);
  const [visited, setVisited] = useState<boolean[]>([]);

  const [started, setStarted] = useState(false);
  const [guidelineToggle, setGuidelineToggle] = useState(true);
  const [mode, setMode] = useState<"video" | "audio" | "quiz">("video");
  const [audioEnded, setAudioEnded] = useState(false);
  const audioReplayingRef = useRef(false);
  const audioSeekLockRef = useRef(false);
  const videoSeekLockRef = useRef(false);
  const [totalDuration, setTotalDuration] = useState(0);
  const [timeTaken, setTimeTaken] = useState(0);
  const [showInstructions, setShowInstructions] = useState(false);
  const [instructionData, setInstructionData] = useState<any>(null);
  const [topics, setTopics] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAll, setShowAll] = useState(false);
  const ytPlayerRef = useRef<any>(null);
  const ytIntervalRef = useRef<number | null>(null);
  const currentVideoIdRef = useRef<string | null>(null);
  const pendingMediaResumeRef = useRef<{
    lessonId: number | null;
    kind: "video" | "audio" | null;
    time: number;
  }>({
    lessonId: null,
    kind: null,
    time: 0,
  });
  const [guidelineData, setGuidelineData] = useState<Guideline[]>([]);
  const [ytStarted, setYtStarted] = useState(false);
  const durationRef = useRef<{ [lessonId: number]: number }>({});
  const hasAutoSeekedRef = useRef<{ [lessonId: number]: boolean }>({});
  const [userData, setUserData] = useState<Record<string, any>>({});
  const [courseId, setCourseId] = useState<string>("");
  const { toast } = useToast();
  const lastYtTimeRef = useRef<number>(0);
  const [showFullscreenModal, setShowFullscreenModal] = useState(false);
  const isSubmittingTestRef = useRef(false);
  // Add these near your other useRef declarations
  const ytCurrentTimeRef = useRef<number>(0);
  const [pendingQuizStart, setPendingQuizStart] = useState<{
    testId: string;
    courseId: string;
  } | null>(null);
  const [gocod, setGocod] = useState("");
  const mediaIntervalRef = useRef<{
    video: number | null;
    audio: number | null;
  }>({
    video: null,
    audio: null,
  });
  const lastProgressSaveRef = useRef<{
    [lessonId: number]: {
      video?: number;
      audio?: number;
    };
  }>({});

  const [, setTick] = useState(false);
  const text = getTranslation(language).quizPage;
  const renderText = (
    template: string,
    values: Record<string, string | number>,
  ) =>
    Object.entries(values).reduce(
      (acc, [key, value]) => acc.replace(`{${key}}`, String(value)),
      template,
    );

  useEffect(() => {
    const interval = setInterval(() => {
      setTick((prev) => !prev);
    }, 1000);

    return () => clearInterval(interval);
  }, [selectedLanguage]);
  const lastPlaybackTimeRef = useRef<{
    [lessonId: number]: {
      video?: number;
      audio?: number;
    };
  }>({});
  const lastTrackedTimeRef = useRef<{
    [lessonId: number]: {
      video?: number;
      audio?: number;
    };
  }>({});
  const ytWatchedRef = useRef<Record<string, number>>({});
  const [activeQuizType, setActiveQuizType] = useState<
    "lesson" | "pre" | "mock" | "final"
  >("lesson");

  const ENABLE_SKIP_PROGRESS_FOR_TESTING = true;
  const getTopicContentId = (topic: any) =>
    Number(topic?.details?.video?.id || topic?.details?.audio?.id || 0);

  const getPreferredModeForTopic = (topic: any): "video" | "audio" | "quiz" => {
    if (topic?.details?.video?.id) return "video";
    if (topic?.details?.audio?.id) return "audio";
    return "quiz";
  };

  const getTopicProgress = (topic: any) => {
    const topicLessonId = getTopicContentId(topic);

    if (!topicLessonId) return 0;

    return Math.max(
      progress[topicLessonId]?.video || 0,
      progress[topicLessonId]?.audio || 0,
    );
  };

  const getQuizWindow = (quizData: any) => {
    const start = Number(quizData?.start_date);
    const end = Number(quizData?.end_date);

    return {
      start: Number.isFinite(start) && start > 0 ? start : null,
      end: Number.isFinite(end) && end > 0 ? end : null,
    };
  };

  const isQuizSubmitted = (topic: any) =>
    String(topic?.details?.quiz?.state) === "1";

  useEffect(() => {
    if (typeof window === "undefined") return;

    const data = localStorage.getItem("user_data");
    const activeCourseLanguage = getActiveCourseLanguage() ?? "english";
    const activeCourseId = getActiveCourseId(activeCourseLanguage);
    const registerDetails = localStorage.getItem("register_details");

    let user = null;
    let register = null;

    try {
      user = data ? JSON.parse(data) : null;
    } catch (e) {
      console.error("Invalid user_data JSON:", data);
    }

    try {
      register = registerDetails ? JSON.parse(registerDetails) : null;
    } catch (e) {
      console.error("Invalid register_details JSON:", registerDetails);
    }

    // ✅ gocod logic
    if (user?.gocod) {
      setGocod(user.gocod);
    } else if (register?.gocod) {
      setGocod(register.gocod);
    }

    // ✅ course id
    if (activeCourseId) {
      setCourseId(activeCourseId);
    }
    setCourseLanguage(activeCourseLanguage);

    // ✅ user data
    if (user) {
      setUserData(user);
    }
  }, []);

  useEffect(() => {
    const token = localStorage.getItem("token");

    if (!token) {
      router.replace("/login");
    }
  }, [router]);

  useEffect(() => {
    const languageFromQuery = getLanguageFromId(langId);
    const storedLang = getStoredQuizLanguage();
    const fallbackLang = getStoredLanguage();

    if (languageFromQuery) {
      setSelectedLanguage(languageFromQuery);
      return;
    }

    setSelectedLanguage(storedLang ?? fallbackLang);
  }, [langId]);

  useEffect(() => {
    localStorage.setItem("quizLanguage", selectedLanguage);

    const params = new URLSearchParams(searchParams.toString());
    const nextLangId = getLanguageId(selectedLanguage);

    if (params.get("langId") !== nextLangId) {
      params.set("langId", nextLangId);
      const nextUrl = `${window.location.pathname}?${params.toString()}`;
      window.history.replaceState(null, "", nextUrl);
    }
  }, [searchParams, selectedLanguage]);

  const getAllTestList = async (user: string, course: string) => {
    const formData = new FormData();
    formData.append("user_id", user);
    formData.append("course_id", course);

    const res = await getTestList(formData);

    if (res?.status) {
      setTopics(res.data);

      // 🔥 SYNC PROGRESS FROM API
      const newProgress: ProgressRecord = {};

      res.data.forEach((topic: any) => {
        const video = topic.details.video;
        const audio = topic.details.audio;

        const lessonId = video?.id || audio?.id;

        if (!lessonId) return;

        const percent = Math.max(
          Number(video?.percentage || 0),
          Number(audio?.percentage || 0),
        );

        newProgress[lessonId] = {
          video: percent,
          audio: percent,
          unlocked:
            percent >= 80 ||
            String(video?.is_locked ?? audio?.is_locked) === "1",
        };
      });

      setProgress(newProgress);
    }

    setLoading(false);
  };

  const handleGuideline = async (language: string, courseId: string) => {
    const formData = new FormData();
    formData.append("language", language == "english" ? "1" : "2");
    formData.append("course_id", courseId || "1");
    const res = await getGuidelines(formData);

    if (res?.status && res.data?.guidelines) {
      setGuidelineData(res.data.guidelines);
    }

    setLoading(false);
  };
  const getLessonProgress = (lessonId: number) => {
    if (!progress[lessonId]) return 0;
    return Math.round(
      Math.max(progress[lessonId].video || 0, progress[lessonId].audio || 0),
    );
  };

  const getAudioProgress = () => {
    if (!audioRef.current) return 0;

    const current = audioRef.current.currentTime || 0;
    const duration = audioRef.current.duration || 1;

    return (current / duration) * 100;
  };

  useEffect(() => {
    handleGuideline(courseLanguage, courseId);
    if (userData?.id && courseId) {
      getAllTestList(userData?.id, courseId);
    }
  }, [courseLanguage, courseId, userData]);
  useEffect(() => {
    if (!visited.length && qlist?.length) {
      setVisited(new Array(qlist.length).fill(false));
    }
  }, [qlist, answers]);
  useEffect(() => {
    setVisited((prev) => {
      if (!prev.length) return prev;

      const copy = [...prev];
      copy[currentQuestion] = true; // ✅ mark immediately
      return copy;
    });
  }, [currentQuestion, answers]);

  const [activeTopicIndex, setActiveTopicIndex] = useState(0);
  const lessonTopics = useMemo(
    () => topics.filter((t) => t.details.quiz?.test_type_mode === "0"),
    [topics],
  );

  const mockTest = useMemo(
    () => topics.filter((t) => t.details.quiz?.test_type_mode === "1"),
    [topics],
  );

  const preCertificationTest = useMemo(
    () => topics.filter((t) => t.details.quiz?.test_type_mode === "2"),
    [topics],
  );

  const finalExam = useMemo(
    () => topics.filter((t) => t.details.quiz?.test_type_mode === "3"),
    [topics],
  );
  const activeTopic = useMemo(() => {
    if (mode === "quiz") {
      if (activeQuizType === "pre") return preCertificationTest[0];
      if (activeQuizType === "mock") return mockTest[0];
      if (activeQuizType === "final") return finalExam[0];
    }

    // default → lesson mode
    return lessonTopics[activeTopicIndex];
  }, [
    mode,
    activeQuizType,
    activeTopicIndex,
    lessonTopics,
    preCertificationTest,
    mockTest,
    finalExam,
  ]);

  const videoLesson = activeTopic?.details?.video;
  const audioLesson = activeTopic?.details?.audio;
  const quiz = activeTopic?.details?.quiz;
  const lessonId = videoLesson?.id ?? audioLesson?.id;

  // Reset audio replay state when lesson changes
  useEffect(() => {
    audioReplayingRef.current = false;
    setAudioEnded(false);
  }, [lessonId]);

  const lessonProgress = Math.max(
    progress[lessonId]?.video || 0,
    progress[lessonId]?.audio || 0,
  );
  const selectedVideoUrl =
    courseLanguage === "english"
      ? videoLesson?.file_url
      : videoLesson?.file_url_hinidi;
  const selectedAudioUrl =
    courseLanguage === "english"
      ? audioLesson?.file_url
      : audioLesson?.file_url_hinidi;

  const captureCurrentMediaTime = () => {
    if (!lessonId) return;

    if (!watchedTimeRef.current[lessonId]) {
      watchedTimeRef.current[lessonId] = { video: 0, audio: 0 };
    }

    if (mode === "video") {
      const currentTime = isYouTubeUrl(selectedVideoUrl)
        ? ytPlayerRef.current?.getCurrentTime?.() || 0
        : videoRef.current?.currentTime || 0;

      if (currentTime > 0) {
        watchedTimeRef.current[lessonId].video = Math.max(
          watchedTimeRef.current[lessonId].video || 0,
          currentTime,
        );
        pendingMediaResumeRef.current = {
          lessonId,
          kind: "video",
          time: currentTime,
        };
      }
      return;
    }

    if (mode === "audio") {
      const currentTime = audioRef.current?.currentTime || 0;

      if (currentTime > 0) {
        watchedTimeRef.current[lessonId].audio = Math.max(
          watchedTimeRef.current[lessonId].audio || 0,
          currentTime,
        );
        pendingMediaResumeRef.current = {
          lessonId,
          kind: "audio",
          time: currentTime,
        };
      }
    }
  };

  const handleLanguageChange = (language: Language) => {
    setSelectedLanguage(language);
  };

  useEffect(() => {
    if (!lessonId || !courseId || !userData?.id) return;

    const loadProgress = async () => {
      const fd = new FormData();
      fd.append("user_id", userData.id);
      fd.append("course_id", courseId);
      fd.append("content_id", String(lessonId));

      const res = await getTestProgress(fd);

      if (res?.status && res.data) {
        // 👉 normalize to array
        const progressData = Array.isArray(res.data) ? res.data : [res.data];

        progressData.forEach((item: any) => {
          watchedTimeRef.current[lessonId] = {
            ...(watchedTimeRef.current[lessonId] || {}),
            [item.mode === "3" ? "video" : "audio"]: Number(item.current_time),
          };

          // 🔒 unlock logic (use is_unlock OR percentage)
          const isUnlocked =
            Number(item.percentage) >= 80 || item.is_unlock === "1";

          if (isUnlocked) {
            setProgress((prev) => ({
              ...prev,
              [lessonId]: {
                ...(prev[lessonId] || {}),
                unlocked: true,
              },
            }));
          }
        });
      }
    };

    loadProgress();
  }, [lessonId, courseId, userData]);

  useEffect(() => {
    if (showInstructions) {
      // 🚫 disable scroll
      document.body.style.overflow = "hidden";
    } else {
      // ✅ enable scroll
      document.body.style.overflow = "auto";
    }

    return () => {
      document.body.style.overflow = "auto";
    };
  }, [showInstructions]);

  useEffect(() => {
    if ((window as any).YT) return;

    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    tag.async = true;
    document.body.appendChild(tag);
  }, []);

  useEffect(() => {
    if (lessonId) {
      hasAutoSeekedRef.current[lessonId] = false;
    }
  }, [lessonId, selectedVideoUrl]);

  const isYouTubeUrl = (url?: string) => {
    if (!url) return false;
    return url.includes("youtube.com") || url.includes("youtu.be");
  };

  const getYouTubeVideoId = (url: string) => {
    if (url.includes("youtu.be")) {
      return url.split("youtu.be/")[1]?.split("?")[0];
    }
    return url.split("v=")[1]?.split("&")[0];
  };

  const VISIBLE_COUNT = 2;

  useEffect(() => {
    if (!started || showResults || timeLeft <= 0) return;

    const timer = setInterval(() => {
      setTimeLeft((t) => {
        if (t <= 1) {
          clearInterval(timer);
          return 0;
        }
        return t - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [started, showResults, timeLeft]);

  useEffect(() => {
    if (mode !== "video" || !videoLesson || !selectedVideoUrl) return;

    if (!isYouTubeUrl(selectedVideoUrl)) {
      if (ytPlayerRef.current) {
        ytPlayerRef.current.destroy();
        ytPlayerRef.current = null;
      }

      if (ytIntervalRef.current) {
        clearInterval(ytIntervalRef.current);
        ytIntervalRef.current = null;
      }

      currentVideoIdRef.current = null;
      return;
    }

    setYtStarted(false);

    const videoId = getYouTubeVideoId(selectedVideoUrl);
    if (!videoId) return;

    if (currentVideoIdRef.current === videoId && ytPlayerRef.current) {
      return;
    }

    currentVideoIdRef.current = videoId;

    const createPlayer = () => {
      if (ytPlayerRef.current) {
        ytPlayerRef.current.destroy();
        ytPlayerRef.current = null;
      }

      // maxWatchedTime tracks the highest point reached through natural playback.
      // This is the single source of truth for forward-seek enforcement.
      let maxWatchedTime = 0;
      let lastPollTime = 0;
      let seekBackInProgress = false;

      ytPlayerRef.current = new (window as any).YT.Player("youtube-player", {
        videoId,
        playerVars: {
          modestbranding: 1,
          rel: 0,
          iv_load_policy: 3,
          playsinline: 1,
          disablekb: 1,
          fs: 0,
        },
        events: {
          onReady: () => {
            const record = watchedTimeRef.current[lessonId];
            const pendingResume = pendingMediaResumeRef.current;
            const resumeAt =
              pendingResume.lessonId === lessonId &&
              pendingResume.kind === "video" &&
              pendingResume.time > 0
                ? pendingResume.time
                : Math.max(record?.video || 0, record?.audio || 0);

            // Initialize maxWatchedTime from saved progress
            maxWatchedTime = Math.max(
              ytWatchedRef.current[String(lessonId)] || 0,
              lastPlaybackTimeRef.current[lessonId]?.video || 0,
              watchedTimeRef.current[lessonId]?.video || 0,
              resumeAt,
            );

            if (resumeAt > 1 && !hasAutoSeekedRef.current[lessonId]) {
              ytPlayerRef.current.seekTo(resumeAt, true);
              hasAutoSeekedRef.current[lessonId] = true;
              lastPollTime = resumeAt;
              ytCurrentTimeRef.current = resumeAt;
              pendingMediaResumeRef.current = {
                lessonId: null,
                kind: null,
                time: 0,
              };
            }
          },

          onStateChange: (event: any) => {
            const YTState = (window as any).YT.PlayerState;

            if (event.data === YTState.PLAYING) {
              setYtStarted(true);

              if (ytIntervalRef.current) clearInterval(ytIntervalRef.current);

              ytIntervalRef.current = window.setInterval(async () => {
                if (!ytPlayerRef.current) return;

                try {
                  const currentTime =
                    await ytPlayerRef.current.getCurrentTime();
                  const duration = ytPlayerRef.current.getDuration();

                  if (!duration || duration <= 0) return;

                  // Allow unrestricted seeking only when genuinely watched to 80%+
                  if ((maxWatchedTime / duration) * 100 >= 80) {
                    // Unrestricted mode - just track progress
                    if (currentTime > maxWatchedTime) {
                      maxWatchedTime = currentTime;
                    }
                    ytCurrentTimeRef.current = currentTime;
                    ytWatchedRef.current[String(lessonId)] = Math.max(
                      ytWatchedRef.current[String(lessonId)] || 0,
                      maxWatchedTime,
                    );
                    handleTimeUpdate(
                      lessonId,
                      "video",
                      maxWatchedTime,
                      duration,
                    );
                    lastPollTime = currentTime;
                    return;
                  }

                  // HARD ENFORCEMENT: If currentTime exceeds maxWatchedTime + tolerance,
                  // always snap back. No exceptions. No state flags needed.
                  const TOLERANCE = 1.5; // seconds tolerance for natural playback jitter
                  if (currentTime > maxWatchedTime + TOLERANCE) {
                    // Don't spam seekTo if we're already correcting
                    if (!seekBackInProgress) {
                      seekBackInProgress = true;
                      ytPlayerRef.current.seekTo(maxWatchedTime, true);

                      toast({
                        title: "Forward Seeking Disabled",
                        description:
                          "Please watch the video to unlock more content.",
                        variant: "default",
                      });

                      // Reset after a short delay to allow the seek to complete
                      setTimeout(() => {
                        seekBackInProgress = false;
                      }, 300);
                    }
                    // DO NOT update lastPollTime here - keep it at maxWatchedTime
                    lastPollTime = maxWatchedTime;
                    return;
                  }

                  // Normal playback or backward seek - update progress
                  if (
                    currentTime > lastPollTime &&
                    currentTime <= maxWatchedTime + TOLERANCE
                  ) {
                    // Natural forward progress within allowed range
                    if (currentTime > maxWatchedTime) {
                      maxWatchedTime = currentTime;
                    }
                    ytCurrentTimeRef.current = currentTime;
                    ytWatchedRef.current[String(lessonId)] = Math.max(
                      ytWatchedRef.current[String(lessonId)] || 0,
                      maxWatchedTime,
                    );
                    handleTimeUpdate(
                      lessonId,
                      "video",
                      maxWatchedTime,
                      duration,
                    );
                  } else if (currentTime < lastPollTime) {
                    // Backward seek - always allowed, no progress update needed
                    ytCurrentTimeRef.current = currentTime;
                  }

                  lastPollTime = currentTime;
                } catch (error) {
                  console.error("YouTube polling error:", error);
                }
              }, 300); // Poll every 300ms for tighter seek detection
            }

            if (event.data === YTState.PAUSED) {
              if (ytIntervalRef.current) {
                clearInterval(ytIntervalRef.current);
                ytIntervalRef.current = null;
              }
            }

            if (event.data === YTState.ENDED) {
              setYtStarted(true);
              if (ytIntervalRef.current) {
                clearInterval(ytIntervalRef.current);
                ytIntervalRef.current = null;
              }
            }
          },
        },
      });
    };

    if ((window as any).YT?.Player) {
      createPlayer();
    } else {
      (window as any).onYouTubeIframeAPIReady = createPlayer;
    }

    return () => {
      if (ytIntervalRef.current) {
        clearInterval(ytIntervalRef.current);
        ytIntervalRef.current = null;
      }
      if (ytPlayerRef.current) {
        ytPlayerRef.current.destroy();
        ytPlayerRef.current = null;
      }
    };
  }, [lessonId, mode, selectedVideoUrl, videoLesson]);

  useEffect(() => {
    if (!contentId || !lessonTopics.length) return;

    const index = lessonTopics.findIndex(
      (t) => String(getTopicContentId(t)) === String(contentId),
    );

    if (index !== -1) {
      setActiveTopicIndex(index);
      setMode(getPreferredModeForTopic(lessonTopics[index]));
      setActiveQuizType("lesson");
    }
  }, [contentId, lessonTopics]);

  useEffect(() => {
    if (mode !== "video") {
      // 🔥 FULL CLEANUP when leaving video
      if (ytPlayerRef.current) {
        ytPlayerRef.current.destroy();
        ytPlayerRef.current = null;
      }

      if (ytIntervalRef.current) {
        clearInterval(ytIntervalRef.current);
        ytIntervalRef.current = null;
      }

      currentVideoIdRef.current = null;
    }
  }, [mode]);

  useEffect(() => {
    stopMediaHeartbeat("video");
    stopMediaHeartbeat("audio");
  }, [lessonId, mode, selectedAudioUrl, selectedVideoUrl]);

  useEffect(() => {
    return () => {
      stopMediaHeartbeat("video");
      stopMediaHeartbeat("audio");
    };
  }, []);

  useEffect(() => {
    const record = watchedTimeRef.current[lessonId];
    const pendingResume = pendingMediaResumeRef.current;

    if (
      pendingResume.lessonId === lessonId &&
      pendingResume.kind === mode &&
      pendingResume.time > 0
    ) {
      if (mode === "video" && videoRef.current) {
        videoRef.current.currentTime = pendingResume.time;
      }

      if (mode === "audio" && audioRef.current) {
        audioRef.current.currentTime = pendingResume.time;
      }

      pendingMediaResumeRef.current = {
        lessonId: null,
        kind: null,
        time: 0,
      };
      return;
    }

    if (!record) return;

    if (
      mode === "audio" &&
      audioRef.current &&
      record.audio &&
      record.audio > 1
    ) {
      audioRef.current.currentTime = record.audio;
    }
  }, [lessonId, mode, selectedAudioUrl, selectedVideoUrl]);

  const isVideoLocked =
    !!lessonId && progress[lessonId]?.unlocked !== true && lessonProgress < 80;

  const isQuizUnlocked =
    Boolean(quiz) &&
    // 🥇 Highest priority: quiz already submitted
    (quiz.state === "1" ||
      // 🥈 Progress-based unlock
      lessonProgress >= 80);

  const select = (idx: number) => {
    const copy = [...answers];
    copy[currentQuestion] = idx;
    setAnswers(copy);
  };

  const markForReview = () => {
    const copy = [...marked];
    copy[currentQuestion] = !copy[currentQuestion];
    setMarked(copy);
  };

  const areAllLessonQuizzesSubmitted = useMemo(() => {
    return lessonTopics.every((topic) => {
      const lessonProgress = getTopicProgress(topic);
      return lessonProgress >= 80 || isQuizSubmitted(topic);
    });
  }, [lessonTopics, progress]);

  const isPreCertificationUnlocked = useMemo(() => {
    if (!areAllLessonQuizzesSubmitted) return false;
    return mockTest.length === 0 || isQuizSubmitted(mockTest[0]);
  }, [mockTest, areAllLessonQuizzesSubmitted]);
  const isMockUnlocked = () => areAllLessonQuizzesSubmitted;
  const isFinalUnlocked = () =>
    areAllLessonQuizzesSubmitted &&
    (preCertificationTest.length === 0 ||
      isQuizSubmitted(preCertificationTest[0]));

  const isFinalExamLocked = !isFinalUnlocked();

  const now = Date.now();
  const finalQuiz = finalExam?.[0]?.details?.quiz;
  const { start, end } = getQuizWindow(finalQuiz);

  const isWithinDateRange =
    start === null || end === null ? true : now >= start && now <= end;

  // final permission
  const canStartFinal = !isFinalExamLocked && isWithinDateRange;
  // const canStartFinal = isMockUnlocked() && isWithinDateRange;

  // Countdown timer for the final exam
  const [finalCountdown, setFinalCountdown] = useState({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
  });

  useEffect(() => {
    const finalStart = start; // start timestamp from getQuizWindow(finalQuiz)
    if (!finalStart || Date.now() >= finalStart) {
      setFinalCountdown({ days: 0, hours: 0, minutes: 0, seconds: 0 });
      return;
    }

    const updateCountdown = () => {
      const diff = finalStart - Date.now();
      if (diff <= 0) {
        setFinalCountdown({ days: 0, hours: 0, minutes: 0, seconds: 0 });
        return;
      }
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
      const minutes = Math.floor((diff / (1000 * 60)) % 60);
      const seconds = Math.floor((diff / 1000) % 60);
      setFinalCountdown({ days, hours, minutes, seconds });
    };

    updateCountdown();
    const interval = setInterval(updateCountdown, 1000);
    return () => clearInterval(interval);
  }, [start]);

  const getTestTimingStatus = (test: any) => {
    const { start, end } = getQuizWindow(test?.details?.quiz);
    const attempted = test.details.quiz.state === "1";

    if (start === null || end === null) {
      return attempted ? "ATTEMPTED_ACTIVE" : "ACTIVE";
    }

    if (now < start) {
      return "NOT_STARTED";
    }

    if (now >= start && now <= end) {
      return attempted ? "ATTEMPTED_ACTIVE" : "ACTIVE";
    }

    return attempted ? "RESULT_EXPIRED" : "EXPIRED";
  };

  // Result is shown only once result_date has passed; if no result_date
  // is provided by the backend, the result is treated as available.
  const getResultInfo = (quiz: any) => {
    const resultDateMs = quiz?.result_date ? Number(quiz.result_date) : null;
    if (!resultDateMs || isNaN(resultDateMs)) {
      return { available: true, date: null as number | null };
    }
    return { available: Date.now() >= resultDateMs, date: resultDateMs };
  };

  const next = async () => {
    if (currentQuestion < qlist.length - 1) {
      setCurrentQuestion(currentQuestion + 1);
      scrollToTop();
    } else {
      if (showSolution) {
        setShowSolution(false);
        setShowResults(true);
        return;
      }
      setConfirmSubmit(true);
      setTimeTaken(totalDuration - timeLeft);
      // await saveTest();
      scrollToTop();
    }
  };

  const prev = () => {
    if (currentQuestion > 0) setCurrentQuestion(currentQuestion - 1);
  };

  const score = () => {
    let s = 0;
    answers.forEach((a, i) => {
      if (a === qlist[i].correctAnswer) s++;
    });
    return s;
  };
  const s = score();

  const formatTime = (seconds: number) => {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
  };

  const handleContinue = () => {
    setIsOpen(false);
  };

  const [isFullscreenActive, setIsFullscreenActive] = useState(false);

  const showErrorToast = (message: string) => {
    toast({
      title: text.actionRequired,
      description: message,
      variant: "destructive",
    });
  };
  const enterFullscreen = async () => {
    const elem: any = document.getElementById("quiz-fullscreen-box");

    try {
      if (elem.requestFullscreen) {
        await elem.requestFullscreen();
      } else if (elem.webkitRequestFullscreen) {
        await elem.webkitRequestFullscreen();
      }
      setIsFullscreenActive(true);
    } catch (error) {
      console.error("Fullscreen permission error:", error);
      showErrorToast(text.fullscreenPermission);
      setIsQuizActive(false);
    }
  };

  const exitFullscreen = async () => {
    try {
      if (document.exitFullscreen) {
        await document.exitFullscreen();
      } else if ((document as any).webkitExitFullscreen) {
        await (document as any).webkitExitFullscreen();
      }
      setIsFullscreenActive(false);
    } catch (error) {
      console.error("Exit fullscreen error:", error);
    }
  };

  const fetchTestData = async (id: any, user: string, course: string) => {
    try {
      const res = await getTestData(user, id, course || "1");

      if (res?.status && res.data) {
        setTestData(res.data);
        setTimeLeft(parseInt(res.data.test_basic.time_in_mins) * 60 || 300);
        const durationInSeconds =
          Number(res.data.test_basic.time_in_mins) * 60 || 0;

        setTotalDuration(durationInSeconds);
        setTimeLeft(durationInSeconds);
        if (selectedLanguage === "hindi") {
          if (
            !res?.data?.questions_hindi ||
            res.data.questions_hindi.length === 0
          ) {
            toast({
              title: "No Hindi Questions Available",
              description:
                "The Hindi version of this test is currently unavailable. Please select English to proceed.",
            });
            setShowInstructions(false);
            return;
          }
        } else if (selectedLanguage === "english") {
          if (!res?.data?.questions || res.data.questions.length === 0) {
            toast({
              title: "No English Questions Available",
              description:
                "The English version of this test is currently unavailable. Please select Hindi to proceed.",
            });
            setShowInstructions(false);
            return;
          }
        }
        setShowInstructions(true);
      }
    } catch (err) {
      console.error("❌ Failed to load test:", err);
    }
  };

  const fetchInstructions = async (id: any, courseId: any) => {
    const body = new FormData();
    body.append("course_id", courseId || "1");
    body.append("test_id", id);
    body.append("user_id", userData?.id || "1");

    const res = await getTestInstructionData(body);
    setInstructionData(res.data);
  };

  const requestQuizStart = (testId: string, selectedCourseId: string) => {
    setPendingQuizStart({
      testId,
      courseId: selectedCourseId || courseId || "1",
    });
    setShowLanguageModal(true);
  };

  const handleLanguageModalContinue = () => {
    setShowLanguageModal(false);

    if (!pendingQuizStart) {
      return;
    }

    fetchInstructions(pendingQuizStart.testId, pendingQuizStart.courseId);
    fetchTestData(
      pendingQuizStart.testId,
      userData?.id,
      pendingQuizStart.courseId,
    );
    setPendingQuizStart(null);
  };

  const buildQuestionDump = () => {
    if (!qlist) return [];

    return qlist.map((q: any, index: number) => {
      const selected = answers[index]; // number | number[] | undefined
      const isVisited = visited[index];
      const timeSpent = 0;
      const isMarkedForReview = marked[index];

      let state = "not_visited";
      let answersArray: string[] = [];

      // detect total options
      const totalOptions = q.option_10
        ? 10
        : q.option_9
          ? 9
          : q.option_8
            ? 8
            : q.option_7
              ? 7
              : q.option_6
                ? 6
                : q.option_5
                  ? 5
                  : q.option_4
                    ? 4
                    : q.option_3
                      ? 3
                      : 2;

      if (!isVisited) {
        state = "not_visited";
      } else if (
        selected === undefined ||
        (Array.isArray(selected) && selected.length === 0)
      ) {
        state = "unanswered";
      } else {
        state = "answered";
      }

      // ⭐ OVERRIDE STATE IF MARKED FOR REVIEW
      if (isMarkedForReview) {
        state = "marked_for_review";
      }

      // ---------- ANSWER BITMASK ----------
      if (state === "answered" || state === "marked_for_review") {
        const bitmask = Array(totalOptions).fill("0");

        // SC
        if (typeof selected === "number") {
          if (selected >= 0 && selected < totalOptions) {
            bitmask[selected] = "1";
          }
        }

        // MC
        if (Array.isArray(selected)) {
          selected.forEach((i) => {
            if (i >= 0 && i < totalOptions) {
              bitmask[i] = "1";
            }
          });
        }
        answersArray = bitmask;
      }

      return {
        config_id: q.config_id,
        section_id: q.section_id,
        index: String(index),
        state,
        answers: answersArray, // 🔥 ONLY ["0","1","0","0"]
        on_screen: String(timeSpent),
      };
    });
  };

  const saveTest = async () => {
    const questionDump = buildQuestionDump();
    const langUsed = testData?.test_basic?.lang_id?.includes("1") ? "1" : "2";
    const actualLanguage = selectedLanguage === "english" ? "english" : "hindi";

    const payload = new FormData();
    payload.append("user_id", userData?.id || "1");
    payload.append("test_series_id", quiz?.test_id || "1");
    payload.append("course_id", String(courseId) || "1");
    payload.append("time_remain", String(timeLeft));
    payload.append("question_dump", JSON.stringify(questionDump));
    payload.append("last_view", String(currentQuestion));
    payload.append("lang_used", actualLanguage === "english" ? "1" : "2");
    payload.append("state", "1");
    payload.append("first_attempt", "1");

    try {
      const res = await saveTestV2(payload);
    } catch (err: any) {
      console.error("❌ Save test failed:", err?.response?.data || err.message);
    }
  };

  const getTestResultdata = async () => {
    try {
      if (!testData?.test_basic?.id) return;

      const res = await getTestResult(
        userData?.id,
        quiz?.test_id,
        courseId,
        "1",
      );

      if (!res?.data || !res.data.questions) return;

      const questions = res.data.questions;

      let correct = 0;
      let wrong = 0;
      let skipped = 0;

      questions.forEach((q: any, index: number) => {
        const userAnswer = answers[index]; // 0-based
        const correctAnswer = Number(q.answer) - 1; // backend is 1-based

        if (userAnswer === undefined) {
          skipped++;
        } else if (userAnswer === correctAnswer) {
          correct++;
        } else {
          wrong++;
        }
      });

      setTestResult({
        correct,
        wrong,
        skipped,
        total: questions.length,
        rank: res.data.user_rank,
        totalParticipants: res.data.total_user_attempt,
        percentile: res.data.percentile,
        total_marks: res.data.total_marks,
        questions: res.data.questions,
        data: res.data,
      });
    } catch (err) {
      console.error("❌ Failed to fetch test result:", err);
    }
  };

  const correct = testResult?.correct ?? 0;
  const wrong = testResult?.wrong ?? 0;
  const skipped = testResult?.skipped ?? 0;

  const totalAttempted = correct + wrong;
  const rank = testResult?.rank;
  const totalParticipants = testResult?.totalParticipants;

  useEffect(() => {
    const handleFullscreenChange = async () => {
      const isInFullscreen =
        document.fullscreenElement || (document as any).webkitFullscreenElement;

      setIsFullscreenActive(!!isInFullscreen);

      // if (!isInFullscreen && isQuizActive && testEnd) {
      //   const confirmLeave = window.confirm(text.fullscreenReturn);

      //   if (confirmLeave) {
      //     enterFullscreen();
      //   } else {
      //     // exitFullscreen()
      //     return;
      //   }
      // }

      if (
        !isInFullscreen &&
        isQuizActive &&
        !showResults &&
        !isSubmittingTestRef.current
      ) {
        // ❌ DON'T call enterFullscreen here
        setShowFullscreenModal(true);
      }
    };

    document.addEventListener("fullscreenchange", handleFullscreenChange);
    document.addEventListener("webkitfullscreenchange", handleFullscreenChange);

    return () => {
      document.removeEventListener("fullscreenchange", handleFullscreenChange);
      document.removeEventListener(
        "webkitfullscreenchange",
        handleFullscreenChange,
      );
    };
  }, [isQuizActive, showResults]);

  useEffect(() => {
    if (isQuizActive) {
      setTimeout(() => {
        enterFullscreen();
      }, 50);
    }
  }, [isQuizActive]);

  const handleStartQuiz = async () => {
    isSubmittingTestRef.current = false;
    setStarted(true);
    setIsQuizActive(true);
    setHidePreviewBar(true);
    setConfirmSubmit(false);
  };

  useEffect(() => {
    const hasSeenGuidelines = localStorage.getItem("guidelines_seen");

    if (!hasSeenGuidelines) {
      setShowGuidelineContinue(true);
      setIsOpen(true);
      localStorage.setItem("guidelines_seen", "true");
    }
  }, []);

  useEffect(() => {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) setProgress(JSON.parse(raw));
    else {
      const init: ProgressRecord = {};
      LESSONS.forEach((l, idx) => {
        init[l.id] = { video: 0, audio: 0, unlocked: idx === 0 };
      });
      setProgress(init);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(init));
    }
  }, []);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(progress));
  }, [progress]);

  const formatAudioTime = (time: number) => {
    if (!time || isNaN(time)) return "00:00";

    const hrs = Math.floor(time / 3600);
    const mins = Math.floor((time % 3600) / 60);
    const secs = Math.floor(time % 60);

    if (hrs > 0) {
      return `${hrs.toString().padStart(2, "0")}:${mins
        .toString()
        .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
    }

    return `${mins.toString().padStart(2, "0")}:${secs
      .toString()
      .padStart(2, "0")}`;
  };

  const watchedTimeRef = useRef<{
    [lessonId: number]: {
      video?: number;
      audio?: number;
    };
  }>({});

  // Track the last seek time to prevent forward seeks
  const lastAudioSeekRef = useRef<{
    [lessonId: number]: number;
  }>({});

  const maxAudioSeekRef = useRef<{
    [lessonId: number]: number;
  }>({});

  const syncMediaTimeOnModeChange = (
    fromMode: "video" | "audio",
    toMode: "video" | "audio",
  ) => {
    if (!lessonId) return;

    // During audio replay, don't sync the low currentTime — progress is already at 100%
    if (fromMode === "audio" && audioReplayingRef.current) {
      // Reset replay state when switching away
      audioReplayingRef.current = false;
      setAudioEnded(false);
      return;
    }

    let currentTime = 0;

    // Capture current time from the mode we're leaving
    if (fromMode === "video") {
      if (isYouTubeUrl(selectedVideoUrl)) {
        currentTime = ytPlayerRef.current?.getCurrentTime?.() || 0;
      } else {
        currentTime = videoRef.current?.currentTime || 0;
      }
    } else if (fromMode === "audio") {
      currentTime = audioRef.current?.currentTime || 0;
    }

    // Store the time so it can be applied to the new mode
    if (currentTime > 0 || currentTime === 0) {
      if (!watchedTimeRef.current[lessonId]) {
        watchedTimeRef.current[lessonId] = {};
      }

      // Update both video and audio to the same time for sync
      watchedTimeRef.current[lessonId].video = currentTime;
      watchedTimeRef.current[lessonId].audio = currentTime;

      // Set pending resume for immediate application
      pendingMediaResumeRef.current = {
        lessonId,
        kind: toMode,
        time: currentTime,
      };

      // Initialize max seek time for the new audio session
      if (toMode === "audio") {
        maxAudioSeekRef.current[lessonId] = currentTime;
        lastAudioSeekRef.current[lessonId] = currentTime;
      }

      // Allow the (re)created video player to seek to the resume time.
      // The YouTube player only seeks in onReady when this flag is false,
      // and it is otherwise reset only on lesson/url change — so without
      // this, switching audio → video would start the video from 0.
      if (toMode === "video") {
        hasAutoSeekedRef.current[lessonId] = false;
      }
    }
  };

  const saveProgressToServer = async (
    lessonId: number,
    kind: "video" | "audio",
    currentTime: number,
    duration: number,
    percentageTime: number = currentTime,
  ) => {
    if (!duration || duration <= 0) return;

    const fd = new FormData();
    fd.append("user_id", userData?.id || "1");
    fd.append("course_id", courseId || "1");
    fd.append("topic_id", String(activeTopic?.topic_id || quiz?.topic_id));
    fd.append("content_id", String(lessonId));
    fd.append("mode", kind === "video" ? "3" : "4");
    fd.append("current_time", Math.floor(currentTime).toString());
    fd.append("total_duration", Math.floor(duration).toString());
    fd.append(
      "percentage",
      Math.min((percentageTime / duration) * 100, 100).toFixed(2),
    );
    fd.append("language", getLanguageId(selectedLanguage));
    fd.append("flag", "0");

    try {
      await updateTestProgress(fd);
    } catch (err) {
      console.error("❌ Progress save failed", err);
    }
  };

  const shouldSendProgressUpdate = (
    lessonId: number,
    kind: "video" | "audio",
    currentTime: number,
    force = false,
  ) => {
    if (!lastProgressSaveRef.current[lessonId]) {
      lastProgressSaveRef.current[lessonId] = {};
    }

    const lastSavedAt = lastProgressSaveRef.current[lessonId][kind];

    if (
      force ||
      typeof lastSavedAt !== "number" ||
      currentTime - lastSavedAt >= PROGRESS_PING_SECONDS
    ) {
      lastProgressSaveRef.current[lessonId][kind] = currentTime;
      return true;
    }

    return false;
  };

  const stopMediaHeartbeat = (kind: "video" | "audio") => {
    if (mediaIntervalRef.current[kind]) {
      clearInterval(mediaIntervalRef.current[kind]!);
      mediaIntervalRef.current[kind] = null;
    }
  };

  const startMediaHeartbeat = (lessonId: number, kind: "video" | "audio") => {
    if (kind === "video" && isYouTubeUrl(selectedVideoUrl)) return;
    if (mediaIntervalRef.current[kind]) return;

    mediaIntervalRef.current[kind] = window.setInterval(() => {
      const mediaEl = kind === "video" ? videoRef.current : audioRef.current;

      if (!mediaEl || mediaEl.paused || mediaEl.ended) {
        stopMediaHeartbeat(kind);
        return;
      }

      handleTimeUpdate(lessonId, kind);
    }, PROGRESS_PING_SECONDS * 1000);
  };

  const saveBackwardSeekProgress = (
    lessonId: number,
    kind: "video" | "audio",
    currentTime: number,
    duration: number,
  ) => {
    if (!duration || duration <= 0) return false;

    if (!lastPlaybackTimeRef.current[lessonId]) {
      lastPlaybackTimeRef.current[lessonId] = {};
    }

    const lastPlaybackTime = lastPlaybackTimeRef.current[lessonId][kind];
    const isBackwardSeek =
      typeof lastPlaybackTime === "number" &&
      currentTime < lastPlaybackTime - 1;

    lastPlaybackTimeRef.current[lessonId][kind] = currentTime;

    if (isBackwardSeek && !isQuizActive) {
      const record = watchedTimeRef.current[lessonId];
      const highestWatchedTime = Math.max(
        record?.video || 0,
        record?.audio || 0,
        currentTime,
      );

      saveProgressToServer(
        lessonId,
        kind,
        currentTime,
        duration,
        highestWatchedTime,
      );
    }

    return isBackwardSeek;
  };

  const handleTimeUpdate = (
    lessonId: number,
    kind: "video" | "audio",
    currentSeconds?: number,
    totalDuration?: number,
  ) => {
    const isYouTube = kind === "video" && typeof currentSeconds === "number";

    const el =
      !isYouTube && kind === "video"
        ? videoRef.current
        : !isYouTube && kind === "audio"
          ? audioRef.current
          : null;

    const resolvedDuration =
      durationRef.current[lessonId] ||
      (isYouTube ? totalDuration : el?.duration) ||
      0;

    if (!resolvedDuration || resolvedDuration <= 0) return;

    // store duration once
    durationRef.current[lessonId] = resolvedDuration;

    const currentTime = isYouTube ? currentSeconds! : el?.currentTime || 0;

    const isBackwardSeek =
      !isYouTube &&
      saveBackwardSeekProgress(lessonId, kind, currentTime, resolvedDuration);

    if (!watchedTimeRef.current[lessonId]) {
      watchedTimeRef.current[lessonId] = { video: 0, audio: 0 };
    }
    if (!lastTrackedTimeRef.current[lessonId]) {
      lastTrackedTimeRef.current[lessonId] = {};
    }

    const record = watchedTimeRef.current[lessonId];
    const lastTrackedTime = lastTrackedTimeRef.current[lessonId][kind];
    const delta =
      typeof lastTrackedTime === "number" ? currentTime - lastTrackedTime : 0;

    lastTrackedTimeRef.current[lessonId][kind] = currentTime;

    if (isYouTube || ENABLE_SKIP_PROGRESS_FOR_TESTING) {
      record[kind] = Math.max(record[kind] || 0, currentTime);
    } else if (!isBackwardSeek && delta > 0 && delta <= 5) {
      record[kind] = Math.min((record[kind] || 0) + delta, resolvedDuration);
    }

    // ✅ UNIQUE watched timeline (correct logic)
    const uniqueWatched = Math.max(record.video || 0, record.audio || 0);
    const percent = Math.min((uniqueWatched / resolvedDuration) * 100, 100);
    const prevPercent = Math.max(
      progress[lessonId]?.video || 0,
      progress[lessonId]?.audio || 0,
    );

    const crossed80 = prevPercent < 80 && percent >= 80;
    if (!isQuizActive) {
      setProgress((prev) => ({
        ...prev,
        [lessonId]: {
          ...(prev[lessonId] || {}),
          video: percent,
          audio: percent,
          unlocked: percent >= 80 || prev[lessonId]?.unlocked,
        },
      }));

      if (crossed80) {
        saveProgressToServer(lessonId, kind, uniqueWatched, resolvedDuration);
      }

      if (
        !isBackwardSeek &&
        shouldSendProgressUpdate(lessonId, kind, uniqueWatched)
      ) {
        saveProgressToServer(lessonId, kind, uniqueWatched, resolvedDuration);
      }
    }

    // 🔓 Unlock logic
  };

  const isLessonUnlocked = (index: number): boolean => {
    if (index === 0) return true;

    const prevTopic = lessonTopics[index - 1];
    if (!prevTopic) return false;

    const prevVideoId = getTopicContentId(prevTopic);
    const prevQuiz = prevTopic.details?.quiz;

    const prevProgress = prevVideoId
      ? Math.max(
          progress[prevVideoId]?.video || 0,
          progress[prevVideoId]?.audio || 0,
        )
      : 0;

    const prevQuizUnlocked = isQuizUnlockSequence(prevTopic, prevProgress);

    return prevQuizUnlocked;
  };

  const scrollToTop = () => {
    if (typeof window !== "undefined") {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    }
  };

  const isBackendVideoLocked = (video: any) => {
    return String(video?.is_locked) === "0"; // 0 locked, 1 unlocked
  };

  const isUnlocked = (topic: any): boolean => {
    const quiz = topic?.details?.quiz;
    if (!quiz) return false;

    // 0 = locked, 1 = unlocked
    return String(quiz.is_locked) === "1";
  };
  const isQuizUnlock = (topic: any, lessonProgress: number): boolean => {
    const quiz = topic?.details?.quiz;
    if (!quiz) return false;

    // Already submitted

    if (String(quiz.state) === "1") return false;

    // 🔥 Backend unlock priority
    if (String(quiz.is_locked) === "1") return true;

    // Progress-based unlock
    return lessonProgress >= 80;
  };
  const isQuizUnlockSequence = (
    topic: any,
    lessonProgress: number,
  ): boolean => {
    const quiz = topic?.details?.quiz;
    if (!quiz) return false;

    // 🔥 Backend unlock priority
    if (String(quiz.is_locked) === "1") return true;

    // Already submitted
    if (String(quiz.state) === "1") return true;

    // Progress-based unlock
    return lessonProgress >= 80;
  };

  const getQuizActionLabel = (
    quiz: any,
    topic: any,
    lessonProgress: number,
  ) => {
    const nowMs = Date.now();

    // 🔓 If unlocked by progress, allow start
    if (isQuizUnlock(topic, lessonProgress)) {
      return "START_TEST";
    }

    if (quiz.state === "1") {
      return "VIEW_RESULT";
    }

    if (quiz.start_date && quiz.end_date) {
      const nowSec = Math.floor(nowMs / 1000);
      const startSec = Math.floor(Number(quiz.start_date) / 1000);
      const endSec = Math.floor(Number(quiz.end_date) / 1000);

      if (nowSec < startSec) return "UPCOMING_TEST";
      if (nowSec > endSec) return "EXPIRED_TEST";
    }

    return "START_TEST";
  };

  const getTimeLeft = (target: number) => {
    const diff = target - Date.now();

    if (diff <= 0) return "00:00";

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
    const minutes = Math.floor((diff / (1000 * 60)) % 60);
    const seconds = Math.floor((diff / 1000) % 60);

    if (days > 0) {
      return `${days}${text.timeUnits.day} ${hours}${text.timeUnits.hour} ${minutes}${text.timeUnits.minute}`;
    }
    return `${hours}${text.timeUnits.hour} ${minutes}${text.timeUnits.minute} ${seconds}${text.timeUnits.second}`;
  };

  const formatDateTime = (ts: number) => {
    return new Date(ts).toLocaleString("en-IN", {
      day: "2-digit",
      month: "short",
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
    });
  };

  const shouldShowStartButton =
    (activeCard === "mock" && isMockUnlocked()) ||
    (activeCard === "pre" && isPreCertificationUnlocked) ||
    (activeCard === "final" && canStartFinal);

  return (
    <div className="pt-6 pb-12 min-h-screen bg-gradient-to-br from-orange-50 to-white">
      {isQuizActive ? (
        <div
          className="bg-gradient-to-br from-orange-50 to-white"
          id="quiz-fullscreen-box"
        >
          {showResults ? (
            <TestResultUI
              testResult={testResult?.data}
              formatTime={formatTime}
              scrollToTop={scrollToTop}
              setShowPreview={setShowPreview}
              setShowResults={setShowResults}
              setConfirmSubmit={setConfirmSubmit}
              setCurrentQuestion={setCurrentQuestion}
              setShowSolution={setShowSolution}
              gocod={gocod}
            />
          ) : (
            <>
              <div className="lg:hidden fixed top-4 right-4 z-40">
                <button
                  onClick={() => setShowMobileSidebar(true)}
                  className="bg-orange-500 text-white px-4 py-2 rounded-lg shadow"
                >
                  {text.viewQuestions}
                </button>
              </div>

              {/* ===== MAIN WRAPPER ===== */}
              <div className="container mx-auto px-4 mt-20">
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                  {/* ---------------- LEFT SIDE (60%) ---------------- */}
                  <div className="lg:col-span-2">
                    <div className="bg-white shadow rounded-lg p-6 min-h-[600px] flex items-center justify-center">
                      <InlineQuiz
                        testData={testData}
                        answers={answers}
                        setAnswers={setAnswers}
                        currentQuestion={currentQuestion}
                        setCurrentQuestion={setCurrentQuestion}
                        marked={marked}
                        setMarked={setMarked}
                        timeLeft={timeLeft}
                        formatTime={formatTime}
                        next={next}
                        prev={prev}
                        score={score}
                        showResults={showResults}
                        setShowResults={setShowResults}
                        showSolution={showSolution}
                        setShowSolution={setShowSolution}
                        confirmSubmit={confirmSubmit}
                        setConfirmSubmit={setConfirmSubmit}
                        saveTest={saveTest}
                        getTestResultdata={getTestResultdata}
                        exitFullscreen={exitFullscreen}
                        totalDuration={totalDuration}
                        setTimeTaken={setTimeTaken}
                        scrollToTop={scrollToTop}
                        showPreview={showPreview}
                        setShowPreview={setShowPreview}
                        setTestEnd={setTestEnd}
                        setHidePreviewBar={setHidePreviewBar}
                        solutionQuestionList={testResult?.questions || []}
                        selectedLanguage={selectedLanguage}
                        returnToTestListAfterSubmit={
                          activeQuizType === "mock" ||
                          activeQuizType === "pre" ||
                          activeQuizType === "final"
                        }
                        onSubmitStart={() => {
                          isSubmittingTestRef.current = true;
                          setShowFullscreenModal(false);
                        }}
                      />
                    </div>
                  </div>

                  {/* ---------------- RIGHT SIDE (40%) — DESKTOP ONLY ---------------- */}
                  {hidePreviewBar && (
                    <div className="hidden lg:block">
                      <QuizSidebar
                        title={
                          selectedLanguage === "hindi"
                            ? quiz.test_series_name_hindi
                            : quiz.test_series_name
                        }
                        qlist={qlist}
                        answers={answers}
                        marked={marked}
                        currentQuestion={currentQuestion}
                        setCurrentQuestion={setCurrentQuestion}
                        setConfirmSubmit={setConfirmSubmit}
                        showSolution={showSolution}
                      />
                    </div>
                  )}
                  {showSolution && (
                    <div className="hidden lg:block">
                      <QuizSidebar
                        title={
                          selectedLanguage === "hindi"
                            ? quiz.test_series_name_hindi
                            : quiz.test_series_name
                        }
                        qlist={qlist}
                        answers={answers}
                        marked={marked}
                        currentQuestion={currentQuestion}
                        setCurrentQuestion={setCurrentQuestion}
                        setConfirmSubmit={setConfirmSubmit}
                        showSolution={showSolution}
                      />
                    </div>
                  )}
                </div>
              </div>

              {/* ---------------- MOBILE MODAL SIDEBAR ---------------- */}
              {showMobileSidebar && hidePreviewBar && (
                <div className="fixed inset-0 bg-black/50 z-50 flex justify-end">
                  <div className="w-[90%] sm:w-[380px] h-full bg-white p-6 overflow-y-auto shadow-xl">
                    <button
                      className="text-gray-600 mb-4"
                      onClick={() => setShowMobileSidebar(false)}
                    >
                      {text.close}
                    </button>

                    <QuizSidebar
                      title={
                        selectedLanguage === "hindi"
                          ? quiz.test_series_name_hindi
                          : quiz.test_series_name
                      }
                      qlist={qlist}
                      answers={answers}
                      marked={marked}
                      currentQuestion={currentQuestion}
                      setCurrentQuestion={setCurrentQuestion}
                      setConfirmSubmit={setConfirmSubmit}
                      showSolution={showSolution}
                    />
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      ) : (
        <div className="container mx-auto px-4 mt-20">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2">
              {/* HEADER */}
              <div className="flex items-center justify-between bg-[#FAA631] text-white p-3 rounded-t-lg">
                <h2 className="font-semibold text-lg">
                  {activeTopic?.details?.topic_name || text.defaultTopicTitle}
                </h2>
              </div>

              {/* PLAYER */}
              <div className="bg-black rounded-b-lg overflow-hidden">
                {/* VIDEO */}
                {mode === "video" && videoLesson && (
                  <>
                    {isYouTubeUrl(selectedVideoUrl) ? (
                      /* 🎥 YouTube Player */
                      <div
                        key={selectedVideoUrl}
                        className="relative w-full h-[480px] rounded-xl overflow-hidden bg-black"
                      >
                        <style jsx global>{`
                          .ytp-more-videos-view a.ytp-suggestion-link {
                            cursor: not-allowed !important;
                            pointer-events: none !important;
                          }
                        `}</style>

                        <div id="youtube-player" className="w-full h-full" />

                        {/* 🔒 Block suggestions ONLY after video starts */}
                        {/* { ytStarted && (
                          <div className="absolute inset-0 z-10 pointer-events-auto" />
                        )} */}

                        {/* ✅ Always allow bottom controls */}
                        <div className="absolute bottom-0 left-0 w-full h-20 z-20 pointer-events-none" />
                      </div>
                    ) : (
                      /* 🎞️ Normal MP4 Video */
                      <video
                        ref={videoRef}
                        src={selectedVideoUrl}
                        controls
                        className="w-full h-[480px] bg-black rounded-xl"
                        onCanPlay={(e) => {
                          setVideoReadyToPlay(true);
                          const pendingResume = pendingMediaResumeRef.current;

                          if (
                            pendingResume.lessonId === videoLesson.id &&
                            pendingResume.kind === "video" &&
                            pendingResume.time >= 0
                          ) {
                            e.currentTarget.currentTime = pendingResume.time;
                            pendingMediaResumeRef.current = {
                              lessonId: null,
                              kind: null,
                              time: 0,
                            };
                            return;
                          }

                          const record = watchedTimeRef.current[videoLesson.id];
                          // Check both video and audio times, use the max (for sync between modes)
                          const resumeTime = Math.max(
                            record?.video || 0,
                            record?.audio || 0,
                          );

                          if (resumeTime > 1) {
                            e.currentTarget.currentTime = resumeTime;
                          }
                        }}
                        onLoadedMetadata={(e) => {
                          // Reset state when video source changes
                          setVideoReadyToPlay(false);
                        }}
                        onPlay={() =>
                          startMediaHeartbeat(videoLesson.id, "video")
                        }
                        onPause={() => {
                          stopMediaHeartbeat("video");
                          handleTimeUpdate(videoLesson.id, "video");
                        }}
                        onEnded={() => {
                          stopMediaHeartbeat("video");
                          handleTimeUpdate(videoLesson.id, "video");
                        }}
                        onTimeUpdate={() =>
                          handleTimeUpdate(videoLesson.id, "video")
                        }
                        onSeeking={(e) => {
                          if (videoSeekLockRef.current) return;

                          const currentTime = e.currentTarget.currentTime;
                          const duration = e.currentTarget.duration;

                          const overallProgress = Math.max(
                            progress[videoLesson.id]?.video || 0,
                            progress[videoLesson.id]?.audio || 0,
                          );

                          // Allow unrestricted seeking once 80%+ genuinely watched or API confirmed
                          if (overallProgress >= 80) {
                            saveBackwardSeekProgress(
                              videoLesson.id,
                              "video",
                              currentTime,
                              duration,
                            );
                            return;
                          }

                          // Max position reached through natural playback (seconds)
                          const maxAllowed =
                            watchedTimeRef.current[videoLesson.id]?.video || 0;
                          const TOLERANCE = 1.5;

                          if (currentTime > maxAllowed + TOLERANCE) {
                            videoSeekLockRef.current = true;
                            e.currentTarget.currentTime = maxAllowed;
                            setTimeout(() => {
                              videoSeekLockRef.current = false;
                            }, 100);
                            toast({
                              title: "Forward Seeking Disabled",
                              description:
                                "Please watch the video to unlock more content.",
                              variant: "default",
                            });
                            return;
                          }

                          // Backward seek or within natural range — allow
                          saveBackwardSeekProgress(
                            videoLesson.id,
                            "video",
                            currentTime,
                            duration,
                          );
                        }}
                      />
                    )}
                  </>
                )}

                {/* AUDIO */}
                {mode === "audio" && audioLesson && (
                  <div className="bg-[#FFF4E4] p-5">
                    <div className="flex items-center gap-4 mb-4">
                      <img
                        src={audioLesson.thumbnail_url}
                        alt={audioLesson.title}
                        className="w-20 h-20 rounded-lg object-cover"
                      />
                      <p className="text-lg font-semibold text-gray-900">
                        {audioLesson.title}
                      </p>
                    </div>

                    {/* AUDIO CONTROLS */}
                    <div className="flex justify-center items-center gap-8 py-4">
                      <button
                        onClick={() => {
                          if (!audioRef.current || !lessonId) return;

                          const nextTime = Math.max(
                            audioRef.current.currentTime - 10,
                            0,
                          );

                          audioRef.current.currentTime = nextTime;
                          lastAudioSeekRef.current[lessonId] = nextTime;

                          saveBackwardSeekProgress(
                            lessonId,
                            "audio",
                            nextTime,
                            audioRef.current.duration,
                          );
                        }}
                      >
                        <RotateCcw
                          className="w-10 h-10 text-[#FAA631]"
                          strokeWidth={1.5}
                        />
                      </button>

                      <button
                        onClick={() => {
                          if (!audioRef.current) return;
                          if (audioEnded) {
                            audioReplayingRef.current = true;
                            audioRef.current.currentTime = 0;
                            audioRef.current.play();
                            setAudioEnded(false);
                          } else {
                            audioRef.current.paused
                              ? audioRef.current.play()
                              : audioRef.current.pause();
                          }
                        }}
                        className="bg-white p-4 rounded-full shadow-lg"
                      >
                        {audioEnded ? (
                          <RotateCw
                            className="w-9 h-9 text-[#FAA631]"
                            strokeWidth={1.5}
                          />
                        ) : audioRef.current?.paused !== false ? (
                          <Play
                            className="w-9 h-9 text-[#FAA631]"
                            strokeWidth={1.5}
                          />
                        ) : (
                          <Pause
                            className="w-9 h-9 text-[#FAA631]"
                            strokeWidth={1.5}
                          />
                        )}
                      </button>

                      <button
                        onClick={() => {
                          if (!audioRef.current || !lessonId) return;

                          const newTime = audioRef.current.currentTime + 10;
                          const maxAllowed =
                            maxAudioSeekRef.current[lessonId] ||
                            audioRef.current.currentTime;
                          const duration = audioRef.current.duration || 1;

                          // Use overall lesson progress (genuinely listened/watched)
                          const overallProgress = Math.max(
                            progress[lessonId]?.video || 0,
                            progress[lessonId]?.audio || 0,
                          );

                          // Allow forward seeking if overall progress >= 80%
                          if (overallProgress >= 80) {
                            audioRef.current.currentTime = newTime;
                            return;
                          }

                          // Prevent forward seeking beyond watched content if progress < 80%
                          if (newTime > maxAllowed + 1) {
                            toast({
                              title: "Forward Seeking Disabled",
                              description:
                                "Please listen to the audio to unlock more content.",
                              variant: "default",
                            });
                            return;
                          }

                          audioRef.current.currentTime = newTime;

                          // Update max seek time if we're advancing legitimately
                          if (newTime <= maxAllowed + 1) {
                            maxAudioSeekRef.current[lessonId] = Math.max(
                              maxAllowed,
                              newTime,
                            );
                          }

                          saveBackwardSeekProgress(
                            lessonId,
                            "audio",
                            newTime,
                            audioRef.current.duration,
                          );
                        }}
                      >
                        <RotateCw
                          className="w-10 h-10 text-[#FAA631]"
                          strokeWidth={1.5}
                        />
                      </button>
                    </div>

                    {/* HIDDEN AUDIO */}
                    <audio
                      ref={audioRef}
                      src={selectedAudioUrl}
                      className="hidden"
                      onLoadedMetadata={(e) => {
                        const pendingResume = pendingMediaResumeRef.current;
                        if (
                          pendingResume.lessonId === lessonId &&
                          pendingResume.kind === "audio" &&
                          pendingResume.time > 0
                        ) {
                          e.currentTarget.currentTime = pendingResume.time;

                          // Initialize max seek time for forward seek prevention
                          maxAudioSeekRef.current[lessonId] =
                            pendingResume.time;
                          lastAudioSeekRef.current[lessonId] =
                            pendingResume.time;

                          pendingMediaResumeRef.current = {
                            lessonId: null,
                            kind: null,
                            time: 0,
                          };
                          return;
                        }

                        const record = watchedTimeRef.current[lessonId];
                        if (record?.audio && record.audio > 1) {
                          e.currentTarget.currentTime = record.audio;

                          // Initialize max seek time for forward seek prevention
                          maxAudioSeekRef.current[lessonId] = record.audio;
                          lastAudioSeekRef.current[lessonId] = record.audio;
                        } else {
                          // Start from beginning
                          maxAudioSeekRef.current[lessonId] = 0;
                          lastAudioSeekRef.current[lessonId] = 0;
                        }
                      }}
                      onPlay={() => {
                        setAudioEnded(false);
                        // Don't start heartbeat during replay — progress already at 100%
                        if (!audioReplayingRef.current) {
                          startMediaHeartbeat(lessonId, "audio");
                        } else {
                          // If somehow play is triggered outside the replay button,
                          // keep audioReplayingRef true only if we're still at 100% progress
                          const duration = audioRef.current?.duration || 1;
                          const record = watchedTimeRef.current[lessonId];
                          const maxWatched = Math.max(
                            record?.video || 0,
                            record?.audio || 0,
                          );
                          if (maxWatched < duration * 0.8) {
                            // Progress isn't actually at 80%+, this shouldn't be a replay
                            audioReplayingRef.current = false;
                            startMediaHeartbeat(lessonId, "audio");
                          }
                        }
                      }}
                      onPause={() => {
                        stopMediaHeartbeat("audio");
                        // Don't save progress during replay — it would overwrite with a low time
                        if (!audioReplayingRef.current) {
                          handleTimeUpdate(lessonId, "audio");
                        }
                      }}
                      onEnded={() => {
                        stopMediaHeartbeat("audio");
                        // Only save progress if not replaying
                        if (!audioReplayingRef.current) {
                          handleTimeUpdate(lessonId, "audio");
                        }
                        setAudioEnded(true);
                        audioReplayingRef.current = false;
                      }}
                      onTimeUpdate={() => {
                        if (!audioRef.current || !lessonId) return;

                        // Update max seek allowed time as user listens
                        const currentTime = audioRef.current.currentTime;
                        const maxSoFar = maxAudioSeekRef.current[lessonId] || 0;

                        if (currentTime > maxSoFar) {
                          maxAudioSeekRef.current[lessonId] = currentTime;
                        }

                        lastAudioSeekRef.current[lessonId] = currentTime;

                        // Skip progress saving during replay (audio already completed)
                        if (audioReplayingRef.current) return;

                        handleTimeUpdate(lessonId, "audio");
                      }}
                      onSeeking={() => {
                        if (!audioRef.current || !lessonId) return;

                        // During replay, allow free seeking without saving progress
                        if (audioReplayingRef.current) return;

                        // Prevent re-entrant seeking (from programmatic currentTime reset)
                        if (audioSeekLockRef.current) return;

                        const currentTime = audioRef.current.currentTime;
                        const maxAllowed =
                          maxAudioSeekRef.current[lessonId] || 0;
                        const duration = audioRef.current.duration || 1;

                        // Use overall lesson progress (how much has been listened/watched)
                        // NOT the seek target position
                        const overallProgress = Math.max(
                          progress[lessonId]?.video || 0,
                          progress[lessonId]?.audio || 0,
                        );

                        // Allow unrestricted seeking only if overall progress >= 80%
                        if (overallProgress >= 80) {
                          saveBackwardSeekProgress(
                            lessonId,
                            "audio",
                            currentTime,
                            duration,
                          );
                          return;
                        }

                        // Prevent seeking forward beyond listened content if progress < 80%
                        if (currentTime > maxAllowed + 1) {
                          audioSeekLockRef.current = true;
                          audioRef.current.currentTime = maxAllowed;
                          // Release the lock after browser processes the seek
                          setTimeout(() => {
                            audioSeekLockRef.current = false;
                          }, 100);
                          toast({
                            title: "Forward Seeking Disabled",
                            description:
                              "Please listen to the audio to unlock more content.",
                            variant: "default",
                          });
                          return;
                        }

                        saveBackwardSeekProgress(
                          lessonId,
                          "audio",
                          currentTime,
                          audioRef.current.duration,
                        );
                      }}
                    />

                    {/* AUDIO PROGRESS */}
                    <div className="mt-3">
                      <div className="flex justify-between text-sm text-gray-700">
                        <span>
                          {formatAudioTime(audioRef.current?.currentTime || 0)}
                        </span>
                        <span>
                          {formatAudioTime(audioRef.current?.duration || 0)}
                        </span>
                      </div>

                      <div className="w-full bg-gray-200 h-2 rounded-full mt-1">
                        <div
                          className="bg-[#FAA631] h-2 rounded-full transition-all"
                          style={{
                            width: `${getAudioProgress()}%`,
                          }}
                        />
                      </div>
                    </div>
                  </div>
                )}
                {mode === "quiz" && activeTopic?.details?.quiz && (
                  <div className="bg-black rounded-b-lg overflow-hidden flex items-center justify-center h-[480px]">
                    <img
                      // src={
                      //   activeTopic.details.quiz.thumbnail_url ??
                      //   "/images/course.png"
                      // }
                      src={"/images/course.png"}
                      alt={text.quizThumbnailAlt}
                      className="w-full h-full object-fill"
                    />
                  </div>
                )}
              </div>

              {/* OVERALL PROGRESS */}
              {mode !== "quiz" && (
                <div className="mt-4 flex items-center gap-4">
                  <div className="flex-1">
                    <div className="w-full bg-gray-200 h-3 rounded-full">
                      <div
                        className="h-3 rounded-full bg-[#FAA631] transition-all"
                        style={{
                          width: `${getLessonProgress(lessonId)}%`,
                        }}
                      />
                    </div>
                    <div className="text-sm text-gray-600 mt-1">
                      {getLessonProgress(lessonId)}% {text.watchedSuffix}
                    </div>
                  </div>

                  {/* SWITCH MODE */}
                  {audioLesson && (
                    <div className="flex justify-center gap-3 py-5 mt-[-20px]">
                      {mode === "video" && (
                        <button
                          onClick={() => {
                            syncMediaTimeOnModeChange("video", "audio");
                            setMode("audio");
                          }}
                          className="rounded-full border-2 flex items-center gap-2 text-sm transition border-[#FAA631] text-[#FAA631] hover:bg-[#FFF4E4]"
                        >
                          <div className="px-6 py-2">{text.listenInAudio}</div>
                          <Image
                            src="/images/audioIcon.svg"
                            alt="msg"
                            width={40}
                            height={40}
                          />
                        </button>
                      )}

                      {mode === "audio" && (
                        <button
                          onClick={() => {
                            syncMediaTimeOnModeChange("audio", "video");
                            setMode("video");
                          }}
                          className="rounded-full border-2 flex items-center gap-2 text-sm transition border-[#FAA631] text-[#FAA631] hover:bg-[#FFF4E4]"
                        >
                          <div className="px-6 py-2">{text.watchInVideo}</div>
                          <Image
                            src="/images/videoIcon.svg"
                            alt="msg"
                            width={40}
                            height={40}
                          />
                        </button>
                      )}
                    </div>
                  )}
                </div>
              )}

              {/* QUIZ CARD */}
              <div className="mt-6">
                <Card className="p-6">
                  <CardHeader className="p-0 mb-4">
                    <CardTitle className="text-xl">
                      {text.lessonContent}
                    </CardTitle>
                  </CardHeader>

                  <CardContent className="p-0">
                    <p className="text-gray-700">
                      {mode === "audio" &&
                        (courseLanguage === "hindi"
                          ? decodeHtml(audioLesson?.description_2)
                          : audioLesson?.description)}

                      {mode === "video" &&
                        (courseLanguage === "hindi"
                          ? decodeHtml(videoLesson?.description_2)
                          : videoLesson?.description)}

                      {mode === "quiz" &&
                        (courseLanguage === "hindi"
                          ? decodeHtml(quiz?.description_hindi)
                          : quiz?.description)}
                    </p>

                    <div className="mt-6 border-t pt-6">
                      <h3 className="font-semibold mb-3">{text.quiz}</h3>
                      {mode !== "quiz" && (
                        <>
                          {isQuizUnlocked ? (
                            <div>
                              {quiz?.state == "1" ? (
                                <div className="text-sm text-green-600 mb-3">
                                  {text.alreadySubmitted}
                                </div>
                              ) : (
                                <Button
                                  onClick={() => {
                                    requestQuizStart(quiz!.test_id, courseId);
                                  }}
                                  className="bg-[#FAA631]"
                                >
                                  {text.startQuiz}
                                </Button>
                              )}
                            </div>
                          ) : (
                            <div className="text-sm text-gray-600">
                              {text.unlockQuizMessage}
                            </div>
                          )}
                        </>
                      )}
                      {mode === "quiz" &&
                        quiz &&
                        (() => {
                          const status = getTestTimingStatus({
                            details: { quiz },
                          });

                          const start = Number(quiz.start_date);
                          const end = Number(quiz.end_date);

                          const now = Date.now();
                          const diffToStart = start - now;

                          const isWithin24Hrs =
                            diffToStart <= 24 * 60 * 60 * 1000;

                          const formatDate = (ts: number) => {
                            return new Date(ts).toLocaleString("en-IN", {
                              day: "numeric",
                              month: "short",
                              hour: "2-digit",
                              minute: "2-digit",
                            });
                          };

                          return (
                            <div className="mt-4 rounded-xl p-4 shadow-md border bg-gradient-to-r from-white to-orange-50">
                              {/* 🟡 NOT STARTED */}
                              {status === "NOT_STARTED" && (
                                <div className="flex items-center justify-between">
                                  <div>
                                    <p className="text-xs text-gray-500 mb-1">
                                      {text.upcomingTest}
                                    </p>

                                    <p className="text-lg font-semibold text-yellow-600">
                                      {isWithin24Hrs
                                        ? renderText(text.startsIn, {
                                            time: getTimeLeft(start),
                                          })
                                        : renderText(text.startsOn, {
                                            date: formatDate(start),
                                          })}
                                    </p>
                                  </div>

                                  {/* <div className="bg-yellow-100 text-yellow-700 px-3 py-1 rounded-full text-xs font-medium">
                                    NOT STARTED
                                  </div> */}
                                </div>
                              )}

                              {/* 🟢 ACTIVE */}
                              {status === "ACTIVE" && (
                                <div className="flex items-center justify-between">
                                  <div>
                                    <p className="text-xs text-gray-500 mb-1">
                                      {text.liveTest}
                                    </p>

                                    <p className="text-lg font-semibold text-green-600">
                                      {renderText(text.endsOn, {
                                        date: formatDateTime(end),
                                      })}
                                    </p>
                                  </div>
                                  {shouldShowStartButton && (
                                    <Button
                                      onClick={() => {
                                        requestQuizStart(
                                          quiz.test_id,
                                          courseId,
                                        );
                                      }}
                                      className="bg-[#FAA631] hover:scale-105 transition-all"
                                    >
                                      {text.startQuiz}
                                    </Button>
                                  )}
                                </div>
                              )}

                              {/* 🟢 ATTEMPTED / RESULT AVAILABLE */}
                              {(status === "ATTEMPTED_ACTIVE" ||
                                status === "RESULT_EXPIRED") && (
                                <div className="flex items-center justify-between">
                                  <div>
                                    <p className="text-xs text-gray-500 mb-1">
                                      {text.attempted}
                                    </p>

                                    {getResultInfo(quiz).available ? (
                                      <p className="text-lg font-semibold text-green-600">
                                        {renderText(text.endsOn, {
                                          date: formatDateTime(end),
                                        })}
                                      </p>
                                    ) : (
                                      <p className="text-sm font-semibold text-gray-500">
                                        {renderText(text.resultPending, {
                                          date: formatDateTime(
                                            Number(quiz.result_date),
                                          ),
                                        })}
                                      </p>
                                    )}
                                  </div>

                                  {getResultInfo(quiz).available && (
                                    <Button
                                      onClick={() =>
                                        router.push(`/result/${quiz.test_id}`)
                                      }
                                      className="bg-[#FAA631]"
                                    >
                                      {text.viewResult}
                                    </Button>
                                  )}
                                </div>
                              )}

                              {/* 🔴 EXPIRED */}
                              {status === "EXPIRED" && (
                                <div className="flex items-center justify-between">
                                  <div>
                                    <p className="text-lg font-semibold text-red-500">
                                      {text.testExpired}
                                    </p>

                                    <p className="text-xs text-gray-500">
                                      {renderText(text.endedOn, {
                                        date: formatDate(end),
                                      })}
                                    </p>
                                  </div>

                                  <span className="text-xs bg-red-100 text-red-600 px-3 py-1 rounded-full">
                                    {text.closed}
                                  </span>
                                </div>
                              )}
                            </div>
                          );
                        })()}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>

            {/* Right column: mentor card + lessons list */}
            <div className="p-6 bg-[#FFF8F0] min-h-screen overflow-y-auto">
              {/* Top Tabs */}
              <div className="flex justify-center gap-4 mb-6">
                {/* Lessons Button */}
                <button
                  onClick={() => setActiveTab("lessons")}
                  className={`px-6 py-2 font-semibold rounded-full shadow w-full transition-all
          ${
            activeTab === "lessons"
              ? "bg-[#FFB84D] text-white"
              : "bg-white text-gray-500 border border-[#FFDDA0]"
          }
        `}
                >
                  {text.lessons}
                </button>

                {/* More Button */}
                <button
                  onClick={() => setActiveTab("more")}
                  className={`px-6 py-2 font-semibold rounded-full shadow w-full transition-all
          ${
            activeTab === "more"
              ? "bg-[#FFB84D] text-white"
              : "bg-white text-gray-500 border border-[#FFDDA0]"
          }
        `}
                >
                  {text.more}
                </button>
              </div>
              {activeTab === "lessons" ? (
                <>
                  {/* HEADING — dynamic */}
                  {/* <h2 className="text-xl font-bold text-gray-900 mb-4">
                    {videoLesson?.title}
                  </h2> */}

                  {/* LESSON LIST */}
                  <div className="max-h-[500px] overflow-y-scroll w-full p-2 scrollbar">
                    {lessonTopics
                      // .slice(0, showAll ? lessonTopics.length : VISIBLE_COUNT)
                      .map((topic, index) => {
                        const quiz = topic.details.quiz;
                        const video = topic.details.video;
                        const audio = topic.details.audio;
                        const lessonMedia = video?.id ? video : audio;
                        const lessonId = lessonMedia?.id;
                        const lessonProgress = getTopicProgress(topic);

                        // sequence rule (based on previous quiz unlock)
                        const unlockedBySequence = isLessonUnlocked(index);

                        // ✅ Force unlock first lesson no matter what backend says
                        const forceUnlockFirst = index === 0;

                        // ✅ FINAL LOCK
                        const isLessonLocked =
                          !forceUnlockFirst && !unlockedBySequence;

                        const isActive = index === activeTopicIndex;

                        return (
                          <div
                            key={lessonId || index}
                            onClick={() => {
                              if (isLessonLocked) return;
                              setActiveTopicIndex(index);
                              setMode(getPreferredModeForTopic(topic));
                              setActiveQuizType("lesson");
                            }}
                            className={`bg-white rounded-2xl p-4 shadow-sm mb-5 transition-all duration-300
          ${
            isLessonLocked
              ? "opacity-50 cursor-not-allowed"
              : "cursor-pointer hover:shadow-xl"
          }
          ${isActive ? "ring-2 ring-[#FAA631]" : ""}
        `}
                          >
                            <div className="flex items-start gap-4">
                              {/* Thumbnail */}
                             <div className="w-24 h-20 rounded-lg overflow-hidden relative flex-shrink-0">
                                <Image
                                  src={
                                    lessonMedia?.thumbnail_url ||
                                    "/images/course.png"
                                  }
                                  alt={
                                    lessonMedia?.title || text.defaultTopicTitle
                                  }
                                  width={1200}
                                  height={675}
                                  className="w-full h-full object-cover"
                                />

                                {/* Play / Lock overlay */}
                                <div className="absolute inset-0 flex items-center justify-center">
                                  <div className="bg-white/70 w-10 h-10 rounded-full flex items-center justify-center">
                                    {isLessonLocked ? (
                                      <SolidLock className="w-5 h-5" />
                                    ) : (
                                      <svg
                                        viewBox="0 0 20 20"
                                        fill="#FF8A00"
                                        className="w-5 h-5"
                                      >
                                        <path d="M6 4l12 6-12 6V4z"></path>
                                      </svg>
                                    )}
                                  </div>
                                </div>
                              </div>

                              {/* Lesson Text */}
                             <div className="flex-1 min-w-0 overflow-hidden">
                              <p className="text-lg font-semibold leading-6 line-clamp-2 break-words overflow-hidden">
                                  {courseLanguage === "hindi"
                                    ? decodeHtml(lessonMedia?.title_2)
                                    : lessonMedia?.title}
                                </p>

                                <p className="text-sm text-gray-500 mt-1">
                                  {isLessonLocked
                                    ? renderText(text.lockedWithWatched, {
                                        progress: Math.floor(lessonProgress),
                                      })
                                    : text.unlocked}
                                </p>
                              </div>
                            </div>

                            {/* Quiz Row */}
                            {quiz && (
                             <div className="mt-4 flex items-start justify-between gap-3 p-3 rounded-xl border bg-[#FFF8F0]">
                               <div className="flex items-start gap-2 flex-1 min-w-0">
                                  <Image
                                    src="/images/bulb-lighting.svg"
                                    alt="Bulb Icon"
                                    width={20}
                                    height={20}
                                    className="w-5 h-5"
                                  />
                             <span className="font-medium text-gray-800 break-words line-clamp-2">
                                    {courseLanguage === "hindi"
                                      ? decodeHtml(quiz.test_series_name_hindi)
                                      : quiz.test_series_name}
                                  </span>
                                </div>

                                {(() => {
                                  const action = getQuizActionLabel(
                                    quiz,
                                    topic,
                                    lessonProgress,
                                  );
                                  switch (action) {
                                    case "VIEW_RESULT":
                                      return (
                                        <span
                                          onClick={async (e) => {
                                            e.stopPropagation();
                                            router.push(
                                              `/result/${quiz.test_id}`,
                                            );
                                          }}
                                          className="text-[#FF8A00] font-medium cursor-pointer"
                                        >
                                          {text.viewResult}
                                        </span>
                                      );

                                    // case "UPCOMING_RESULT":
                                    //   return (
                                    //     <span className="text-gray-500 font-medium">
                                    //       Upcoming Result
                                    //     </span>
                                    //   );

                                    case "UPCOMING_TEST":
                                      return (
                                        <span className="text-gray-500 font-medium">
                                          {text.upcomingTest}
                                        </span>
                                      );

                                    case "EXPIRED_TEST":
                                      return (
                                        <span className="text-red-500 font-medium">
                                          {text.expiredTest}
                                        </span>
                                      );

                                    case "START_TEST":
                                      return isQuizUnlock(
                                        topic,
                                        lessonProgress,
                                      ) ? (
                                        <span
                                          className="font-bold text-[#FAA631] cursor-pointer"
                                          onClick={(e) => {
                                            e.stopPropagation();
                                            setActiveTopicIndex(index);
                                            setActiveQuizType("lesson");
                                            setMode("quiz");
                                            requestQuizStart(
                                              topic.details.quiz.test_id,
                                              courseId,
                                            );
                                          }}
                                        >
                                          {text.startTest}
                                        </span>
                                      ) : (
                                        <SolidLock className="w-5 h-5" />
                                      );

                                    default:
                                      return null;
                                  }
                                })()}
                              </div>
                            )}
                          </div>
                        );
                      })}
                  </div>
                  {/* PRE CERTIFICATION QUIZ CARD — UNCHANGED */}
                  {/* <div className="mt-6 bg-white rounded-2xl p-4 py-6 shadow-sm flex items-center justify-between hover:shadow-xl transition-all duration-300">
                    <div className="flex items-center gap-3">
                      <Image
                        src="/images/bulb-lighting.svg"
                        alt="Bulb Icon"
                        width={24}
                        height={24}
                        className="w-6 h-6"
                      />
                      <span className="font-semibold text-gray-900">
                        Pre Certification Quiz
                      </span>
                    </div>

                    <span className="text-[#FF8A00] font-medium cursor-pointer">
                      View Result
                    </span>
                  </div> */}

                  {/* {lessonTopics.length > VISIBLE_COUNT && !showAll && (
                    <div className="flex justify-center mt-8">
                      <button
                        onClick={() => setShowAll(true)}
                        className="px-6 py-2 border border-[#FFB84D] text-[#FF8A00] rounded-full font-medium bg-white shadow-sm hover:bg-[#FFF4E4] transition"
                      >
                        View All &gt;
                      </button>
                    </div>
                  )} */}
                  {/* MOCK + PRE-CERTIFICATION TEST GRID */}
                  <div className="grid grid-cols-2 gap-4 mt-6">
                    {mockTest.map((test, index) => {
                      const status = getTestTimingStatus(test);
                      const canStart = isMockUnlocked() && status === "ACTIVE";
                      return (
                        <div
                          key={test.topic_id}
                          onClick={() => {
                            setActiveQuizType("mock");
                            setActiveTopicIndex(index);
                            setMode("quiz");
                            setActiveCard("mock");
                          }}
                          className={`relative rounded-2xl p-5 cursor-pointer border-2 transition-all flex flex-col items-center justify-center text-center
  ${activeCard === "mock" ? "border-[#FAA631] bg-[#FFEFD8]" : "border-[#FAA631]/30 bg-[#FFEFD8]"}`}
                        >
                          {/* Lock icon top-right if not startable */}
                          {!canStart && (
                            <div className="absolute top-3 right-3">
                              <SolidLock className="w-5 h-5" />
                            </div>
                          )}

                          {/* Document icon */}
                          <div className="w-14 h-14 rounded-full border-2 border-gray-200 bg-white flex items-center justify-center mb-3">
                            <Image
                              src="/images/bulb-lighting.svg"
                              alt="Test"
                              width={28}
                              height={28}
                            />
                          </div>

                          {/* Test name */}
                          <span className="font-semibold text-sm text-gray-800">
                            {courseLanguage === "hindi"
                              ? decodeHtml(
                                  test.details.quiz.test_series_name_hindi,
                                )
                              : test.details.quiz.test_series_name}
                          </span>

                          {/* Status actions */}
                          <div className="mt-2">
                            {canStart && (
                              <span
                                className="text-xs font-bold text-[#FAA631] bg-[#FAA631]/10 px-3 py-1 rounded-full"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setActiveQuizType("mock");
                                  setActiveTopicIndex(index);
                                  setMode("quiz");
                                  setActiveCard("mock");
                                  requestQuizStart(
                                    test.details.quiz.test_id,
                                    courseId,
                                  );
                                }}
                              >
                                {text.startTest}
                              </span>
                            )}
                            {(status === "ATTEMPTED_ACTIVE" ||
                              status === "RESULT_EXPIRED") &&
                              !canStart &&
                              (getResultInfo(test.details.quiz).available ? (
                                <span
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    router.push(
                                      `/result/${test.details.quiz.test_id}`,
                                    );
                                  }}
                                  className="text-xs font-bold text-[#FAA631] bg-[#FAA631]/10 px-3 py-1 rounded-full"
                                >
                                  {text.viewResult}
                                </span>
                              ) : (
                                <span className="text-xs font-semibold text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                  {renderText(text.resultPending, {
                                    date: formatDateTime(
                                      Number(test.details.quiz.result_date),
                                    ),
                                  })}
                                </span>
                              ))}
                            {status === "EXPIRED" && !canStart && (
                              <span className="text-xs text-gray-500">
                                {text.expired}
                              </span>
                            )}
                          </div>
                        </div>
                      );
                    })}

                    {preCertificationTest.map((test, index) => {
                      const status = getTestTimingStatus(test);
                      const canStart =
                        isPreCertificationUnlocked && status === "ACTIVE";

                      return (
                        <div
                          key={test.topic_id}
                          onClick={() => {
                            setActiveQuizType("pre");
                            setActiveTopicIndex(index);
                            setMode("quiz");
                            setActiveCard("pre");
                          }}
                          className={`relative rounded-2xl p-5 cursor-pointer border-2 transition-all flex flex-col items-center justify-center text-center
  ${activeCard === "pre" ? "border-[#FAA631] bg-[#FFEFD8]" : "border-[#FAA631]/30 bg-[#FFEFD8]"}`}
                        >
                          {/* Lock icon top-right if not startable */}
                          {!canStart && (
                            <div className="absolute top-3 right-3">
                              <SolidLock className="w-5 h-5" />
                            </div>
                          )}

                          {/* Document icon */}
                          <div className="w-14 h-14 rounded-full border-2 border-gray-200 bg-white flex items-center justify-center mb-3">
                            <Image
                              src="/images/bulb-lighting.svg"
                              alt="Test"
                              width={28}
                              height={28}
                            />
                          </div>

                          {/* Test name */}
                          <span className="font-semibold text-sm text-gray-800">
                            {courseLanguage === "hindi"
                              ? decodeHtml(
                                  test.details.quiz.test_series_name_hindi,
                                )
                              : test.details.quiz.test_series_name}
                          </span>

                          {/* Status actions */}
                          <div className="mt-2">
                            {canStart && (
                              <span
                                className="text-xs font-bold text-[#FAA631] bg-[#FAA631]/10 px-3 py-1 rounded-full"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setActiveQuizType("pre");
                                  setActiveTopicIndex(index);
                                  setMode("quiz");
                                  setActiveCard("pre");
                                  requestQuizStart(
                                    test.details.quiz.test_id,
                                    courseId,
                                  );
                                }}
                              >
                                {text.startTest}
                              </span>
                            )}
                            {(status === "ATTEMPTED_ACTIVE" ||
                              status === "RESULT_EXPIRED") &&
                              !canStart &&
                              (getResultInfo(test.details.quiz).available ? (
                                <span
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    router.push(
                                      `/result/${test.details.quiz.test_id}`,
                                    );
                                  }}
                                  className="text-xs font-bold text-[#FAA631] bg-[#FAA631]/10 px-3 py-1 rounded-full"
                                >
                                  {text.viewResult}
                                </span>
                              ) : (
                                <span className="text-xs font-semibold text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                  {renderText(text.resultPending, {
                                    date: formatDateTime(
                                      Number(test.details.quiz.result_date),
                                    ),
                                  })}
                                </span>
                              ))}
                            {status === "EXPIRED" && !canStart && (
                              <span className="text-xs text-gray-500">
                                {text.expired}
                              </span>
                            )}
                            {(status === "NOT_STARTED" ||
                              !isPreCertificationUnlocked) &&
                              !canStart && (
                                <span className="text-xs text-gray-400"></span>
                              )}
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  {/* FINAL EXAM / OLYMPIAD EXAM CARD */}
                  <div
                    className={`rounded-3xl mt-6 cursor-pointer border-2 transition-all
    ${activeCard === "final" ? "border-[#FAA631] bg-[#FFEFD8]" : "border-[#FAA631]/30 bg-[#FFEFD8]"}`}
                    onClick={() => {
                      setMode("quiz");
                      setActiveQuizType("final");
                      setActiveCard("final");
                    }}
                  >
                    <div className="flex flex-col items-center py-8 px-4">
                      <h3 className="text-xl font-bold text-gray-900 mb-5">
                        {courseLanguage === "hindi"
                          ? decodeHtml(
                              finalExam?.[0]?.details.quiz
                                .test_series_name_hindi,
                            )
                          : decodeHtml(
                              finalExam?.[0]?.details.quiz.test_series_name,
                            )}
                      </h3>

                      {/* Countdown Timer */}
                      <div className="flex items-center gap-2 mb-5">
                        {[
                          { value: finalCountdown.days, label: "DD" },
                          { value: finalCountdown.hours, label: "HH" },
                          { value: finalCountdown.minutes, label: "MM" },
                          { value: finalCountdown.seconds, label: "SS" },
                        ].map((item, i) => (
                          <div
                            key={item.label}
                            className="flex items-center gap-2"
                          >
                            <div className="flex flex-col items-center">
                              <div className="bg-white text-black font-bold text-xl w-12 h-12 rounded-lg flex items-center justify-center">
                                {String(item.value).padStart(2, "0")}
                              </div>
                              <span className="text-[11px] text-gray-500 mt-1 font-medium">
                                {item.label}
                              </span>
                            </div>
                            {i < 3 && (
                              <span className="text-gray-900 font-bold text-xl -mt-4">
                                :
                              </span>
                            )}
                          </div>
                        ))}
                      </div>

                      {/* Status Button */}
                      {finalExam?.[0]?.details.quiz.state === "1" ? (
                        getResultInfo(finalExam?.[0]?.details?.quiz).available ? (
                          <span
                            onClick={(e) => {
                              e.stopPropagation();
                              router.push(
                                `/result/${finalExam?.[0]?.details.quiz.test_id}`,
                              );
                            }}
                            className="bg-[#FAA631] text-white text-sm font-semibold px-6 py-2.5 rounded-full"
                          >
                            {text.viewResult}
                          </span>
                        ) : (
                          <span className="bg-gray-200 text-gray-600 text-sm font-semibold px-6 py-2.5 rounded-full">
                            {renderText(text.resultPending, {
                              date: formatDateTime(
                                Number(finalExam[0].details.quiz.result_date),
                              ),
                            })}
                          </span>
                        )
                      ) : (
                        canStartFinal && (
                          <span
                            className="bg-[#FAA631] text-white text-sm font-semibold px-6 py-2.5 rounded-full"
                            onClick={(e) => {
                              e.stopPropagation();
                              setActiveQuizType("final");
                              setMode("quiz");
                              setActiveCard("final");
                              requestQuizStart(
                                finalExam?.[0]?.details.quiz.test_id,
                                courseId,
                              );
                            }}
                          >
                            {text.startTest}
                          </span>
                        )
                      )}
                    </div>
                  </div>

                  {/* ))} */}
                </>
              ) : (
                <>
                  {/* ABOUT / GUIDELINES / LANGUAGE CARD */}
                  <div className="mt-6 bg-white rounded-3xl p-4 shadow-sm border">
                    {/* ABOUT COURSE */}
                    <div
                      onClick={() => router.push("/course/online")}
                      className="flex items-center justify-between p-4 border rounded-2xl mb-3 cursor-pointer"
                    >
                      <div className="flex items-center gap-3">
                        <svg
                          width="22"
                          height="22"
                          fill="none"
                          stroke="black"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <circle cx="4" cy="10" r="1.5" />
                          <circle cx="11" cy="10" r="1.5" />
                          <circle cx="18" cy="10" r="1.5" />
                        </svg>
                        <span className="font-medium text-gray-800">
                          {text.aboutCourse}
                        </span>
                      </div>
                    </div>

                    {/* COURSE GUIDELINES */}
                    <div
                      onClick={() => {
                        setShowGuidelineContinue(false);
                        setIsOpen(true);
                      }}
                      className="flex items-center justify-between p-4 border rounded-2xl mb-3 cursor-pointer"
                    >
                      <div className="flex items-center gap-3">
                        <svg
                          width="22"
                          height="22"
                          viewBox="0 0 24 24"
                          stroke="black"
                          strokeWidth="1.8"
                          fill="none"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <path d="M3 6h6M3 12h9M3 18h6M14 6l2 2 4-4M14 12l2 2 4-4" />
                        </svg>
                        <span className="font-medium text-gray-800">
                          {text.courseGuidelines}
                        </span>
                      </div>
                    </div>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}

      <GuidelinesModal
        isOpen={isOpen}
        guidelineToggle={guidelineToggle}
        setGuidelineToggle={setGuidelineToggle}
        guidelineData={guidelineData}
        showContinue={showGuidelineContinue}
        onContinue={handleContinue}
      />

      <LanguageModal
        open={showLanguageModal}
        selectedLanguage={selectedLanguage}
        onSelect={handleLanguageChange}
        onClose={() => {
          setShowLanguageModal(false);
          setPendingQuizStart(null);
        }}
        onContinue={handleLanguageModalContinue}
      />

      <InstructionsModal
        show={showInstructions}
        instructionData={instructionData}
        onContinue={() => {
          scrollToTop();
          handleStartQuiz();
          setShowInstructions(false);
        }}
        onClose={() => setShowInstructions(false)}
      />

      {showFullscreenModal && (
        <div className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center">
          <div className="bg-white p-6 rounded-xl text-center max-w-sm w-full">
            <h2 className="text-lg font-semibold mb-2">Fullscreen Required</h2>

            <p className="text-gray-600 mb-4">
              First submit the exam, then you can exit fullscreen.
            </p>

            <button
              onClick={() => {
                setShowFullscreenModal(false);
                enterFullscreen();
              }}
              className="bg-orange-500 text-white px-5 py-2 rounded-lg"
            >
              Go Back to Exam
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
