jQuery(document).ready(function ($) {
  $(document).on("submit", ".algo-form[data-form-id]", function (e) {
    e.preventDefault();
    e.stopPropagation();

    var $form = $(this);
    var formId = $form.data("form-id");
    var $submitButton = $form.find('button[type="submit"]');
    var $submitLabel = $submitButton.find(".algo-form__submit-label");
    var originalButtonText = $submitLabel.length
      ? $submitLabel.text()
      : $submitButton.text();
    var sendingLabel = $form.data("sending-label") || "Sending…";
    var errorGeneric = $form.data("error-generic") || "Something went wrong.";

    $submitButton.prop("disabled", true);
    if ($submitLabel.length) {
      $submitLabel.text(sendingLabel);
    } else {
      $submitButton.text(sendingLabel);
    }

    $form.find(".algo-form__message").remove();

    var formData = new FormData(this);
    formData.append("action", "algo_forms_submission");
    formData.append("nonce", algoForms.nonce);
    formData.append("form_id", formId);
    formData.set("page_url", window.location.href || "");
    formData.set("page_title", document.title || "");

    $.ajax({
      url: algoForms.ajaxurl,
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (response) {
        if (response.success) {
          $form.prepend(
            '<div class="algo-form__message algo-form__message--success">' +
              response.data +
              "</div>"
          );
          setTimeout(function () {
            $form.find(".algo-form__message--success").fadeOut("slow", function () {
              $(this).remove();
            });
          }, 5000);
          $form[0].reset();
        } else {
          $form.prepend(
            '<div class="algo-form__message algo-form__message--error">' +
              response.data +
              "</div>"
          );
          setTimeout(function () {
            $form.find(".algo-form__message--error").fadeOut("slow", function () {
              $(this).remove();
            });
          }, 5000);
        }
      },
      error: function () {
        $form.prepend(
          '<div class="algo-form__message algo-form__message--error">' +
            errorGeneric +
            "</div>"
        );
        setTimeout(function () {
          $form.find(".algo-form__message--error").fadeOut("slow", function () {
            $(this).remove();
          });
        }, 5000);
      },
      complete: function () {
        $submitButton.prop("disabled", false);
        if ($submitLabel.length) {
          $submitLabel.text(originalButtonText);
        } else {
          $submitButton.text(originalButtonText);
        }
      },
    });
  });
});
