(function () {
  document.addEventListener('DOMContentLoaded', function () {
    var forms = document.querySelectorAll('.bwdk-bulk-verify-form');
    if (!forms || !forms.length) return;

    forms.forEach(function (form) {
      var button = form.querySelector('[data-bwdk-bulk-verify-button="1"]');
      var limitInput = form.querySelector('input[name="bwdk_bulk_verify_limit"]');
      if (!button || !limitInput) return;

      var originalText = button.textContent;

      form.addEventListener('submit', function () {
        // Normalize the value. If invalid/empty, default to 20.
        var v = parseInt(String(limitInput.value || ''), 10);
        if (!Number.isFinite(v)) v = 20;
        if (v < 1) v = 1;
        if (v > 200) v = 200;
        limitInput.value = String(v);

        // If browser validation prevents submit, don't keep loading state.
        if (typeof form.checkValidity === 'function' && !form.checkValidity()) {
          button.classList.remove('disabled');
          button.removeAttribute('aria-disabled');
          button.removeAttribute('disabled');
          button.textContent = originalText;
          return;
        }

        button.disabled = true;
        button.classList.add('disabled');
        button.setAttribute('aria-disabled', 'true');
        button.textContent = 'در حال بررسی سفارشات BWDK...';
      });
    });
  });
})();

