let attemptedQuestionArray = [];
let attemptedAnswerArray = [];
let visitedQuestionArray = [];
let lockedQuestionArray = [];
let currentSlideNum = 1;

let correctImage = `<img class="result-image" src="./images/correct.png" alt="correct">`;
let incorrectImage = `<img class="result-image" src="./images/incorrect.png" alt="incorrect">`;
let notAttemptedImage = `<img class="result-image" src="./images/not-attempted.png" alt="not-attempted"></img>`;

for (let i = 0; i < data.questions.length; i++) {
  attemptedQuestionArray[i] = 0;
  attemptedAnswerArray[i] = "no";
  lockedQuestionArray[i] = "no";
  if (i == 0) {
    visitedQuestionArray[i] = 1;
  }
  if (i > 0) {
    visitedQuestionArray[i] = 0;
  }
}

let startBtn = document.getElementById("startBtn");
let startPage = document.getElementById("start-page");
let mainPage = document.getElementById("main-page");
let previewQuizAttemptPage = document.getElementById("preview-quiz-attempt");
let endPage = document.getElementById("end-page");
let quizHeading = document.getElementById("quiz-heading");
quizHeading.innerHTML = data.quizHeading;
let marker;

startBtn.addEventListener("click", function () {
  startPage.style.display = "none";
  endPage.style.display = "none";
  previewQuizAttemptPage.style.display = "none";
  mainPage.style.display = "block";
  goToSlide($currentSlide);

  marker = document.querySelector(".radioMover");
});





let questionSlideMainContainer = document.getElementById("question-slides-main");
questionSlideMainContainer.innerHTML = "";
let totalQuestions = data.questions.length;
let navList = document.getElementById("nav-list");
navList.innerHTML = "";

let rubric = document.getElementById("rubric");
rubric.innerHTML = data.instruction;

