(function ($) {
  "use strict";

  $(document).ready(function () {
    var $modal = $("#quicker-deactivation-modal");
    var deactivateUrl = "";

    // Intercept the deactivate link click for this plugin
    $(
      'tr[data-slug="' +
        quicker_deactivation.slug +
        '"] .deactivate a, tr[data-plugin="' +
        quicker_deactivation.slug +
        '/quicker.php"] .deactivate a'
    ).on("click", function (e) {
      e.preventDefault();
      deactivateUrl = $(this).attr("href");
      $modal.fadeIn(200);
    });

    // Close modal on overlay click
    $modal.find(".quicker-deactivation-modal-overlay").on("click", function () {
      $modal.fadeOut(200);
    });

    // Show/hide detail input based on selected reason
    $modal
      .find('input[name="quicker_deactivation_reason"]')
      .on("change", function () {
        // Hide all detail inputs
        $modal.find(".quicker-deactivation-detail").slideUp(150);

        // Show detail input for the selected reason if it has one
        var $detail = $(this)
          .closest("li")
          .find(".quicker-deactivation-detail");
        if ($detail.length) {
          $detail.slideDown(150).focus();
        }

        // Enable submit button
        $modal.find(".quicker-deactivation-submit").prop("disabled", false);
      });

    // Skip & Deactivate — go straight to deactivation
    $modal.find(".quicker-deactivation-skip").on("click", function () {
      window.location.href = deactivateUrl;
    });

    // Submit & Deactivate — send feedback then deactivate
    $modal.find(".quicker-deactivation-submit").on("click", function () {
      var $btn = $(this);
      var reason = $modal
        .find('input[name="quicker_deactivation_reason"]:checked')
        .val();
      var detail = $modal
        .find(
          'input[name="quicker_deactivation_reason"]:checked'
        )
        .closest("li")
        .find(".quicker-deactivation-detail")
        .val();

      if (!reason) {
        window.location.href = deactivateUrl;
        return;
      }

      $btn.text("Submitting...").prop("disabled", true);

      $.ajax({
        url: quicker_deactivation.ajax_url,
        type: "POST",
        data: {
          action: "quicker_deactivation_feedback",
          nonce: quicker_deactivation.nonce,
          reason: reason,
          detail: detail || "",
        },
        complete: function () {
          window.location.href = deactivateUrl;
        },
      });
    });
  });
})(jQuery);
