(function ($) {
  "use strict";

  var $modal = $("#falselogics-support-modal");
  var $dialog = $modal.find(".falselogics-support-modal__dialog");
  var $form = $("#falselogics-support-form");
  var $status = $("#falselogics-support-status");
  var $submitButton = $("#falselogics-support-submit");
  var originalButtonText = $submitButton.text();

  function lockScroll() {
    $("body").addClass("falselogics-support-no-scroll");
  }

  function unlockScroll() {
    $("body").removeClass("falselogics-support-no-scroll");
  }

  function openModal() {
    if (!$modal.length) {
      return;
    }
    $modal.addClass("is-open").attr("aria-hidden", "false");
    lockScroll();
    setTimeout(function () {
      $dialog.trigger("focus");
    }, 20);
  }

  function closeModal() {
    if (!$modal.length) {
      return;
    }
    $modal.removeClass("is-open").attr("aria-hidden", "true");
    unlockScroll();
  }

  function setStatus(message, isError) {
    $status
      .text(message)
      .removeClass("is-error is-success")
      .addClass(isError ? "is-error" : "is-success");
  }

  $(document).on("click", ".falselogics-open-support", function () {
    openModal();
  });

  $(document).on("click", "[data-falselogics-support-close]", function () {
    closeModal();
  });

  $(document).on("submit", "#falselogics-support-form", function (e) {
    e.preventDefault();

    if (typeof falselogicsSupport === "undefined") {
      setStatus("Support config missing.", true);
      return;
    }

    $submitButton.prop("disabled", true).addClass("is-busy");
    $submitButton.text(falselogicsSupport.sendingText || "Sending...");
    $status.text("").removeClass("is-error is-success");

    $.post(falselogicsSupport.ajaxUrl, {
      action: "falselogics_support_send",
      nonce: falselogicsSupport.nonce,
      name: $("#falselogics-support-name").val(),
      email: $("#falselogics-support-email").val(),
      subject: $("#falselogics-support-subject").val(),
      message: $("#falselogics-support-message").val(),
    })
      .done(function (response) {
        if (response && response.success) {
          setStatus(response.data.message || "Message sent successfully.", false);
          $form.trigger("reset");
          return;
        }
        setStatus(
          (response && response.data && response.data.message) ||
            falselogicsSupport.failedText ||
            "Failed to send. Please try again.",
          true
        );
      })
      .fail(function () {
        setStatus(falselogicsSupport.failedText || "Failed to send. Please try again.", true);
      })
      .always(function () {
        $submitButton.prop("disabled", false).removeClass("is-busy");
        $submitButton.text(originalButtonText);
      });
  });

  $(document).on("keydown", function (e) {
    if (!$modal.hasClass("is-open")) {
      return;
    }

    if (e.key === "Escape") {
      closeModal();
    }
  });
})(jQuery);
