document.addEventListener('DOMContentLoaded', function() {
  const productGrid = document.querySelector('.product-grid');
  const productCards = productGrid.querySelectorAll('.product-card');
  const prevButton = document.querySelector('.nav-button.prev');
  const nextButton = document.querySelector('.nav-button.next');

  let currentIndex = 0;
  let cardsPerView = getCardsPerView();

  function getCardsPerView() {
    const style = getComputedStyle(document.documentElement);
    return parseInt(style.getPropertyValue('--cards-per-view'));
  }

  function updateSliderPosition() {
    const translateX = -currentIndex * (100 / cardsPerView);
    productGrid.style.transform = `translateX(${translateX}%)`;
  }

  function updateNavigation() {
    prevButton.disabled = currentIndex === 0;
    nextButton.disabled = currentIndex >= productCards.length - cardsPerView;
  }

  function goToSlide(index) {
    currentIndex = Math.max(0, Math.min(index, productCards.length - cardsPerView));
    updateSliderPosition();
    updateNavigation();
  }

  function handleResize() {
    const newCardsPerView = getCardsPerView();
    if (newCardsPerView !== cardsPerView) {
      cardsPerView = newCardsPerView;
      goToSlide(currentIndex);
    }
  }

  prevButton.addEventListener('click', () => goToSlide(currentIndex - 1));
  nextButton.addEventListener('click', () => goToSlide(currentIndex + 1));

  window.addEventListener('resize', handleResize);

  // Initial setup
  updateNavigation();
});