import React, { useState, useEffect, useRef } from "react";
import "../style/index.css";
import "../style/guidedTest.css";
import OptionContainer from "../../chapter/OptionContainer";
import QuestionBodyTestSeries from "../../chapter/QuestionBodyTestSeries";
import ChapterStepper from "../../chapter/ChapterStepper";
import GuidedTestStepper from "../../chapter/GuidedTestStepper";
import { useLocation, useNavigate } from "react-router-dom";
import submitTest from "../api/submitTest";
import ComprehensionBox from "../ComprehensionBox";
import BackDrop from "../../ui/backdrop/BackDrop";
import { LanguagesSlugs } from "../LanguageData";
import "../style/testHeader.css";
import ChatVoiceComponent from "../../chapterPractice/ChatVoiceComponent";
import { processSubject } from "./processSubject";
import Preloader from "../../ui/loading/Preloader";
import oneshotUpdateAndGetRecord from "../api/oneshotupdateAndGetall";
import OpttionContainerOneshot from "../../chapter/OptionContainerOneShot";
import TextToSpeech from "../ellevenlabsVoice/VoiceLabs";
// import getAllChapters from './api/getAllChapters';
// import BackDrop from '../ui/backdrop/BackDrop';
const throttle = (func, limit) => {
  let lastFunc;
  let lastRan;
  return function () {
    const context = this;
    const args = arguments;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function () {
        if (Date.now() - lastRan >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
};

const AnimatedScore = ({ value }) => {
  const [prevValue, setPrevValue] = useState(value);
  const [isAnimating, setIsAnimating] = useState(false);

  useEffect(() => {
    console.log("AnimatedScore received new value:", value);
    if (value !== prevValue) {
      console.log("AnimatedScore animating from", prevValue, "to", value);
      setIsAnimating(true);
      const timer = setTimeout(() => {
        setPrevValue(value);
        setIsAnimating(false);
      }, 500);
      return () => clearTimeout(timer);
    }
  }, [value]);

  const formattedScore = (num) => (num * 100).toFixed(2);
  const currentScore = formattedScore(value);
  const previousScore = formattedScore(prevValue);

  return (
    <div style={{ display: "block", margin: 0 }}>
      Score →&nbsp;
      <span
        style={{
          position: "relative",
          display: "inline-block",
          minWidth: "4em",
          height: "1.2em",
          overflow: "hidden",
        }}
      >
        <span
          style={{
            position: "absolute",
            left: 0,
            transform: isAnimating ? "translateY(-100%)" : "translateY(0)",
            opacity: isAnimating ? 0 : 1,
            transition: "all 500ms ease-out",
          }}
        >
          {isAnimating ? previousScore : currentScore}%
        </span>
        <span
          style={{
            position: "absolute",
            left: 0,
            transform: isAnimating ? "translateY(0)" : "translateY(100%)",
            opacity: isAnimating ? 1 : 0,
            transition: "all 500ms ease-out",
          }}
        >
          {currentScore}%
        </span>
        <span style={{ visibility: "hidden" }}>{currentScore}%</span>
      </span>
    </div>
  );
};

// Add Hindi translations for encouragement messages
const encouragementMessages = {
  wrongAnswer: {
    English: [
      "Don't worry! Every mistake is a step towards learning.",
      "Keep going! Mistakes are part of the learning journey.",
      "It's okay to make mistakes! That's how we learn.",
    ],
    Hindi: [
      "चिंता न करें! हर गलती सीखने की दिशा में एक कदम है।",
      "जारी रखें! गलतियाँ सीखने की यात्रा का हिस्सा हैं।",
      "गलतियाँ करना ठीक है! इसी तरह हम सीखते हैं।",
    ],
  },
  milestone: {
    English: {
      5: "You've completed 5 questions! Keep going!",
      10: "Great! 10 questions done!",
      20: "Awesome! 20 questions completed!",
      40: "🔥 40 questions! You're unstoppable!",
      50: "Half century! Keep pushing!",
      70: "70 questions solved! Amazing!",
      90: "90 done! Almost there!",
      100: "🎯 100 questions! Excellent effort!",
    },
    Hindi: {
      5: "आपने 5 प्रश्न पूरे कर लिए हैं! जारी रखें!",
      10: "शानदार! 10 प्रश्न पूरे!",
      20: "कमाल है! 20 प्रश्न पूरे!",
      40: "🔥 40 प्रश्न! आप अद्भुत हैं!",
      50: "अर्धशतक पूरा! ऐसे ही चलते रहें!",
      70: "70 प्रश्न हल हो चुके हैं! शानदार!",
      90: "90 हो गए! अब थोड़ा ही बचा है!",
      100: "🎯 100 प्रश्न! अद्भुत प्रयास!",
    },
  },
  score: {
    English: {
      10: "🎉 Great! Your score crossed 10%.",
      20: "👏 Well done! 20% achieved.",
      40: "🔥 40% score reached!",
      60: "Awesome! You hit 60%.",
      80: "💯 80%! You're crushing it!",
    },
    Hindi: {
      10: "🎉 बढ़िया! आपका स्कोर 10% पार कर गया है।",
      20: "👏 शाबाश! 20% प्राप्त हुआ।",
      40: "🔥 40% स्कोर पूरा किया!",
      60: "शानदार! आपने 60% हासिल किया।",
      80: "💯 80%! आप धूम मचा रहे हैं!",
    },
  },
  completion: {
    English: "🎉 Congratulations on completing this test!",
    Hindi: "🎉 इस परीक्षा को पूरा करने पर बधाई हो!",
  },
};


// Update EncouragementMessage component
const EncouragementMessage = ({ message, type, language }) => {
  const [isVisible, setIsVisible] = useState(true);

  useEffect(() => {
    setIsVisible(true);
    const timer = setTimeout(() => {
      setIsVisible(false);
    }, 5000); // Increased display time to 5 seconds for longer messages
    return () => clearTimeout(timer);
  }, [message, type]);

  if (!isVisible) return null;

  // Get the appropriate heading based on message type
  const getHeading = () => {
    switch (type) {
      case 'wrongAnswer':
        return '💪 Keep Going!';
      case 'achievement':
        return '🏆 Achievement Unlocked!';
      default:
        return '🌟 Great Job!';
    }
  };

  return (
    <div
      className="encouragement-message"
      style={{
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: 'var(--bg-primary-clr)',
        padding: '20px 40px',
        borderRadius: '10px',
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
        zIndex: 1000,
        textAlign: 'center',
        border: '2px solid var(--accent-primary-clr)',
        animation: 'fadeInOut 5s ease-in-out forwards', // Increased animation time
        maxWidth: '80%', // Added max width
        width: 'auto', // Allow width to adjust to content
        minWidth: '300px', // Minimum width
      }}
    >
      <h3 style={{ margin: '0 0 10px 0', color: 'var(--accent-primary-clr)' }}>
        {getHeading()}
      </h3>
      <p style={{ 
        margin: 0, 
        fontSize: '16px', 
        color: 'var(--text-primary-clr)',
        whiteSpace: 'pre-wrap', // Allow text to wrap
        wordBreak: 'break-word', // Break long words if needed
        lineHeight: '1.5' // Improve readability
      }}>
        {message}
      </p>
      <button 
  onClick={() => setIsVisible(false)} 
  style={{ 
    marginTop: '12px', 
    padding: '6px 16px', 
    backgroundColor: 'var(--accent-primary-clr)', 
    color: 'white', 
    border: 'none', 
    borderRadius: '6px', 
    cursor: 'pointer', 
    fontSize: '14px' 
  }}
>
  {language?.id === 'hi' ? 'बंद करें' : 'Close'}
</button>
    </div>
  );
};

// Update showEncouragement function


function PracticePage() {
  const location = useLocation();
  const navigate = useNavigate();
  // const [testCategory, setTestCategory] = useState("")
  // const [allChapter, setAllChapter] = useState([])
  // const [ChapterDropdown, setChapterDropdown] = useState(false)
  // const [chapterSelected, setChapterSelected] = useState({})
  // const [subTopicSelected, setsubTopicSelected] = useState("All")
  // const [examTypeMode, setExamTypeMode] = useState("Both MCQs and Integer Type")
  // const [examTypeDropDown, setExamTypeDropDown] = useState(false)
  // const [subTopicSelectecdDropDown, setSubTopicSelectecdDropDown] = useState(false)
  const [language, setLanguagesSlugs] = useState(
    localStorage.getItem("language")
      ? LanguagesSlugs.filter(
          (obj) => obj.id === localStorage.getItem("language")
        )[0]
      : LanguagesSlugs[0]
  );
  const [openLanguage, setOpenLanguage] = useState(false);
  const { skipInitialLoader } = location.state || {};
  const [loading, setLoading] = useState(!skipInitialLoader);

  // console.log(location?.state)
  let ChapterID = location?.state?.ChapterID;
  let UserID = location?.state?.UserID;
  // let TestID = location?.state?.TestID;
  let ChapterName = location?.state?.ChapterName?.replaceAll(",", ", ");
  let TestTitle = location?.state?.TestTitle;
  let questionMain = location?.state?.Questions;
  let scores = location?.state?.score;
  // Store the original question data with all language variants
  const [originalQuestions, setOriginalQuestions] = useState(questionMain);
  const [question, setQuestionMain] = useState(questionMain);
  const [currentQuestion, setCurrentQuestion] = useState(question?.length);
  // const [currentQuestion, setCurrentQuestion] = useState(1);
  const [totalPages, setTotalPages] = useState(question?.length);
  const [score, setScore] = useState(scores);
  // console.log(question)
  const [questionSubmitted, setQuestionSubmitted] = useState(false);
  const [speakerVoiceActivatedOnce, setSpeakerVoiceActivatedOnce] =
    useState(false);
  const [encouragementMessage, setEncouragementMessage] = useState("");
  const [encouragementType, setEncouragementType] = useState("");
  const [milestonesShown, setMilestonesShown] = useState({
    questions: [],
    scores: [],
    concepts: [],
  });

  const [currentTestTitle, setCurrentTestTitle] = useState(TestTitle);

  // New useEffect to update currentTestTitle state when TestTitle changes
  useEffect(() => {
    if (TestTitle) {
      setCurrentTestTitle(TestTitle);
    }
  }, [TestTitle]);

  // New useEffect to show message when currentTestTitle changes
  useEffect(() => {
    if (currentTestTitle) {
      showEncouragement(`🎉 Congratulations on completing ${currentTestTitle}!`);
    }
  }, [currentTestTitle]);
// Encouragement Message Function
const showEncouragement = (message, type = 'encouragement', langState) => {
  // If no message or type is provided, don't show anything
  if (!message || !type) {
    setEncouragementMessage("");
    setEncouragementType("");
    return;
  }

  const lang = langState?.id === 'hi' ? 'Hindi' : 'English';
  let translatedMessage;

  // Only handle specific message types
  switch (type) {
    case 'wrongAnswer':
      const messages = encouragementMessages[type][lang];
      translatedMessage = messages[Math.floor(Math.random() * messages.length)];
      break;
    case 'score':
      if (typeof message === "number") {
        translatedMessage = encouragementMessages.score?.[lang]?.[message] || `🌟 Your score just crossed ${message}%!`;
      }
      break;
    case 'milestone':
      if (typeof message === "number") {
        translatedMessage = encouragementMessages.milestone?.[lang]?.[message] || `🎉 You've completed ${message} questions!`;
      }
      break;
    case 'completion':
      translatedMessage = encouragementMessages.completion?.[lang] || message;
      break;
    default:
      // For any other type, don't show a message
      setEncouragementMessage("");
      setEncouragementType("");
      return;
  }

  // Only set the message if we have a translated message
  if (translatedMessage) {
    setEncouragementMessage(translatedMessage);
    setEncouragementType(type);
  } else {
    setEncouragementMessage("");
    setEncouragementType("");
  }
};


  const updateQuestionData = (data, langDefiner) => {
    // Create a copy of the data to avoid mutating the original object
    const updatedData = { ...data };

    // Iterate over the keys of the object
    Object.keys(data).forEach((key) => {
      const langSpecificKey = `${key}${langDefiner}`;
      // console.log(langDefiner)

      // Check if the language-specific key exists and is not null
      if (
        data[langSpecificKey] !== undefined &&
        data[langSpecificKey] !== null
      ) {
        updatedData[key] = data[langSpecificKey];
      }
    });

    return updatedData;
  };

  const questionstr = {
    optionChosen: "",
    optionBeforeSubmit: "",
  };
  // console.log(question)
  const [questionTestStatus, setQuestionTestStatus] = useState(() =>
    question.map((val) => {
      return {
        ...questionstr,
        QuestionID: val.QuestionID,
        QuestionType: val.QuestionType,
      };
    })
  );
  // console.log(language);

  // useEffect(() => {
  //   let selectedOption =
  //     question[currentQuestion - 1].OptionA ===
  //     question[currentQuestion - 1].optionBeforeSubmit
  //       ? "a"
  //       : question[currentQuestion - 1].OptionB ===
  //         question[currentQuestion - 1].optionBeforeSubmit
  //       ? "b"
  //       : question[currentQuestion - 1].OptionC ===
  //         question[currentQuestion - 1].optionBeforeSubmit
  //       ? "c"
  //       : question[currentQuestion - 1].OptionD ===
  //         question[currentQuestion - 1].optionBeforeSubmit
  //       ? "d"
  //       : question[currentQuestion - 1].OptionE ===
  //         question[currentQuestion - 1].optionBeforeSubmit
  //       ? "e"
  //       : question[currentQuestion - 1].OptionF ===
  //         question[currentQuestion - 1].optionBeforeSubmit
  //       ? "f"
  //       : ""; // Return null if no match is found

  //   console.log(selectedOption);

  //   oneshotUpdateAndGetRecord(
  //     UserID,
  //     ChapterID,
  //     question?.length != currentQuestion
  //       ? "&QuestionID=" + question[currentQuestion - 1]
  //       : ""
  //   )
  //     .then((res) => {
  //       let adata = res.data;
  //       let nextQuestion = res.data.nextQuestion;
  //       if (!nextQuestion && question?.length === currentQuestion) {
  //         alert("You reached a peak level now pleas wait for more questions");
  //       }
  //       let AllQueston = question;
  //       AllQueston[currentQuestion - 1] = nextQuestion[0];
  //       console.log(AllQueston[currentQuestion - 1]);
  //     })
  //     .catch((err) => console.log(err));
  //   // }, [currentQuestion]);
  // }, [question]);
  // console.log(questionTestStatus[currentQuestion - 1]?.optionChosen);
  console.log(UserID);

  // Add a ref for the TextToSpeech component
  const textToSpeechRef = useRef(null);
  // functio to show the Encouragement message

  // Function to check and show achievements
 const checkAchievements = (currentScore, questionsCompleted) => {
  const lang = language?.id === 'hi' ? 'Hindi' : 'English';

  // Score-based achievements
  if (currentScore >= 0.8 && !milestonesShown.scores.includes('high_score')) {
    const message = encouragementMessages.score[lang][80] || "🎉 High score!";
    showEncouragement(message, 'score', language);
    setMilestonesShown(prev => ({
      ...prev,
      scores: [...prev.scores, 'high_score']
    }));
  }

  // Question completion achievements
  const milestones = {
    5: encouragementMessages.milestone[lang][5],
    10: encouragementMessages.milestone[lang][10]
  };

  if (milestones[questionsCompleted] && !milestonesShown.questions.includes(`first_${questionsCompleted}`)) {
    showEncouragement(milestones[questionsCompleted], 'milestone', language);
    setMilestonesShown(prev => ({
      ...prev,
      questions: [...prev.questions, `first_${questionsCompleted}`]
    }));
  }

  // Concept completion achievement
  if (currentTestTitle && !milestonesShown.concepts.includes(currentTestTitle)) {
    const message = encouragementMessages.completion[lang] || `🎉 Completed ${currentTestTitle}`;
    showEncouragement(message, 'completion', language);
    setMilestonesShown(prev => ({
      ...prev,
      concepts: [...prev.concepts, currentTestTitle]
    }));
  }
};


  const handleClickNextButton = () => {
    // Pause any ongoing speech before proceeding
    if (speakerVoiceActivatedOnce && question?.length === currentQuestion - 1) {
      setSpeakerVoiceActivatedOnce(false);
    }
    if (textToSpeechRef.current) {
      textToSpeechRef.current.pauseSpeech();
    }

    console.log("=== API Call Debug ===");
    const currentQuestionData = question[currentQuestion - 1];
    const currentQuestionStatus = questionTestStatus[currentQuestion - 1];

    // Set submitted to true when user clicks next
    setQuestionSubmitted(true);

    // Check if the answer is wrong and show appropriate message
    

    console.log("Current Question Data:", {
      QuestionID: currentQuestionData?.QuestionID,
      CorrectOption: currentQuestionData?.CorrectOption,
      UserAnswer: currentQuestionStatus?.optionChosen,
    });

    // Ensure we have valid data before making the API call
    if (!currentQuestionData?.QuestionID) {
      console.error("Missing QuestionID");
      return;
    }

    // Get the user's answer and correct answer
    const userAnswer = currentQuestionStatus?.optionChosen || "";
    const correctAnswer = currentQuestionData?.CorrectOption || "";

    // Encode parameters properly
    const params = new URLSearchParams({
      QuestionID: currentQuestionData.QuestionID,
      user_answer: userAnswer.toLowerCase(),
      correct_answer: correctAnswer.toUpperCase(),
    });

    // Build API parameters with proper encoding
    const apiParams = `&${params.toString()}`;

    console.log("API Call Parameters:", {
      UserID: UserID?.UserID,
      ChapterID: ChapterID,
      apiParams: apiParams,
      fullURL: `${UserID?.UserID}/${ChapterID}/${apiParams}`,
    });

    // Make API call
    oneshotUpdateAndGetRecord(UserID?.UserID, ChapterID, apiParams)
      .then((res) => {
        console.log("=== API Response Success ===");
        console.log("Response Data:", res.data);

        // Add detailed logging for score
        console.log("Current score state:", score);
        console.log("Score from API:", res.data.score);
        console.log("Score type:", typeof res.data.score);

        if (!res.data) {
          console.error("No data received from API");
          return;
        }

        const { nextQuestion, score: newScore } = res.data;

        // Always update score if provided
        if (typeof newScore === "number") {
          console.log("Updating score from", score, "to", newScore);
          setScore(newScore);
        
          const questionsCompleted = currentQuestion;
          const roundedScore = parseFloat((newScore * 100).toFixed(1));
        
          // ✅ 1. Question Milestones
          const questionMilestones = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
          if (
            questionMilestones.includes(questionsCompleted) &&
            !milestonesShown.questions.includes(questionsCompleted)
          ) {
            showEncouragement(questionsCompleted, 'milestone',language); // 🔄 Pass milestone value
            setMilestonesShown((prev) => ({
              ...prev,
              questions: [...prev.questions, questionsCompleted],
            }));
          }
        
          // ✅ 2. Score Milestones
          const scoreMilestones = [10, 20, 40, 60, 80];
          const crossedMilestone = scoreMilestones.find(
            (milestone) =>
              roundedScore >= milestone && !milestonesShown.scores.includes(milestone)
          );
        
          if (crossedMilestone) {
            showEncouragement(crossedMilestone, 'score',language); // 🔄 Pass score milestone value
            setMilestonesShown((prev) => ({
              ...prev,
              scores: [...prev.scores, crossedMilestone],
            }));
          }
        }
         else if (newScore !== undefined) {
          // Try to convert the score to a number if it's not already
          const parsedScore = parseFloat(newScore);
          if (!isNaN(parsedScore)) {
            console.log(
              "Updating score from",
              score,
              "to",
              parsedScore,
              "(after conversion)"
            );
            setScore(parsedScore);
          } else {
            console.error("Invalid score format received:", newScore);
          }
        } else {
          console.warn("No score received in API response");
        }

        // If we have a next question and we're at the last question, add it
        if (nextQuestion?.length > 0 && currentQuestion === question.length) {
          console.log("Adding new question:", nextQuestion[0]);
          
          // First, update the originalQuestions state with the new questions
          const updatedOriginalQuestions = [...originalQuestions, ...nextQuestion];
          setOriginalQuestions(updatedOriginalQuestions);
          
          // Then apply translations based on current language
          const translatedNextQuestions = nextQuestion.map(questionItem => 
            updateQuestionData(questionItem, language.Definer)
          );
          console.log("Translated new question:", translatedNextQuestions[0]);

          const updatedQuestions = [...question, ...translatedNextQuestions];
          setQuestionMain(updatedQuestions);
          setTotalPages(updatedQuestions.length);

          const updatedStatus = [
            ...questionTestStatus,
            {
              optionChosen: "",
              optionBeforeSubmit: "",
              QuestionID: nextQuestion[0].QuestionID,
              QuestionType: nextQuestion[0].QuestionType,
            },
          ];
          setQuestionTestStatus(updatedStatus);
        }

        // Allow navigation to next question if available
        if (currentQuestion < question.length) {
          setCurrentQuestion((prev) => prev + 1);
        }
        else {
  // All questions completed
  if (!milestonesShown.questions.includes("complete")) {
   
// For final question
showEncouragement("🏁 You've completed all the questions! Amazing effort!");
    setMilestonesShown((prev) => ({
      ...prev,
      questions: [...prev.questions, "complete"],
    }));
  }
}

      })
      .catch((err) => {
        console.error("=== API Error Debug ===");
        console.error("Error Details:", {
          message: err.message,
          userAnswer: userAnswer,
          correctAnswer: correctAnswer,
          questionId: currentQuestionData.QuestionID,
          fullURL: `${UserID?.UserID}/${ChapterID}/${apiParams}`,
        });

        // Still allow navigation on error if there are more questions
        if (currentQuestion < question.length) {
          setCurrentQuestion((prev) => prev + 1);
        }
      });

    // After updating score and current question
    checkAchievements(score, currentQuestion);

    // Handle answer feedback
    const isCorrect = questionTestStatus[currentQuestion - 1]?.optionChosen === question[currentQuestion - 1]?.CorrectOption;
    
    // Clear any existing message first
    setEncouragementMessage("");
    setEncouragementType("");
    
    // Only show message for wrong answers
    if (!isCorrect) {
      showEncouragement("wrongAnswer", 'wrongAnswer', language);
    }
    
  };
  console.log(questionMain);
  useEffect(() => {
    console.log("=== Language Switch Debug ===");
    console.log("Language changed to:", language?.Name);
    console.log("Original Questions length:", originalQuestions?.length);
    console.log("Question Test Status length:", questionTestStatus?.length);
    
    if (originalQuestions?.length) {
      // We'll handle the question translation in the other useEffect
      // This effect will focus solely on updating questionTestStatus based on the new language
      
      // Get the current translated questions from the other useEffect
      const updatedDataArray = originalQuestions.map((questionI) =>
        updateQuestionData(questionI, language.Definer)
      );
      
      // Update the questionTestStatus to preserve user choices while updating text
      const updatedStatus = updatedDataArray.map((translatedQuestion, idx) => {
        // If we have existing test status for this question, preserve the user choices
        if (idx < questionTestStatus.length) {
          return {
            ...questionTestStatus[idx],
            // Update the optionBeforeSubmit with the newly translated text
            optionBeforeSubmit:
              translatedQuestion.UserAnswer && 
              translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
                ? translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
                : ""
          };
        } else {
          // For new questions without existing test status
          return {
            QuestionID: translatedQuestion.QuestionID,
            QuestionType: translatedQuestion.QuestionType,
            optionBeforeSubmit: 
              translatedQuestion.UserAnswer && 
              translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
                ? translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
                : "",
            optionChosen: translatedQuestion.UserAnswer ? translatedQuestion.UserAnswer : "",
          };
        }
      });
      
      console.log("Updated status after translation:", updatedStatus?.length);
      setQuestionTestStatus(updatedStatus);
    }
  }, [
    language?.id,
    language?.Definer
    // Remove dependency on originalQuestions as it's handled in the other useEffect
    // Remove dependency on questionTestStatus.length to avoid infinite loops
  ]);
  console.log(questionTestStatus);
  useEffect(() => {
    if (location.state?.Questions?.length) {
      setOriginalQuestions(location.state.Questions);
    }
  }, [location.state?.Questions]);

  useEffect(() => {
    if (
      location.state?.questionTestStatus &&
      location.state?.currentQuestion >= 0
    ) {
      setQuestionTestStatus(location.state?.questionTestStatus);
      setCurrentQuestion(location.state?.currentQuestion);
    }
  }, [location?.state]);

  useEffect(() => {
    const handleKeyPress = (event) => {
      // Disable F5 key
      if (event.keyCode === 116) {
        event.preventDefault();
      }

      // Disable browser reload (Ctrl+R or Command+R)
      if ((event.ctrlKey || event.metaKey) && event.keyCode === 82) {
        event.preventDefault();
      }
    };

    const handleBeforeUnload = (event) => {
      // Display a confirmation dialog
      event.preventDefault();
      const confirmationMessage = "Are you sure you want to leave?";
      event.returnValue = confirmationMessage; // Standard-compliant browsers
      return confirmationMessage; // For legacy browsers
    };

    // Attach the event listeners when the component mounts
    window.addEventListener("keydown", handleKeyPress);
    window.addEventListener("beforeunload", handleBeforeUnload);

    // Detach the event listeners when the component unmounts
    return () => {
      window.removeEventListener("keydown", handleKeyPress);
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  const [containerWidth, setContainerWidth] = useState(
    window?.innerWidth < 600.02 ? 350 : 400
  );
  let comprehensionDataReflector = question?.length
    ? question[currentQuestion - 1]?.Instructions
    : null;
  const handleMouseDown = (event) => {
    let startX = event.pageX; // Capture the initial X position

    const handleDrag = throttle((event) => {
      const deltaX = event.pageX - startX; // Calculate the change in X position
      setContainerWidth((prevWidth) => {
        let newWidth = prevWidth + deltaX;
        if (newWidth < 200) {
          newWidth = 200;
        } else if (newWidth > 800) {
          newWidth = 800;
        }
        startX = event.pageX; // Update the start X position for the next drag movement
        return newWidth;
      });
    }, 16); // Throttle to roughly 60fps (16ms)

    const handleMouseUp = () => {
      document.removeEventListener("mousemove", handleDrag);
      document.removeEventListener("mouseup", handleMouseUp);
    };

    document.addEventListener("mousemove", handleDrag);
    document.addEventListener("mouseup", handleMouseUp);
  };

  const handleSubmitTest = () => {
    navigate("/oneshot");
  };

  // console.log(comprehensionDataReflector);

  useEffect(() => {
    if (!skipInitialLoader) {
      // Only show loader if not skipping
      const timer = setTimeout(() => {
        setLoading(false);
      }, 1500);
      return () => clearTimeout(timer);
    }
  }, [skipInitialLoader]);

  // pagination controls

  const goToPage = (page) => {
    if (page >= 1 && page <= totalPages) {
      // Pause any ongoing speech before changing the question
      if (textToSpeechRef.current) {
        textToSpeechRef.current.pauseSpeech();
      }
      setCurrentQuestion(page);
    }
  };

  const getPaginationRange = () => {
    const pages = [];
    let showPiece = window?.innerWidth > 600.02 ? 2 : 1;
    let startPage = Math.max(1, currentQuestion - showPiece);
    let endPage = Math.min(totalPages, currentQuestion + showPiece);

    // Add previous ellipsis
    if (startPage > 1) {
      // pages.push("<<");
      // pages.push("<");
    }

    // Add page numbers
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }

    // Add next ellipsis
    if (endPage < totalPages) {
      // pages.push(">");
      // pages.push(">>");
    }

    return pages;
  };

  // Reset questionSubmitted when moving to next question
  useEffect(() => {
    setQuestionSubmitted(false);
  }, [currentQuestion]);

  useEffect(() => {
    if (
      // question[currentQuestion - 1]?.QuestionID?.toLowerCase().includes(
      //   "theory"
      // ) &&
      question?.length === currentQuestion &&
      !speakerVoiceActivatedOnce
    ) {
      setSpeakerVoiceActivatedOnce(true);
    } else {
      // if (speakerVoiceActivatedOnce &&(question?.length === currentQuestion)) setSpeakerVoiceActivatedOnce(false);
    }
  }, [question?.length]);

  // Add a useEffect to update translated questions whenever originalQuestions changes
  useEffect(() => {
    console.log("=== Original Questions Update Debug ===");
    console.log("Original Questions changed, length:", originalQuestions?.length);
    
    if (originalQuestions?.length && language) {
      // Apply current language translations
      const updatedDataArray = originalQuestions.map((questionI) =>
        updateQuestionData(questionI, language.Definer)
      );
      console.log("Setting translated questions, length:", updatedDataArray?.length);
      setQuestionMain(updatedDataArray);
    }
  }, [originalQuestions, language?.Definer]); // Only depend on originalQuestions and language.Definer

  // useEffect to initialize originalQuestions when component loads
  useEffect(() => {
    if (location.state?.Questions?.length) {
      setOriginalQuestions(location.state.Questions);
    }
  }, [location.state?.Questions]);

  // // Add test buttons for development
  // const TestButtons = () => {
  //   if (process.env.NODE_ENV !== "development") return null;

  //   return (
  //     <div style={{ 
  //       position: 'fixed', 
  //       bottom: '2rem', 
  //       right: '2rem', // Changed from left to right
  //       zIndex: 999,
  //       display: 'flex',
  //       flexDirection: 'column',
  //       gap: '0.5rem',
  //       backgroundColor: 'var(--bg-primary-clr)',
  //       padding: '1rem',
  //       borderRadius: '8px',
  //       boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
  //     }}>
  //       <h4 style={{ margin: '0 0 0.5rem 0', color: 'var(--text-primary-clr)' }}>Test Messages</h4>
  //       <button 
  //         onClick={() => showEncouragement("wrongAnswer", 'wrongAnswer',language)}
  //         style={{
  //           padding: '0.5rem 1rem',
  //           backgroundColor: 'var(--accent-primary-clr)',
  //           color: 'white',
  //           border: 'none',
  //           borderRadius: '4px',
  //           cursor: 'pointer'
  //         }}
  //       >
  //         Test Wrong Answer
  //       </button>
  //       <button 
  //         onClick={() => showEncouragement("correctAnswer", 'correctAnswer',language)}
  //         style={{
  //           padding: '0.5rem 1rem',
  //           backgroundColor: 'var(--accent-primary-clr)',
  //           color: 'white',
  //           border: 'none',
  //           borderRadius: '4px',
  //           cursor: 'pointer'
  //         }}
  //       >
  //         Test Correct Answer
  //       </button>
  //       <button 
  //         onClick={() => showEncouragement(5,"milestone", 'milestone',language)}
  //         style={{
  //           padding: '0.5rem 1rem',
  //           backgroundColor: 'var(--accent-primary-clr)',
  //           color: 'white',
  //           border: 'none',
  //           borderRadius: '4px',
  //           cursor: 'pointer'
  //         }}
  //       >
  //         Test Question Milestone
  //       </button>
  //       <button 
  //         onClick={() => showEncouragement(11,"highScore", 'highScore',language)}
  //         style={{
  //           padding: '0.5rem 1rem',
  //           backgroundColor: 'var(--accent-primary-clr)',
  //           color: 'white',
  //           border: 'none',
  //           borderRadius: '4px',
  //           cursor: 'pointer'
  //         }}
  //       >
  //         Test Score Achievement
  //       </button>
  //       <button 
  //         onClick={() => showEncouragement("completion", 'completion',language)}
  //         style={{
  //           padding: '0.5rem 1rem',
  //           backgroundColor: 'var(--accent-primary-clr)',
  //           color: 'white',
  //           border: 'none',
  //           borderRadius: '4px',
  //           cursor: 'pointer'
  //         }}
  //       >
  //         Test Completion
  //       </button>
  //     </div>
  //   );
  // };

  if (loading) return <Preloader />;
  console.log("Checking the score at the moment");
  console.log(
    question[currentQuestion - 1]?.QuestionID?.toLowerCase().includes("theory")
  );

  return (
    <div className="TestStartingContainer">
      {encouragementMessage && (
        <EncouragementMessage 
          message={encouragementMessage} 
          type={encouragementType}
          language={language}
        />
      )}
      {/* <TestButtons /> */}
      <div
        className="TestButtosContainer testContentViewPort3"
        style={{ maxWidth: "100%" }}
      >
        <div className="uniVersalTextRecord headingButtons">
          <div>
            {TestTitle ? (
              <>Title : &nbsp;{TestTitle}</>
            ) : (
              <>Chapter: &nbsp;{ChapterName}</>
            )}
            <AnimatedScore value={score} />

            {question?.find((obj, idx) => obj.Question_hi != null) ? (
              <div
                style={{ marginLeft: "0.5rem" }}
                // onClick={()=>setOpenLanguage(prev=>!prev)}
              >
                <div
                  className="app-btn-1-reverse"
                  style={{ width: "fit-content", padding: "0.5rem 0.5rem" }}
                  onClick={() => setOpenLanguage(true)}
                >
                  <TranslateSvg /> {language?.Name}
                </div>
                {openLanguage ? (
                  <>
                    <div
                      className="dropdownLanguageGuided"
                      style={{ right: null }}
                    >
                      {LanguagesSlugs?.filter(
                        (obj) => obj.id !== language?.id
                      )?.map((obj) => (
                        <div
                          className="ObjectTileLanguage"
                          onClick={() => [
                            setLanguagesSlugs(obj),
                            localStorage.setItem("language", obj?.id),
                            setOpenLanguage(false),
                          ]}
                        >
                          {obj.Svg}
                          {obj.Name}
                        </div>
                      ))}
                    </div>
                    <BackDrop
                      blur
                      closeHandler={() => setOpenLanguage(false)}
                    />
                  </>
                ) : null}
              </div>
            ) : null}
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "0.4em",
              flexDirection: "row-reverse",
              flexWrap: "wrap",
            }}
          >
            <button className="app-btn-1" onClick={() => handleSubmitTest()}>
              {"Exit practice ->"}
            </button>

            <div>
              {
                question?.length === currentQuestion &&
                  speakerVoiceActivatedOnce && (
                    <TextToSpeech
                      ref={textToSpeechRef}
                      text={
                        language?.id === "hi"
                          ? (question[currentQuestion - 1]?.QuestionTTS_hi || question[currentQuestion - 1]?.Question_hi)
                          : (question[currentQuestion - 1]?.QuestionTTS || question[currentQuestion - 1]?.Question)
                      }
                    />
                  )
              }
            </div>
          </div>
        </div>
        <div
          style={{
            display: "inline-block",
            alignItems: "center",
            marginLeft: "0",
            fontFamily: "inherit",
            fontSize: "inherit",
            lineHeight: "inherit",
          }}
        >
          <button
            onClick={() => {
              if (textToSpeechRef.current) {
                textToSpeechRef.current.pauseSpeech();
              }
              goToPage(1);
            }}
            disabled={currentQuestion <= 1}
            style={{
              background: "none",
              border: "none",
              color: "inherit",
              fontSize: "inherit",
              cursor: "pointer",
              padding: "0 0.4rem",
              opacity: currentQuestion <= 1 ? 0.5 : 1,
            }}
          >
            {"<<"}
          </button>
          <button
            onClick={() => {
              if (textToSpeechRef.current) {
                textToSpeechRef.current.pauseSpeech();
              }
              goToPage(currentQuestion - 1);
            }}
            disabled={currentQuestion <= 1}
            style={{
              background: "none",
              border: "none",
              color: "inherit",
              fontSize: "inherit",
              cursor: "pointer",
              padding: "0 0.4rem",
              opacity: currentQuestion <= 1 ? 0.5 : 1,
            }}
          >
            {"<"}
          </button>
          {getPaginationRange().map((page) => (
            <span
              key={page}
              onClick={() => goToPage(page)}
              style={{
                cursor: "pointer",
                padding: "0 0.4rem",
                fontWeight: currentQuestion === page ? "bold" : "normal",
                color: "inherit",
              }}
            >
              {page}
            </span>
          ))}
          <button
            onClick={() => {
              if (textToSpeechRef.current) {
                textToSpeechRef.current.pauseSpeech();
              }
              goToPage(currentQuestion + 1);
            }}
            disabled={currentQuestion >= totalPages}
            style={{
              background: "none",
              border: "none",
              color: "inherit",
              fontSize: "inherit",
              cursor: "pointer",
              padding: "0 0.4rem",
              opacity: currentQuestion >= totalPages ? 0.5 : 1,
            }}
          >
            {">"}
          </button>
          <button
            onClick={() => {
              if (textToSpeechRef.current) {
                textToSpeechRef.current.pauseSpeech();
              }
              goToPage(totalPages);
            }}
            disabled={currentQuestion >= totalPages}
            style={{
              background: "none",
              border: "none",
              color: "inherit",
              fontSize: "inherit",
              cursor: "pointer",
              padding: "0 0.4rem",
              opacity: currentQuestion >= totalPages ? 0.5 : 1,
            }}
          >
            {">>"}
          </button>
        </div>
        <div
          className="TestStartingContainer CompressionBoxCont"
          style={{
            marginInline: "1%",
            marginTop: "0em",
            gridTemplateColumns: comprehensionDataReflector ? "" : "1fr",
            maxWidth: comprehensionDataReflector ? "" : "calc(90% - 1rem)",
            width: comprehensionDataReflector ? "" : "calc(90% - 2rem)",
          }}
        >
          {comprehensionDataReflector ? (
            <>
              <div className="comprehensionHead">Instructions</div>
              <div
                className="draggableLine"
                onMouseDown={handleMouseDown}
              ></div>

              <div className="comprehensionHead QuestionBig">Question</div>

              <ComprehensionBox
                containerWidth={containerWidth}
                data={comprehensionDataReflector}
                render={
                  question?.length
                    ? question[currentQuestion - 1]?.RenderFormat
                    : null
                }
              />
              <div className="comprehensionHead QuestionSmall">Question</div>
              <div
                className="draggableLine"
                onMouseDown={handleMouseDown}
              ></div>
            </>
          ) : null}

          <div
            className="TestButtosContainer testContentViewPort"
            style={{
              maxWidth:
                window.innerWidth > 600.02 && comprehensionDataReflector
                  ? `calc(90% - ${containerWidth}px - 1em)`
                  : "90vw",
              //   width: `calc(100% - ${containerWidth}px)`,
              minWidth:
                // window.innerWidth > 600.02 &&
                comprehensionDataReflector
                  ? `calc(${90}vw - ${containerWidth}px - 1em)`
                  : "90vw",
            }}
          >
            {question.map(
              (object, idx) =>
                currentQuestion === idx + 1 && (
                  <OpttionContainerOneshot
                    question={object}
                    setCurrentQuestion={setCurrentQuestion}
                    currentQuestion={currentQuestion - 1}
                    questionTestStatus={questionTestStatus}
                    setQuestionTestStatus={setQuestionTestStatus}
                    handleClickNextButton={handleClickNextButton}
                  />
                )
            )}
          </div>
          {/* <div style={{ height: "4em" }}></div> */}
        </div>
        {/* Only show ChatVoiceComponent when question is submitted */}
        {questionSubmitted && (
          <ChatVoiceComponent
            question={JSON.stringify({
              currentQuestion: question[currentQuestion - 1],
              userAnswer: questionTestStatus[currentQuestion - 1]?.optionChosen,
              correctAnswer: question[currentQuestion - 1]?.CorrectOption,
              explanation:
                question[currentQuestion - 1]?.Solution ||
                question[currentQuestion - 1]?.Explanation,
            })}
          />
        )}
      </div>
    </div>
  );
}

export default PracticePage;
export const TranslateSvg = () => {
  return (
    <svg
      width="14"
      height="15"
      viewBox="0 0 26 27"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M23.9995 13.3333H21.3328C20.9792 13.3333 20.6401 13.4738 20.39 13.7239C20.14 13.9739 19.9995 14.3131 19.9995 14.6667C19.9995 15.0203 20.14 15.3594 20.39 15.6095C20.6401 15.8595 20.9792 16 21.3328 16V18.6667H19.7538C19.9119 18.2397 19.995 17.7886 19.9995 17.3333C19.9996 16.4528 19.7092 15.5968 19.1732 14.8982C18.6371 14.1996 17.8855 13.6974 17.035 13.4695C16.1844 13.2417 15.2824 13.3009 14.469 13.638C13.6555 13.9751 12.976 14.5713 12.536 15.334C12.4476 15.4857 12.39 15.6534 12.3666 15.8274C12.3432 16.0014 12.3544 16.1783 12.3995 16.348C12.4447 16.5177 12.5229 16.6768 12.6297 16.8161C12.7365 16.9555 12.8698 17.0724 13.0219 17.1601C13.174 17.2478 13.342 17.3046 13.5161 17.3273C13.6902 17.3499 13.8671 17.3379 14.0365 17.292C14.206 17.2461 14.3648 17.1672 14.5036 17.0597C14.6425 16.9523 14.7588 16.8185 14.8458 16.666C14.963 16.4637 15.1312 16.2956 15.3336 16.1788C15.5361 16.0619 15.7657 16.0002 15.9995 16C16.3531 16 16.6923 16.1405 16.9423 16.3905C17.1924 16.6406 17.3328 16.9797 17.3328 17.3333C17.3328 17.687 17.1924 18.0261 16.9423 18.2761C16.6923 18.5262 16.3531 18.6667 15.9995 18.6667C15.6459 18.6667 15.3067 18.8071 15.0567 19.0572C14.8066 19.3072 14.6662 19.6464 14.6662 20C14.6662 20.3536 14.8066 20.6928 15.0567 20.9428C15.3067 21.1929 15.6459 21.3333 15.9995 21.3333C16.3531 21.3333 16.6923 21.4738 16.9423 21.7239C17.1924 21.9739 17.3328 22.3131 17.3328 22.6667C17.3328 23.0203 17.1924 23.3594 16.9423 23.6095C16.6923 23.8595 16.3531 24 15.9995 24C15.7657 23.9998 15.5361 23.9381 15.3336 23.8212C15.1312 23.7043 14.963 23.5363 14.8459 23.334C14.7588 23.1815 14.6425 23.0477 14.5037 22.9403C14.3648 22.8328 14.206 22.7539 14.0366 22.708C13.8671 22.6621 13.6902 22.6501 13.5161 22.6727C13.342 22.6954 13.174 22.7522 13.0219 22.8399C12.8698 22.9276 12.7365 23.0445 12.6297 23.1838C12.5229 23.3232 12.4447 23.4823 12.3996 23.652C12.3544 23.8216 12.3432 23.9986 12.3666 24.1726C12.39 24.3466 12.4476 24.5143 12.536 24.666C12.976 25.4287 13.6555 26.0248 14.469 26.362C15.2824 26.6991 16.1844 26.7583 17.035 26.5304C17.8855 26.3026 18.6371 25.8004 19.1731 25.1018C19.7092 24.4032 19.9996 23.5472 19.9995 22.6667C19.995 22.2114 19.9119 21.7603 19.7538 21.3333H21.3328V25.3333C21.3328 25.687 21.4733 26.0261 21.7234 26.2762C21.9734 26.5262 22.3125 26.6667 22.6662 26.6667C23.0198 26.6667 23.3589 26.5262 23.609 26.2762C23.859 26.0261 23.9995 25.687 23.9995 25.3333V16C24.3531 16 24.6923 15.8595 24.9423 15.6095C25.1924 15.3594 25.3328 15.0203 25.3328 14.6667C25.3328 14.3131 25.1924 13.9739 24.9423 13.7239C24.6923 13.4738 24.3531 13.3333 23.9995 13.3333ZM8.03988 12.3236C8.12569 12.6665 8.34422 12.9613 8.64738 13.1431C8.79749 13.2331 8.96386 13.2927 9.13699 13.3184C9.31012 13.3441 9.48662 13.3355 9.65642 13.293C9.82621 13.2505 9.98597 13.175 10.1266 13.0707C10.2672 12.9665 10.3859 12.8356 10.4759 12.6855C10.5659 12.5354 10.6255 12.369 10.6512 12.1959C10.6769 12.0227 10.6683 11.8462 10.6258 11.6764L8.28336 2.30339C8.11894 1.64548 7.73931 1.06142 7.20481 0.644061C6.67031 0.226701 6.01163 0 5.33349 0C4.65535 0 3.99667 0.226701 3.46217 0.644061C2.92767 1.06142 2.54804 1.64548 2.38362 2.30339L0.0398773 11.6764C-0.0459397 12.0193 0.00798124 12.3823 0.189778 12.6855C0.371574 12.9886 0.666355 13.2072 1.00927 13.293C1.35219 13.3788 1.71515 13.3249 2.01831 13.1431C2.32147 12.9613 2.53999 12.6665 2.62581 12.3236L3.37353 9.33334H7.29256L8.03988 12.3236ZM4.04036 6.66667L4.96956 2.95053C4.99773 2.87684 5.04761 2.81344 5.11259 2.76872C5.17757 2.72399 5.2546 2.70005 5.33349 2.70005C5.41238 2.70005 5.48941 2.72399 5.55439 2.76872C5.61937 2.81344 5.66925 2.87684 5.69742 2.95053L6.62613 6.66667H4.04036ZM14.6662 6.66667H15.9995C16.353 6.66703 16.6919 6.80762 16.9419 7.05759C17.1919 7.30756 17.3325 7.64649 17.3328 8.00001V9.33334C17.3328 9.68696 17.4733 10.0261 17.7234 10.2761C17.9734 10.5262 18.3125 10.6667 18.6662 10.6667C19.0198 10.6667 19.3589 10.5262 19.609 10.2761C19.859 10.0261 19.9995 9.68696 19.9995 9.33334V8.00001C19.9983 6.9395 19.5765 5.92275 18.8267 5.17286C18.0768 4.42296 17.06 4.00116 15.9995 4.00001H14.6662C14.3125 4.00001 13.9734 4.14048 13.7234 4.39053C13.4733 4.64058 13.3328 4.97972 13.3328 5.33334C13.3328 5.68696 13.4733 6.0261 13.7234 6.27615C13.9734 6.5262 14.3125 6.66667 14.6662 6.66667ZM9.33284 18.6667H7.9995C7.64599 18.6663 7.30706 18.5257 7.05708 18.2758C6.80711 18.0258 6.66652 17.6869 6.66617 17.3333V16C6.66617 15.6464 6.5257 15.3072 6.27565 15.0572C6.0256 14.8071 5.68646 14.6667 5.33284 14.6667C4.97921 14.6667 4.64008 14.8071 4.39003 15.0572C4.13998 15.3072 3.9995 15.6464 3.9995 16V17.3333C4.00066 18.3939 4.42246 19.4106 5.17236 20.1605C5.92225 20.9104 6.93899 21.3322 7.9995 21.3333H9.33284C9.68646 21.3333 10.0256 21.1929 10.2756 20.9428C10.5257 20.6928 10.6662 20.3536 10.6662 20C10.6662 19.6464 10.5257 19.3072 10.2756 19.0572C10.0256 18.8071 9.68646 18.6667 9.33284 18.6667Z"
        fill="#F9F9F9"
      />
    </svg>
  );
};