(function () {
  function updateState(input) {
    const wrap = input.closest(".js-quantity-increment");
    if (!wrap) return;

    const btnDown = wrap.querySelector(".increment-down");
    const btnUp   = wrap.querySelector(".increment-up");

    const min = +input.min || 0;
    const max = +input.max || 999999;
    const val = +input.value || 0;

    // DOWN button state
    if (btnDown) {
      const disableDown = val <= min;
      btnDown.disabled = disableDown;
    }

    // UP button state
    if (btnUp) {
      const disableUp = val >= max;
      btnUp.disabled = disableUp;
    }
  }

  document.addEventListener("DOMContentLoaded", () => {
    // Init
    document.querySelectorAll('.js-quantity-increment input[type="number"]').forEach(updateState);

    document.body.addEventListener("click", (e) => {
      const btn = e.target.closest(".increment-up, .increment-down");
      if (!btn) return;

      const wrap = btn.closest(".js-quantity-increment");
      if (!wrap) return;

      const input = wrap.querySelector('input[type="number"]');
      if (!input) return;

      const min = +input.min || 0;
      const max = +input.max || 999999;
      const step = +input.step || 1;
      let val = +input.value || 0;

      // Direction
      val += btn.classList.contains("increment-up") ? step : -step;

      // Limit
      if (val < min) val = min;
      if (val > max) val = max;

      input.value = val;
      updateState(input);

      input.dispatchEvent(new Event("change", { bubbles: true }));
    });

    document.body.addEventListener("change", (e) => {
      if (!e.target.matches('.js-quantity-increment input[type="number"]')) return;

      const input = e.target;
      const min = +input.min || 1;

      if (input.value === "") input.value = min;

      updateState(input);
    });
  });
})();
