jQuery(document).ready(function ($) {
  var openButton = document.getElementById("bc_forum_question_form");
  var modal = document.getElementById("question_modal");
  var closeButton = document.getElementsByClassName("close")[0];

  if (openButton) {
    openButton.onclick = function () {
      var isLoggedIn = openButton.getAttribute("data-logged-in") === "true";
      var loginUrl = openButton.getAttribute("data-login-url");
      if (isLoggedIn) {
        modal.style.display = "block";
      } else {
        window.location.href = loginUrl;
      }
    };
  }

  if (closeButton) {
    closeButton.onclick = function () {
      modal.style.display = "none";
    };
  }

  window.onclick = function (event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };
  function handleLikes() {
    $(".comments").on("click", function () {
      let id = this.id;
      let spinner = $("#spinner_" + id);
      let replyAnswers = $("#" + id + ".reply-answers");
      if (replyAnswers.hasClass("show")) {
        replyAnswers.removeClass("show");
      } else {
        spinner.show();
        setTimeout(function () {
          spinner.hide();
          replyAnswers.addClass("show");
        }, 500);
      }
    });

    $(".likes").on("click", function () {
      var likeContainer = $(this);
      var question_id = likeContainer.attr("id");
      var user_id = likeContainer.attr("user_id");

      $.ajax({
        type: "POST",
        url: bcforum_ajax_object.ajaxurl,
        data: {
          action: "bcforum_toggle_like",
          question_id: question_id,
          user_id: user_id,
          security: bcforum_ajax_object.nonceSecurity,
        },
        success: function (response) {
          if (response.success) {
            likeContainer
              .find(".count_likes")
              .text(response.data.likes + " likes");

            if (response.data.liked) {
              likeContainer.find(".unlike-img").hide();
              likeContainer.find(".like-img").show();
              likeContainer.addClass("liked");
            } else {
              likeContainer.find(".like-img").hide();
              likeContainer.find(".unlike-img").show();
              likeContainer.removeClass("liked");
            }
          }
        },
      });
    });

    $(".limit").each(function () {
      if ($(this).text().length > 200) {
        $(this).next("span.more").show();
      } else {
        $(this).next("span.more").hide();
      }
      $(this).data("question-content", $(this).text());
      $(this).data("limit", $(this).text().substring(0, 200));
      $(this).text($(this).data("limit"));
    });

    $("span.more").click(function () {
      var $this = $(this);
      var elP = $this.siblings("span");
      var length = elP.text().length;
      if (length == 200) {
        elP.text(elP.data("question-content"));
        $this.text("less");
      } else {
        elP.text(elP.data("limit"));
        $this.text("...");
      }
    });
  }

  var globalArray = [];

  function TextLimitMoreorLess(limit) {
    limit.each(function () {
      if (limit.text().length > 200) {
        limit.next("span.more").show();
      } else {
        limit.next("span.more").hide();
      }
      limit.data("question-content", $(this).text());
      limit.data("limit", $(this).text().substring(0, 200));
      limit.text($(this).data("limit"));
    });
    $("span.more").click(function () {
      var $this = $(this);
      var elP = $this.siblings("span");
      var length = elP.text().length;
      if (length == 200) {
        elP.text(elP.data("question-content"));
        $this.text("less");
      } else {
        elP.text(elP.data("limit"));
        $this.text("...");
      }
    });
  }

  handleLikes();

  $(".likes").each(function () {
    if ($(this).hasClass("liked")) {
      $(this).find(".unlike-img").hide();
      $(this).find(".like-img").show();
    } else {
      $(this).find(".like-img").hide();
      $(this).find(".unlike-img").show();
    }
  });

  $(document).on("click", ".comment-toggle", function (event) {
    if ($(this).parents(".answers").length) {
      $(this)
        .parents(".answers")
        .next(".author-details")
        .next(".comment-box")
        .toggle();
    } else {
      $(this)
        .parents(".single-question")
        .next(".author-datetime-details")
        .next(".comment-box")
        .toggle();
    }
  });
  // Toggle answers accordion
  $(document).on("click", ".accordion-toggle", function () {
    $(this).next(".answers-content").slideToggle();
  });
  // Hide error message when user starts typing
  $(document).on("input", "textarea[name='answer']", function () {
    var errorMessage = $(this).closest("form").find(".error-message");
    if ($.trim($(this).val()) !== "") {
      errorMessage.hide();
    }
  });
  // Handle comment submission
  $(document).on("click", ".submit", function (event) {
    event.preventDefault();

    var form = $(this).closest("form");
    var textarea = form.find("textarea[name='answer']");
    var errorMessage = form.find(".error-message");
    var spinner;

    // Validate textarea
    if ($.trim(textarea.val()) === "") {
      errorMessage.show();
      return;
    } else {
      errorMessage.hide();
    }

    if ($(this).closest(".comment-form").serializeArray().length > 0) {
      spinner = $("#spinner-comment");
      var formData = $(this).closest(".comment-form").serializeArray();
    } else {
      spinner = form
        .parents(".comment-box")
        .parents(".answer")
        .find("#spinner-reply");
      var formData = $(this).closest(".reply-form").serializeArray();
    }

    var data = { parent: "0" };
    $(formData).each(function (index, obj) {
      if (obj.name == "parent_answer_id") {
        data["parent"] = obj.value;
      } else {
        data[obj.name] = obj.value;
      }
    });

    var questionId = data["question_id"]; // Get the question ID
    var that = this;
    // Show the spinner
    spinner.show();

    $.ajax({
      type: "POST",
      url: bcforum_ajax_object.ajaxurl,
      data: {
        action: "bcforum_submit_comment",
        data: data,
        security: bcforum_ajax_object.nonceSecurity,
      },
      success: function (response) {
        var newCommentHTML = response.answer_html;
        var updatedAnswersCount = response.answers_count;

        var tempElement = $("<div>").html(newCommentHTML);
        // Extract the level value
        var answer_id = tempElement
          .find('input[name="parent_answer_id"]')
          .val();

        if (globalArray.indexOf(answer_id) === -1) {
          globalArray.push(answer_id);
        }

        var parentAnswerItem = $(that).parent(".comment-form");

        if (parentAnswerItem.length > 0) {
          var level1Div = $(that)
            .parent(".comment-form")
            .parent(".comment-box")
            .parent(".main-question");

          if (level1Div.children(".load-more-section").length > 0) {
            level1Div.children(".load-more-section").before(newCommentHTML);
          } else {
            level1Div.append(newCommentHTML);
            var mainQuestionReply = level1Div.find(".limit").last();
            if (mainQuestionReply) {
              TextLimitMoreorLess(mainQuestionReply);
            }
          }
        } else {
          $(that)
            .parent(".reply-form")
            .parent(".comment-box")
            .parent(".answer")
            .parent(".answer-item")
            .parent(".answer-list")
            .after(newCommentHTML);
          var answersReply = $(that)
            .parent(".reply-form")
            .parent(".comment-box")
            .parent(".answer")
            .parent(".answer-item")
            .parent(".answer-list")
            .next(".answer-list")
            .find(".limit");
          if (answersReply) {
            TextLimitMoreorLess(answersReply);
          }
        }
        $(that).closest("form").find("input[type=text], textarea").val("");
        $(".comment-box").hide();

        // Update the answers count for the specific question
        $("#count_answers_" + questionId).text(
          updatedAnswersCount + " comments"
        );
        spinner.hide();
      },
      error: function (xhr, status, error) {
        console.error(xhr.responseText);
        spinner.hide();
      },
    });
  });

  // Add event handling for the Load More button
  $(".more-btn .load-more-btn").click(function (event) {
    const questionId = $(this).attr("data-question-id");
    var page = parseInt($(this).attr("data-page"));
    var that = this;

    $.ajax({
      type: "POST",
      url: bcforum_ajax_object.ajaxurl,
      data: {
        action: "bcforum_loadmore_answers",
        question_id: questionId,
        exclude_ids: globalArray,
        page: page + 1,
        security: bcforum_ajax_object.nonceSecurity,
      },
      success: function (data) {
        if (data.trim() === "") {
          $(that).hide();
        } else {
          $(that).attr("data-page", page + 1);
          $(".more-btn")
            .parent(".load-more-section")
            .find(".load-more-answers")
            .append(data);

          var limit = $(".load-more-answers .limit");
          if (limit) {
            TextLimitMoreorLess(limit);
          }
        }
      },
      error: function (errorThrown) {
        console.log(errorThrown);
      },
    });
  });

  // Hide error message when user starts typing in the question title input field
  $(document).on("input", "input[name='question_title']", function () {
    $("#question_title_error").hide();
  });

  $(document).on("click", "input[name='submit_question']", function (event) {
    event.preventDefault();

    let spinner = $("#spinner_que");
    spinner.show();

    var formData = $("#question_submission_form").serializeArray();
    var data = {};
    var isValid = true;

    // Clear any previous error messages
    $("#question_title_error").hide();
    $("#question_content_error").hide();

    // Construct data object and validate fields
    $(formData).each(function (index, obj) {
      data[obj.name] = obj.value;
      if (obj.name === "question_title" && !obj.value.trim()) {
        isValid = false;
        $("#question_title_error").show();
      } else if (obj.name === "question_content" && !obj.value.trim()) {
        isValid = false;
        $("#question_content_error").show();
      }
    });

    // If validation fails, stop form submission and hide spinner
    if (!isValid) {
      spinner.hide();
      return;
    }
    if (modal) {
      modal.style.display = "none";
    }

    // Now you can proceed with your AJAX request
    $.ajax({
      type: "POST",
      url: bcforum_ajax_object.ajaxurl,
      data: {
        action: "bcforum_save_question",
        data: data,
        security: bcforum_ajax_object.nonceSecurity,
      },
      success: function (response) {
        // var parsedResponse = response;
        fetchUpdatedQuestions(response.id);
        spinner.hide();
        // Clear the form data
        $("#question_submission_form")[0].reset();
      },
      error: function (xhr, status, error) {
        console.error(xhr.responseText);
        spinner.hide(); // Ensure spinner is hidden on error
      },
    });
  });

  function fetchUpdatedQuestions(id) {
    $.ajax({
      type: "POST",
      url: bcforum_ajax_object.ajaxurl,
      data: {
        action: "bcforum_get_questions",
        questionId: id,
        security: bcforum_ajax_object.nonceSecurity,
      },
      success: function (response) {
        // Check if the .question-list element exists
        if ($(".question-list").length === 0) {
          var questionList = $("<div class='question-list'></div>");
          $(".bc-ask-question-container").after(questionList);
        }

        $(".question-list").prepend(response);

        handleLikes();
      },
      error: function (xhr, status, error) {
        console.error(xhr.responseText);
      },
    });
  }
});
