(function ($) {
  var $modal = $("#minimalblog-support-modal");
  var $dialog = $modal.find(".minimalblog-support-modal__dialog");
  var $form = $("#minimalblog-support-form");
  var $status = $("#minimalblog-support-status");
  var $openButtons = $(".minimalblog-open-support");
  var $submitButton = $("#minimalblog-support-submit");
  var isSubmitting = false;
  var lastActiveElement = null;

  function getFocusableElements() {
    return $dialog.find(
      'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'
    );
  }

  function setBusyState(isBusy) {
    isSubmitting = isBusy;
    $submitButton.prop("disabled", isBusy).toggleClass("is-busy", isBusy);
    $submitButton.attr("aria-busy", isBusy ? "true" : "false");
  }

  function openModal() {
    if (!$modal.length) {
      return;
    }
    lastActiveElement = document.activeElement;
    $modal.addClass("is-open").attr("aria-hidden", "false");
    setTimeout(function () {
      var $focusable = getFocusableElements();
      if ($focusable.length) {
        $focusable.first().trigger("focus");
      } else {
        $dialog.trigger("focus");
      }
    }, 10);
  }

  function closeModal() {
    if (!$modal.length) {
      return;
    }
    $modal.removeClass("is-open").attr("aria-hidden", "true");
    $status.removeClass("is-error is-success").text("");
    setBusyState(false);
    $form[0].reset();
    if (lastActiveElement && typeof lastActiveElement.focus === "function") {
      lastActiveElement.focus();
    } else {
      $openButtons.first().trigger("focus");
    }
  }

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

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

  $(document).on("submit", "#minimalblog-support-form", function (e) {
    e.preventDefault();
    if (isSubmitting) {
      return;
    }

    $status.removeClass("is-error is-success").text("");
    setBusyState(true);

    var payload = {
      action: "minimalblog_support_send",
      nonce: minimalblogSupport.nonce,
      name: $("#minimalblog-support-name").val(),
      email: $("#minimalblog-support-email").val(),
      subject: $("#minimalblog-support-subject").val(),
      message: $("#minimalblog-support-message").val(),
    };

    $status.text(minimalblogSupport.sendingText || "Sending...");

    $.post(minimalblogSupport.ajaxUrl, payload)
      .done(function (response) {
        if (response && response.success) {
          $status.addClass("is-success").text(response.data.message);
          setTimeout(function () {
            closeModal();
          }, 2500);
        } else if (response && response.data && response.data.message) {
          $status.addClass("is-error").text(response.data.message);
        } else {
          $status
            .addClass("is-error")
            .text(minimalblogSupport.failedText || "Failed to send. Please try again.");
        }
      })
      .fail(function (xhr) {
        var message =
          (xhr.responseJSON &&
            xhr.responseJSON.data &&
            xhr.responseJSON.data.message) ||
          minimalblogSupport.failedText ||
          "Failed to send. Please try again.";
        $status.addClass("is-error").text(message);
      })
      .always(function () {
        setBusyState(false);
      });
  });

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

    if (event.key === "Escape") {
      event.preventDefault();
      closeModal();
      return;
    }

    if (event.key !== "Tab") {
      return;
    }

    var $focusable = getFocusableElements();
    if (!$focusable.length) {
      return;
    }

    var first = $focusable[0];
    var last = $focusable[$focusable.length - 1];

    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  });
})(jQuery);
