// --- Carousel State ---
let allProducts = [];
let selectedProducts = [];
let currentIndex = 0;

// --- Helpers ---
const getProductId = (product) => {
  return `${product.skuID}-${product.catNumber}-${product.productNumber}`;
};

// --- Render the three visible items ---
const renderCarousel = () => {
  const productList = document.getElementById("product-list");
  productList.innerHTML = "";

  if (selectedProducts.length === 0) return;

  // Calculate indexes for left, center, right
  const leftIndex = (currentIndex - 1 + selectedProducts.length) % selectedProducts.length;
  const centerIndex = currentIndex;
  const rightIndex = (currentIndex + 1) % selectedProducts.length;

  const visibleIndexes = [leftIndex, centerIndex, rightIndex];

  visibleIndexes.forEach((idx, position) => {
    const product = selectedProducts[idx];
    const productId = getProductId(product);

    const card = document.createElement("div");
    card.className = "product-card";
    if (position === 1) card.classList.add("is-centered");

    card.dataset.productId = productId;
    card.innerHTML = `
      <img src="../images/_s-thumbs/${product.category}/${product.imageFile}" alt="${product.altText}">
      <h3>${product.productName}</h3>
      <p class="description">${position === 1 ? product.longDescription : product.shortDescription}</p>
      <p>$${product.price}</p>
      <button class="add-to-cart-btn" data-product-id="${productId}">Add to Cart</button>
    `;

    // Event listeners
    card.querySelector('.add-to-cart-btn')
      .addEventListener('click', () => addToCart(productId, allProducts));

    card.addEventListener('click', (event) => {
      event.preventDefault();
      event.stopPropagation();

      if (position === 0) prevProduct();   // left → move backward
      if (position === 2) nextProduct();   // right → move forward
    });

    productList.appendChild(card);
  });
};

// --- Navigation ---
const nextProduct = () => {
  currentIndex = (currentIndex + 1) % selectedProducts.length;
  renderCarousel();
};

const prevProduct = () => {
  currentIndex = (currentIndex - 1 + selectedProducts.length) % selectedProducts.length;
  renderCarousel();
};

// --- Category Update ---
const updateProductList = (category) => {
  const productList = document.getElementById("product-list");
  if (!productList) return console.error("Element with ID 'product-list' not found.");

  // Remove active class from all buttons
  document.querySelectorAll(".categories ul li").forEach(li => {
    li.classList.remove('active');
  });

  // Add active class to the button for the current category
  document.querySelectorAll(".cat-btn").forEach(button => {
    const url = new URL(button.href);
    const btnCategory = url.searchParams.get('category');
    if (btnCategory === category) {
      button.parentElement.classList.add('active');
    }
  });

  selectedProducts = allProducts.filter(product => product.category === category);
  currentIndex = 0;

  if (selectedProducts.length === 0) {
    console.error(`No products found for category: ${category}`);
    productList.innerHTML = "";
    return;
  }

  renderCarousel();
};

// --- Cart ---
const addToCart = (productId, products) => {
  const product = products.find(p => getProductId(p) === productId);
  if (!product) return;

  let cart = JSON.parse(sessionStorage.getItem('cart')) || [];
  const existing = cart.find(item => getProductId(item) === productId);

  if (existing) {
    existing.quantity++;
  } else {
    cart.push({ ...product, quantity: 1 });
  }

  sessionStorage.setItem('cart', JSON.stringify(cart));
  alert(`${product.productName} has been added to your cart!`);
};

// --- Init ---
document.addEventListener('DOMContentLoaded', () => {
  fetch("../data/inventory.json")
    .then(r => r.json())
    .then(products => {
      allProducts = products;

      const scrollLeftButton = document.getElementById('scroll-left');
      const scrollRightButton = document.getElementById('scroll-right');
      const categoryButtons = document.querySelectorAll(".cat-btn");

      scrollLeftButton.addEventListener('click', prevProduct);
      scrollRightButton.addEventListener('click', nextProduct);

      categoryButtons.forEach(button => {
        button.addEventListener('click', (event) => {
          event.preventDefault();
          const url = new URL(button.href);
          const category = url.searchParams.get('category');
          updateProductList(category);
        });
      });

      const currentUrl = new URL(window.location.href);
      const defaultCategory = currentUrl.searchParams.get('category') || 'trees';
      updateProductList(defaultCategory);
    })
    .catch(err => console.error('Problem fetching products:', err));
});