(function ($) {
  function nonce() {
    return (window.SPG_ADMIN && SPG_ADMIN.nonce) ? SPG_ADMIN.nonce : "";
  }

  function $keyInput() {
    return $("#woocommerce_spg_crypto_manual_license_key");
  }

  function ensureButtons() {
    const $inp = $keyInput();
    if (!$inp.length) return;

    if ($("#spg_license_activate").length) return; // already injected

    const $wrap = $('<span class="spg-license-btns" style="margin-left:8px; display:inline-flex; gap:6px; vertical-align:middle;"></span>');
    const $act  = $('<button type="button" class="button button-primary" id="spg_license_activate">activate</button>');
    const $de   = $('<button type="button" class="button" id="spg_license_deactivate">deactivate</button>');

    $wrap.append($act, $de);

    // ✅ place buttons right after the input
    $inp.after($wrap);
  }

  function post(action, data) {
    return $.post(
      SPG_ADMIN.ajax_url,
      $.extend({ action: action, _wpnonce: nonce() }, data || {})
    );
  }

  // Inject buttons when settings page loads (and after WC ajax reloads sections)
  $(document).ready(ensureButtons);
  $(document).on("wc_backbone_modal_loaded updated_wc_div", ensureButtons);

  $(document).on("click", "#spg_license_activate", function (e) {
    e.preventDefault();
    const key = ($keyInput().val() || "").trim();
    if (!key) return alert("Please paste your license key first.");

    const $btn = $(this);
    $btn.prop("disabled", true).text("Activating...");

    post("spg_activate_license", { license_key: key })
      .done(function (resp) {
        if (resp && resp.success) location.reload();
        else alert(resp?.data?.message || "Activation failed.");
      })
      .fail(function (xhr) {
        alert("Activation failed.\n\n" + (xhr?.responseText || ""));
      })
      .always(function () {
        $btn.prop("disabled", false).text("activate");
      });
  });

  $(document).on("click", "#spg_license_deactivate", function (e) {
    e.preventDefault();

    const $btn = $(this);
    $btn.prop("disabled", true).text("Deactivating...");

    post("spg_deactivate_license", {})
      .done(function (resp) {
        if (resp && resp.success) location.reload();
        else alert(resp?.data?.message || "Deactivation failed.");
      })
      .fail(function (xhr) {
        alert("Deactivation failed.\n\n" + (xhr?.responseText || ""));
      })
      .always(function () {
        $btn.prop("disabled", false).text("deactivate");
      });
  });
})(jQuery);
