// ----------------------------------------------------
// Update cart quantiy total icon badge
// ----------------------------------------------------
// This get all quantity inputs and update the total quantity badge
function kubelioUpdateCartQuantity() {
  const quantityInputs = document.querySelectorAll("table.cart input.qty");
  let total = 0;

  quantityInputs.forEach((input) => {
    const value = parseInt(input.value, 10);
    if (!isNaN(value)) {
      total += value;
    }
  });

  // Update all cart badges
  const cartBadges = document.querySelectorAll(".rt_cart_info_count");
  cartBadges.forEach((badge) => {
    badge.textContent = total;
  });
}
jQuery(document.body).on("updated_cart_totals", kubelioUpdateCartQuantity);
jQuery(document.body).on("removed_from_cart", kubelioUpdateCartQuantity);

// ----------------------------------------------------
// Update cart on quantity change without button click
// ----------------------------------------------------
document.addEventListener('DOMContentLoaded', function () {

  const cartQuantityAutoUpdate = document.querySelector(".has-cart-quantity-auto-update");

  if (cartQuantityAutoUpdate === null) {
    return;
  }

  cartQuantityAutoUpdate.addEventListener('input', handleEvent, false);
  cartQuantityAutoUpdate.addEventListener('change', handleEvent, false);

  function handleEvent(event) {
    if (event.target && event.target.matches('form.woocommerce-cart-form input.qty')) {
      const input = event.target;
      const minValue = parseInt(input.getAttribute('min') || '1');
      const maxValue = parseInt(input.getAttribute('max'));
      const currentValue = parseInt(input.value) || 0;

      // Skip update if the input is empty, below minimum (e.g. still typing), or exceeds maximum.
      // Note: currentValue equal to minValue must still trigger (min can be 0, meaning "remove item").
      if (input.value === '' || currentValue < minValue || currentValue >= maxValue) {
        return;
      }

      var updateBtn = document.querySelector('button[name="update_cart"]');
      if (updateBtn) {
        updateBtn.disabled = false;
        updateBtn.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
      }
    }
  }
});