for (let i = 0; i < totalQuestions; i++) {
  var userAgent = navigator.userAgent;
  let opening = ``;
  if (/iPhone/i.test(userAgent)) {
    let pageHeight = $(window).innerHeight();
    let style = `style="height: ${pageHeight}px;"`;
    opening = `
          <div class="slide" id="slide-${i + 1}" ${style}>
            <div class="container">
              <div class="row">
                <div class="col fs-5">
                  <p class="question_num">Question ${i + 1}</p>
                  <p class="hang">${data.questions[i].ques}</p>
                </div>
              </div>
              <div class="row">
                <div class="col col-vr">
                  <form>`;
  } else if (/ipad/.test(userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) {
    let pageHeight = $(window).innerHeight();
    let style = `style="height: ${pageHeight}px;"`;
    opening = `
          <div class="slide" id="slide-${i + 1}" ${style}>
            <div class="container">
              <div class="row">
                <div class="col fs-5">
                  <p class="question_num">Question ${i + 1}</p>
                  <p class="hang">${data.questions[i].ques}</p>
                </div>
              </div>
              <div class="row">
                <div class="col col-vr">
                  <form>`;
  } else {
    opening = `
          <div class="slide" id="slide-${i + 1}">
            <div class="container">
              <div class="row">
                <div class="col fs-5">
                  <p class="question_num">Question ${i + 1}</p>
                  <p class="hang">${data.questions[i].ques}</p>
                </div>
              </div>
              <div class="row">
                <div class="col col-vr">
                  <form>`;
  }

  let inputs = '';

  for (let j = 0; j < data.questions[i].options.length; j++) {
    if (data.questions[i].ans[0] === j) {
     
      inputs += `<input type="radio" name="r${i + 1}" id="r${i + 1}_queston_text_${j}" class="option${i + 1} option_label_input"><label data-questionNum="${i + 1}" data-optionId="${j}" for="r${i + 1}_queston_text_${j}" class="option_label correct${i + 1}" >${data.questions[i].options[j]}</label>`;
    }
    else {
      
      inputs += `<input type="radio" name="r${i + 1}" id="r${i + 1}_queston_text_${j}" class="option${i + 1} option_label_input"><label data-questionNum="${i + 1}" data-optionId="${j}" for="r${i + 1}_queston_text_${j}" class="option_label" >${data.questions[i].options[j]}</label>`;
    }
  }
  let closing = `<span class="radioMover"></span>
                  </form>
                </div>
              </div>
              <div class="row button-div">
                ${(i + 1) === 1 ?
      `<button id="disabled-prev-button">Previous</button>`
      : `<button class="prev-button">Previous</button>`
    }
                ${(i + 1) === data.questions.length ?
      `<button id="submit-button">Submit</button>`
      : `<button class="next-button">Next</button>`
    }
              </div>
            </div>
          </div>
    `;

  questionSlideMainContainer.innerHTML += opening + inputs + closing;
  navList.innerHTML += `<li><a id="${i + 1}" data-anchor="slide_anchor" href="#slide-${i + 1}">${i + 1}</a></li>`;
}

function lockQuestion() {
  lockedQuestionArray[currentSlideNum - 1] = "yes";
}

function handleRadioClick(e) {

  let optionId = parseInt(e.target.dataset.optionid);
  if (lockedQuestionArray[currentSlideNum - 1] === "no") {
    attemptedAnswerArray[currentSlideNum - 1] = optionId;
  }
}
let options = document.getElementsByClassName("option_label");
Array.from(options).forEach(function (option) {
  option.addEventListener("click", function (e) {
    handleRadioClick(e); // keep your existing answer tracking

    // === marker movement ===
    const form = option.closest("form");
    const marker = form.querySelector(".radioMover");
    if (!marker) return;

    const labelRect = option.getBoundingClientRect();
    const parentRect = form.getBoundingClientRect();

    // vertical offset relative to form
    const offsetY = labelRect.top - parentRect.top +9;

    // position marker
    marker.style.transition = "top 0.25s ease";
    marker.style.position = "absolute"; // ensure absolute
    marker.style.left = "0.25em";       // adjust if needed
    marker.style.top = offsetY + "px";
    marker.style.visibility = "visible";
  });
});


function disableOption() {
  if (attemptedAnswerArray[currentSlideNum - 1] !== "no") {
    Array.from(document.getElementsByClassName("option" + currentSlideNum)).forEach(function (e) {
      e.removeEventListener("click", handleRadioClick);
      e.disabled = true;
      lockQuestion();
    });
  }
}

let prevButton = document.getElementsByClassName("prev-button");
let nextButton = document.getElementsByClassName("next-button");
let submitButton = document.getElementById("submit-button");

Array.from(prevButton).forEach(function (element) {
  element.addEventListener("click", () => {
    disableOption();
    visitedQuestionArray[currentSlideNum - 1] = 1;
    goToPrevSlide();
    listButtonColorUpdate();
    scrollToTop();
  })
});

Array.from(nextButton).forEach(function (element) {
  element.addEventListener("click", () => {
    disableOption();
    visitedQuestionArray[currentSlideNum] = 1;
    goToNextSlide();
    listButtonColorUpdate();
    scrollToTop();
  })
});

submitButton.addEventListener("click", () => {
  disableOption();
  scrollToTop();
  startPage.style.display = "none";
  endPage.style.display = "none";
  mainPage.style.display = "none";
  previewQuizAttemptPage.style.display = "flex";
  let tableSection1 = `<table>
  <tr>
    <th>Question No.</th>
    <th>Status</th>
  </tr>`;

  for (let i = 0; i < data.questions.length; i++) {
    tableSection1 += `
    <tr>
    <td><a class="preview-question-number">${i + 1}</a></td>
    <td>${(attemptedAnswerArray[i] != "no") ? "Attempted" : "Not Attempted"}</td>
  </tr>`;
  }

  let tableSection2 = `</table>
  <button id="final-submit">Final Submit</button>`;

  previewQuizAttemptPage.innerHTML = tableSection1 + tableSection2;
  let previewQuestionNumber = document.getElementsByClassName("preview-question-number");
  Array.from(previewQuestionNumber).forEach(function (element) {
    element.addEventListener("click", () => {
      startPage.style.display = "none";
      endPage.style.display = "none";
      previewQuizAttemptPage.style.display = "none";
      mainPage.style.display = "block";
      goToSlide($((document.getElementById(`slide-${parseInt(element.innerHTML)}`))));
      currentSlideNum = parseInt(element.innerHTML);
      visitedQuestionArray[parseInt(element.innerHTML) - 1] = 1;
      listButtonColorUpdate();
    })
  });
  let finalSubmitButton = document.getElementById("final-submit");
  finalSubmitButton.addEventListener("click", function () {

    startPage.style.display = "none";
    previewQuizAttemptPage.style.display = "none";
    mainPage.style.display = "none";
    endPage.style.display = "flex";

    let finalSubmitSection1 = `<div id="score">Score : ${totalScore()}</div>
    
    <table>
    <tr>
      <th>Question No.</th>
      <th>Result</th>
    </tr>`;

    for (let i = 0; i < data.questions.length; i++) {
      finalSubmitSection1 += `
    <tr>
      <td>${i + 1}</td>
      <td>${(attemptedAnswerArray[i] === "no") ? notAttemptedImage : ((attemptedAnswerArray[i] === data.questions[i].ans[0]) ? correctImage : incorrectImage)}</td>
    </tr>`;
    }

    let finalSubmitSection2 = `</table>
    <div class="infoImage">Correct : <img class="result-image" src="./images/correct.png" alt="correct"></div>
    <div class="infoImage">Incorrect : <img class="result-image" src="./images/incorrect.png" alt="correct"></div>
    <div class="infoImage">Not Attempted : <img class="result-image" src="./images/not-attempted.png" alt="correct"></div>`;

    endPage.innerHTML = finalSubmitSection1 + finalSubmitSection2;
  });
});

let listButtons = document.querySelectorAll("nav a");

function listButtonColorUpdate() {
  listButtons.forEach((btn) => {
    if (!(visitedQuestionArray[parseInt(btn.id - 1)])) {
      btn.style.backgroundColor = "#ededed";
      btn.style.boxShadow = "";
    }
    if (visitedQuestionArray[parseInt(btn.id - 1)]) {
      // btn.style.backgroundColor = "#ffc6c6";
      btn.style.backgroundColor = "rgb(255 161 109)";
      btn.style.boxShadow = "";
    }
    if (attemptedQuestionArray[parseInt(btn.id - 1)]) {
      // btn.style.backgroundColor = "#bafba9";
      btn.style.backgroundColor = "rgb(0 211 255)";
      btn.style.boxShadow = "";
    }
    if (currentSlideNum == btn.id) {
      btn.style.backgroundColor = "#bfeeff";
      btn.style.boxShadow = "inset 0px 0px 0px 3px rgb(0, 23, 128)";
    }
  });
}

listButtonColorUpdate();

listButtons.forEach((btn) => {
  btn.addEventListener("click", (e) => {
    disableOption();
    currentSlideNum = e.target.id;
    visitedQuestionArray[parseInt(e.target.id) - 1] = 1;
    scrollToTop();
  });
});

function totalScore() {
  let score = 0;
  for (let i = 0; i < data.questions.length; i++) {
    if (attemptedAnswerArray[i] != "no") {
      if (attemptedAnswerArray[i] === data.questions[i].ans[0]) {
        score += 1;
        var Status = scorm.data.get('cmi.core.lesson_status')
        if (Status === "incomplete") {
          scorm.set("cmi.core.score.raw", score);
        }
      }
    }
  }
  scorm.set("cmi.core.lesson_status", "completed");
  return score;
}

function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'  // Optional: makes the scroll smooth
  });
}