jQuery(document).ready(function ($) {
  const tickSVG = `
  <svg class="svg-inline--fa fa-check fa-w-16 fa-lg mt-2 mb-2" style="width:20px;height:20px" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="check" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" color="#56cc9d">
      <path fill="currentColor" d="M173.898 439.404l-166.4-166.4c-12.497-12.497-12.497-32.758 0-45.255l45.255-45.255c12.497-12.497 32.758-12.497 45.255 0L192 312.69l264.092-264.092c12.497-12.497 32.758-12.497 45.255 0l45.255 45.255c12.497 12.497 12.497 32.758 0 45.255l-341.347 341.347c-12.497 12.497-32.758 12.497-45.255 0z"></path>
  </svg>
`;

  const xSVG = `
  <svg class="svg-inline--fa fa-times fa-w-10 fa-lg mt-2 mb-2" style="width:20px;height:20px" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="times" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512" color="rgb(255, 99, 71)">
      <path fill="currentColor" d="M310.6 361.4c12.5-12.5 12.5-32.8 0-45.3L233.4 256l77.2-77.1c12.5-12.5 12.5-32.8 0-45.3l-22.6-22.6c-12.5-12.5-32.8-12.5-45.3 0L160 188.7 82.8 111.6c-12.5-12.5-32.8-12.5-45.3 0L15 134.2c-12.5 12.5-12.5 32.8 0 45.3L92.2 256 15 333.1c-12.5 12.5-12.5 32.8 0 45.3l22.6 22.6c12.5 12.5 32.8 12.5 45.3 0L160 323.3l77.2 77.1c12.5 12.5 32.8 12.5 45.3 0l22.6-22.6z"></path>
  </svg>
`;

  $("#restart-quiz").click(function () {
    localStorage.setItem("correct", 0);
    location.reload();
  });

  function getIsExamMode() {
    try {
      const examModeInput = $("#examModeHiddenInput");

      if (examModeInput) {
        return examModeInput.val() === "true";
      }
    } catch (error) {
      console.error("Error getting exam mode", error);
    }
    return false;
  }

  $("#btn-next").click(function () {
    $("#btn-next").addClass("disabled");
    $('#button-next-text').text('Loading your next question');
    $("#loading-spinner").removeClass("hide-content");
    $('#spinner-right').addClass("hide-content");
  });

  $(".complete-quiz").click(function () {
    let correct = localStorage.getItem("correct");
    let count = parseInt($("#count").val());

    $("#attained-text").text("You have completed " + correct + " / " + count);

    var modal = new bootstrap.Modal(document.getElementById("staticBackdrop"));
    modal.show();
  });

  $(".question-row").click(function (event) {
    if ($(this).hasClass("disabled")) {
      return;
    }

    const isExamMode = getIsExamMode();
    const isMultipleChoiceMode = !isExamMode;

    let selection = event.target.id
      .replace("radio-row-", "")
      .replace("radio-col2-", "")
      .replace("radio-svg-", "")
      .replace("radio-path-", "")
      .replace("radio-col10-", "")
      .replace("radio-p-", "");
    let choice = parseInt(selection);

    let answer = parseInt($("#answer").val());
    

    if (choice === answer) {
      let correct = localStorage.getItem("correct");

      if (correct == null || correct == undefined || correct.length < 1) {
        correct = 0;
      }

      correct = parseInt(correct) + 1;

      var hasShownModal = localStorage.getItem("@EmailModalShown");

      if (correct == 5 && !hasShownModal) {
        localStorage.setItem("@EmailModalShown", new Date().getTime());
        $("#emailModal").modal("show");
      }

      localStorage.setItem("correct", correct);

      if (isMultipleChoiceMode) {
        $("#radio-row-" + answer).addClass("animate__animated animate__tada");
        $("#radio-svg-" + choice).replaceWith(tickSVG);
      }
    } else {
      if (isMultipleChoiceMode) {
        $("#radio-row-" + selection).addClass(
          "animate__animated animate__headShake"
        );
        $("#radio-svg-" + choice).replaceWith(xSVG);
        $("#explanation-div").addClass("animate__animated animate__flash");
      }
    }

    if (isMultipleChoiceMode) {
      $("#radio-row-" + answer).removeClass("default-question-row");

      $(".default-question-row").css({
        "border-color": "#FF6347",
        "background-color": "rgba(243, 166, 131, 0.3)",
      });
      $("#radio-row-" + answer).addClass("correct-question-row");

      $("#explanation-div").removeClass("explanation-hide");
    } else {
      $("#radio-row-" + choice).addClass("exam-mode-selected-answer-row ");
    }

    for (let i = 0; i <= 10; i++) {
      $(`#radio-row-${i}`).removeClass("question-row");
      $(`#radio-row-${i}`).addClass("disabled");
    }

    $(".question-row").addClass("disabled");
    $(".question-row").off("click");

    const selectedQuestionId = $("#selectedQuestionId").val();
    $("#loading-spinner").removeClass("hide-content");
    $('#spinner-right').addClass("hide-content");
    $('#button-next-text').text('Saving your selection');


    $.ajax({
      type: "POST",
      url: "/answer-question",
      data: {
        questionId: selectedQuestionId,
        selectedAnswer: parseInt(choice)
      },
      success: function (response) {
        $("#btn-next").removeClass("disabled");
        $("#loading-spinner").addClass("hide-content");
        $('#spinner-right').removeClass("hide-content");
        $('#button-next-text').text('Next');
      },
      error: function (err) {
        console.error("Error submitting report:", err);
      },
    });

    // get question id

    
  });

  $("#report-question-explanation").on("input", function () {
    var explanation = $(this).val();
    if (explanation.trim().length > 5) {
      $("#report-question-button").prop("disabled", false);
    } else {
      $("#report-question-button").prop("disabled", true);
    }
  });

  function thumbsUp() {
    var questionId = $("#report-question-id").val();

    $.ajax({
      type: "POST",
      url: "/thumbs-up",
      data: {
        questionId: questionId,
      },
      success: function (response) {
        Toastify({
          text: "🥰 Thank you",
          duration: 2000,
          close: true,
          gravity: "bottom",
          position: "center",
        }).showToast();
      },
      error: function (err) {
        console.error("Error submitting report:", err);
      },
    });
  }

  function thumbsDown() {
    //reportQuestion("👎🏽 Thumbs Down.");
    Toastify({
      text: "Thank you for reporting this question. Our team has been notified",
      duration: 8000,
      close: true,
      gravity: "top",
      position: "center",
    }).showToast();
  }

  function reportQuestion(explanation) {
    var questionId = $("#report-question-id").val();

    $.ajax({
      type: "POST",
      url: "/reportquestion",
      data: {
        questionId: questionId,
        explanation: explanation,
      },
      success: function (response) {
        $("#report-question-explanation").val("");
        $("#reportModal").modal("hide");
        $("#report-question-button").prop("disabled", true);
        Toastify({
          text: "Thank you for reporting this question. Our team has been notified",
          duration: 8000,
          close: true,
          gravity: "top",
          position: "center",
        }).showToast();
      },
      error: function (err) {
        console.error("Error submitting report:", err);
        $("#reportModal").modal("hide");
      },
    });
  }

  $("#report-question-button").click(function () {
    var explanation = $("#report-question-explanation").val();
    reportQuestion(explanation);
  });

  $("#thumbs-up").click(function () {
    thumbsUp();
  });

  function report() {
    var email = $("#report-problem-email").val().trim();
    var explanation = $("#report-problem-explanation").val().trim();

    // Gather client metrics

    var browserInfo = navigator.userAgent;
    var platform = navigator.platform;
    var language = navigator.language;
    var resolution = window.screen.width + "x" + window.screen.height;
    var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

    // Combine the metrics with the explanation text
    var fullExplanation =
      explanation +
      "\n\n---\n" +
      "Browser: " +
      browserInfo +
      "\n" +
      "Platform: " +
      platform +
      "\n" +
      "Screen Resolution: " +
      resolution +
      "\n" +
      "Language: " +
      language +
      "\n" +
      "Timezone: " +
      timeZone;

    // Validate the fields
    if (email && explanation) {
      $.ajax({
        type: "POST",
        url: "/report-a-problem",
        data: { email: email, explanation: fullExplanation },
        success: function (response) {
          $("#report-problem-explanation").val("");
          $("#report-problem-email").val("");
          $("#reportProblem").modal("hide");
          $("#report-problem-button").prop("disabled", true);
          Toastify({
            text: "Thank you for reporting this problem. Our team has been notified",
            duration: 8000,
            close: true,
            gravity: "top",
            position: "center",
          }).showToast();
        },
        error: function (err) {
          console.error("Error submitting report:", err);
          $("#reportModal").modal("hide");
        },
      });
    } else {
      console.log("Form is not valid.");
    }
  }

  $("#report-problem-email, #report-problem-explanation").on(
    "input",
    function () {
      var email = $("#report-problem-email").val().trim();
      var explanation = $("#report-problem-explanation").val().trim();
      // Simple regex for basic email validation
      var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      if (email && explanation && emailRegex.test(email)) {
        $("#report-problem-button").prop("disabled", false);
      } else {
        $("#report-problem-button").prop("disabled", true);
      }
    }
  );

  // Call the report function when the report button is clicked.
  $("#report-problem-button").on("click", function () {
    report();
  });

  $("#thumbs-down").click(function () {
    thumbsDown();
  });
});

