document.addEventListener("DOMContentLoaded", function () {
  // ========================================
  // SORT PRODUCTS
  // ========================================

  const sortSelect = document.querySelector("#productSort");

  if (sortSelect) {
    sortSelect.addEventListener("change", function () {
      const url = new URL(window.location.href);

      url.searchParams.set("sort", this.value);

      url.searchParams.set("page", "1");

      window.location.href = url.toString();
    });
  }

  // ========================================
  // PRODUCT IMAGE GALLERY
  // ========================================

  const mainImage = document.querySelector("#mainProductImage");

  const thumbnails = document.querySelectorAll(".product-thumbnail");

  if (mainImage && thumbnails.length) {
    thumbnails.forEach(function (thumbnail) {
      thumbnail.addEventListener("click", function () {
        const image = this.dataset.image;

        if (!image) {
          return;
        }

        mainImage.src = image;

        thumbnails.forEach(function (item) {
          item.classList.remove("active");
        });

        this.classList.add("active");
      });
    });
  }
});
