// Product Animation - Desktop and Mobile
(function() {
  "use strict";

  const items = document.querySelectorAll('.product-item');
  const total = items.length;
  let currentIndex = 0;
  let intervalId = null;
  const displayDuration = 3000; // 3 seconds per image

  function showItem(index) {
    // Hide all items
    items.forEach(el => {
      el.classList.remove('active', 'floating');
      el.style.opacity = '0';
      el.style.transform = 'scale(0.8) translateY(-100px)';
    });

    // Show current item
    const el = items[index];
    el.style.transition = 'opacity 0.8s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1)';
    void el.offsetWidth; // force reflow
    el.classList.add('active');
    el.style.opacity = '1';
    el.style.transform = 'scale(1) translateY(0px)';
    
    // Add floating animation
    setTimeout(() => {
      el.classList.add('floating');
    }, 800);
  }

  function nextItem() {
    currentIndex = (currentIndex + 1) % total;
    showItem(currentIndex);
  }

  function startCarousel() {
    if (intervalId) clearInterval(intervalId);
    showItem(0);
    currentIndex = 0;
    intervalId = setInterval(nextItem, displayDuration);
  }

  function stopCarousel() {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
  }

  function init() {
    if (total === 0) return;
    
    // Initialize all items as hidden
    items.forEach(el => {
      el.style.transition = 'opacity 0.8s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1)';
      el.style.opacity = '0';
      el.style.transform = 'scale(0.8) translateY(-100px)';
      el.style.pointerEvents = 'none';
    });

    startCarousel();
    
    // Pause on hover/touch
    const stage = document.getElementById('singleImageContainer');
    if (stage) {
      stage.addEventListener('mouseenter', stopCarousel);
      stage.addEventListener('mouseleave', startCarousel);
      stage.addEventListener('touchstart', stopCarousel, { passive: true });
      stage.addEventListener('touchend', startCarousel, { passive: true });
    }
    
    // Pause when tab is hidden
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        stopCarousel();
      } else {
        startCarousel();
      }
    });
  }

  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();