function isValidEmail(email) {
  var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

document.addEventListener("DOMContentLoaded", function () {
  const ratingButton = document.getElementById("review-rating");
  const ratingValue = document.getElementById("review-rating-value");
  const nameInput = document.getElementById("review-name");
  const reviewContent = document.getElementById("review-content");
  const submitButton = document.getElementById("review-submit-button");
  const ratingOptions = document.querySelectorAll(
    "#review-rating + .dropdown-menu .dropdown-item"
  );

  // 1. Set default rating to 5 stars (using emoji)
  ratingButton.innerHTML = "⭐️⭐️⭐️⭐️⭐️";
  ratingValue.value = "5";

  // 2. When a dropdown rating is selected, update button content and hidden value
  ratingOptions.forEach((option) => {
    option.addEventListener("click", () => {
      const value = option.getAttribute("data-value");
      ratingValue.value = value;
      // Set the button content to the dropdown item's inner content (which contains the stars)
      ratingButton.innerHTML = option.innerHTML;
      checkFormValidity();
    });
  });

  // 3. Enable/disable the "Send review" button based on form validity
  function checkFormValidity() {
    // If name, review content, and rating have values, enable button
    if (
      nameInput.value.trim() !== "" &&
      reviewContent.value.trim() !== "" &&
      ratingValue.value !== ""
    ) {
      submitButton.disabled = false;
    } else {
      submitButton.disabled = true;
    }
  }

  document
    .getElementById("review-submit-button")
    .addEventListener("click", function () {
      const ratingValue = document.getElementById("review-rating-value").value;
      const name = document.getElementById("review-name").value.trim();
      const content = document.getElementById("review-content").value.trim();

      const rating = parseInt(ratingValue, 10);

      $.ajax({
        type: "POST",
        url: "/create-review",
        data: {
          rating: rating,
          name: name,
          content: content,
        },
        success: function (response) {
          $("#review-content").val("");
          $("#review-name").val("");
          $("#reviewModal").modal("hide");
          document.getElementById("review-submit-button").disabled = true;

          Toastify({
            text: "Thank you, we have received your review",
            duration: 8000,
            close: true,
            gravity: "top",
            position: "center",
          }).showToast();
        },
        error: function (err) {
          console.error("Error submitting review:", err);
          alert("An error occurred. Please try again later.");
        },
      });
    });

  // Listen for input changes in name & content
  nameInput.addEventListener("input", checkFormValidity);
  reviewContent.addEventListener("input", checkFormValidity);

  var emailInput = document.getElementById("download-guide-email-id");
  var downloadButton = document.getElementById("download-guide");

  if (emailInput && downloadButton) {
    emailInput.addEventListener("input", function () {
      var email = emailInput.value.trim();
      downloadButton.disabled = !isValidEmail(email);
    });

    emailInput.addEventListener("keydown", function (event) {
      if (event.key === "Enter") {
        // Prevent form submission if inside a form
        event.preventDefault();
        var email = emailInput.value.trim();
        if (isValidEmail(email)) {
          downloadButton.click();
        }
      }
    });

    downloadButton.addEventListener("click", function () {
      const emailAddress = emailInput.value.trim();
      console.log(emailAddress);

      $.ajax({
        type: "POST",
        url: "/email-submission",
        data: {
          email: emailAddress,
          sample: true,
        },
        success: function (response) {
          $("#email").val("");
          $("#downloadSampleModel").modal("hide");
          downloadButton.disabled = true;
          localStorage.setItem("@EmailModalShown", new Date().getTime());

          Toastify({
            text: "Thank you, we have sent you an email with the download link for the sample.",
            duration: 8000,
            close: true,
            gravity: "top",
            position: "center",
          }).showToast();
        },
        error: function (err) {
          console.error("Error submitting email:", err);
          alert("An error occurred. Please try again later.");
        },
      });
    });
  }

  var emailTextInput = document.getElementById("email");
  var saveEmailButton = document.getElementById("save-email");

  if (emailTextInput && saveEmailButton) {
    emailTextInput.addEventListener("input", function () {
      var email = emailTextInput.value.trim();
      saveEmailButton.disabled = !isValidEmail(email);
    });

    emailTextInput.addEventListener("keydown", function (event) {
      if (event.key === "Enter") {
        // Prevent form submission if inside a form
        event.preventDefault();
        var email = emailTextInput.value.trim();
        if (isValidEmail(email)) {
          saveEmailButton.click();
        }
      }
    });

    saveEmailButton.addEventListener("click", function () {
      const emailAddress = emailTextInput.value.trim();
      console.log(emailAddress);

      $.ajax({
        type: "POST",
        url: "/email-submission",
        data: {
          email: emailAddress,
        },
        success: function (response) {
          $("#email").val("");
          $("#emailModal").modal("hide");
          saveEmailButton.disabled = true;

          Toastify({
            text: "Thank you, we will send you all applicable offers",
            duration: 8000,
            close: true,
            gravity: "top",
            position: "center",
          }).showToast();
        },
        error: function (err) {
          console.error("Error submitting email:", err);
          alert("An error occurred. Please try again later.");
        },
      });
    });
  }
});
