document.addEventListener("DOMContentLoaded", function () {
  const quantityControls = document.querySelectorAll(".quantity-control");

  quantityControls.forEach(function (control) {
    const minus = control.querySelector(".quantity-minus");

    const plus = control.querySelector(".quantity-plus");

    const input = control.querySelector('input[type="number"]');

    if (!minus || !plus || !input) {
      return;
    }

    minus.addEventListener("click", function () {
      const min = parseInt(input.min || "1", 10);

      let value = parseInt(input.value || "1", 10);

      value = Math.max(min, value - 1);

      input.value = value;
    });

    plus.addEventListener("click", function () {
      const max = parseInt(input.max || "999", 10);

      let value = parseInt(input.value || "1", 10);

      value = Math.min(max, value + 1);

      input.value = value;
    });

    input.addEventListener("change", function () {
      const min = parseInt(this.min || "1", 10);

      const max = parseInt(this.max || "999", 10);

      let value = parseInt(this.value || "1", 10);

      if (value < min) {
        value = min;
      }

      if (value > max) {
        value = max;
      }

      this.value = value;
    });
  });
});
