/**
 * Theme Sliders Module
 * Optimized for WordPress with proper isolation and performance
 * @version 2.0.0
 */

// ==========================================================================
// 1. Main Sliders Controller
// ==========================================================================

const ThemeSliders = (function() {
  'use strict';
  
  // Private variables
  let swiperInstances = [];
  let productImageCache = new Map();
  let gridObserver = null;
  
  // Check if Swiper is available
  const isSwiperAvailable = () => typeof Swiper !== 'undefined';
  
  // Initialize all sliders
  const init = () => {
    if (!isSwiperAvailable()) {
      console.warn('[ThemeSliders] Swiper library not loaded');
      return;
    }
    
    initCategorySliders();
    initBrandsSlider();
    initProductsTabsSlider();
    initProductCardSliders();
  };
  
  // ==========================================================================
  // 2. Category Sliders (Categories, Small Categories)
  // ==========================================================================
  
  const initCategorySliders = () => {
    // Main categories slider
    initSwiper('.categories-slider', {
      slidesPerView: 3.3,
      spaceBetween: 20,
      breakpoints: {
        840: { slidesPerView: 3.5 },
        1280: { slidesPerView: 4 },
        1720: { slidesPerView: 5 }
      }
    }, 'categories');
    
    // Small categories slider
    initSwiper('.small-categories-slider', {
      slidesPerView: 3.5,
      spaceBetween: 15,
      navigation: false,
      breakpoints: {
        400: { slidesPerView: 4 },
        600: { slidesPerView: 5 },
        840: { slidesPerView: 7 },
        1024: { slidesPerView: 7 },
        1280: { slidesPerView: 10 },
        1720: { slidesPerView: 11 }
      }
    }, 'small-categories');
  };
  
  // ==========================================================================
  // 3. Brands Marquee Slider
  // ==========================================================================
  
  const initBrandsSlider = () => {
    initSwiper('.brands-slider', {
      slidesPerView: 3.4,
      spaceBetween: 40,
      loop: true,
      speed: 3000,
      autoplay: {
        delay: 0,
        disableOnInteraction: false,
        pauseOnMouseEnter: true,
        reverseDirection: false
      },
      breakpoints: {
        768: { slidesPerView: 5 },
        1280: { slidesPerView: 6 },
        1720: { slidesPerView: 7 }
      },
      loopAdditionalSlides: 1,
      watchSlidesProgress: true,
      breakpointsBase: 'window',
      navigation: false,
      pagination: false,
      easing: 'linear'
    }, 'brands');
  };
  
  // ==========================================================================
  // 4. Products Tabs Slider (with Thumbnails)
  // ==========================================================================
  
  const initProductsTabsSlider = () => {
    const thumbsElement = document.querySelector('.products-thumbs');
    const mainElement = document.querySelector('.products-slider');
    
    if (!thumbsElement || !mainElement) return;
    
    // Initialize thumbs slider
    const thumbsSwiper = new Swiper('.products-thumbs', {
      slidesPerView: 1,
      spaceBetween: 0,
      effect: 'fade',
      fadeEffect: { crossFade: true },
      allowTouchMove: false,
      watchSlidesProgress: true,
      speed: 400
    });
    
    // Initialize main slider with thumbs
    new Swiper('.products-slider', {
      slidesPerView: 1,
      spaceBetween: 30,
      effect: 'fade',
      fadeEffect: { crossFade: true },
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
      },
      thumbs: { swiper: thumbsSwiper }
    });
    
    swiperInstances.push(thumbsSwiper);
  };
  
  // ==========================================================================
  // 5. Product Card Sliders (Dynamic on Shop/Archive Pages)
  // ==========================================================================
  
  const initProductCardSliders = async () => {
    const cards = getUnboundProductCards();
    if (!cards.length) return;
    
    const cardsById = groupCardsByProductId(cards);
    const idsToFetch = getUncachedProductIds(cardsById);
    
    if (idsToFetch.length) {
      await fetchAndCacheProductImages(idsToFetch);
    }
    
    // Build sliders for each card
    cardsById.forEach((cardsForId, productId) => {
      const images = productImageCache.get(productId) || [];
      if (images.length >= 2) {
        cardsForId.forEach(card => buildProductCardSwiper(card, images));
      }
    });
  };
  
  // Helper: Get unbound product cards
  const getUnboundProductCards = () => {
    return Array.from(document.querySelectorAll(
      '.wc-block-product:not([data-product-swiper-bound="1"])'
    )).filter(card => card.querySelector('.baty-card'));
  };
  
  // Helper: Group cards by product ID
  const groupCardsByProductId = (cards) => {
    const cardsById = new Map();
    
    cards.forEach(card => {
      card.setAttribute('data-product-swiper-bound', '1');
      const productId = getProductIdFromCard(card);
      
      if (productId) {
        card.setAttribute('data-product-id', String(productId));
        if (!cardsById.has(productId)) cardsById.set(productId, []);
        cardsById.get(productId).push(card);
      }
    });
    
    return cardsById;
  };
  
  // Helper: Get uncached product IDs
  const getUncachedProductIds = (cardsById) => {
    return Array.from(cardsById.keys()).filter(id => !productImageCache.has(id));
  };
  
  // Helper: Fetch and cache product images
  const fetchAndCacheProductImages = async (ids) => {
    const products = await fetchProductsByIds(ids);
    
    products.forEach(product => {
      const images = normalizeProductImages(product);
      productImageCache.set(Number(product.id), images);
    });
    
    // Set empty arrays for products without images
    ids.forEach(id => {
      if (!productImageCache.has(id)) productImageCache.set(id, []);
    });
  };
  
  // Helper: Normalize product images
  const normalizeProductImages = (product) => {
    const imageList = Array.isArray(product?.images) ? product.images : [];
    
    return imageList
      .map(image => image?.src ? {
        src: image.src,
        srcset: image.srcset || '',
        sizes: image.sizes || '',
        alt: image.alt || image.name || ''
      } : null)
      .filter(Boolean);
  };
  
  // Helper: Extract product ID from card
  const getProductIdFromCard = (card) => {
    // Check data attribute
    const explicitId = parseInt(card.getAttribute('data-product-id') || '', 10);
    if (Number.isFinite(explicitId) && explicitId > 0) return explicitId;
    
    // Check post class
    const classMatch = (card.className || '').match(/(?:^|\s)post-(\d+)(?:\s|$)/);
    if (classMatch) return parseInt(classMatch[1], 10);
    
    // Check WC key attribute
    const wcKey = card.getAttribute('data-wc-key') || '';
    const keyMatch = wcKey.match(/(\d+)/);
    if (keyMatch) return parseInt(keyMatch[1], 10);
    
    // Check add to cart button
    const addToCartButton = card.querySelector('[data-product_id]');
    if (addToCartButton) {
      const buttonId = parseInt(addToCartButton.getAttribute('data-product_id') || '', 10);
      if (Number.isFinite(buttonId) && buttonId > 0) return buttonId;
    }
    
    return null;
  };
  
  // Helper: Fetch products by IDs (batched)
  const fetchProductsByIds = async (ids) => {
    const chunkSize = 20;
    const chunks = [];
    
    for (let i = 0; i < ids.length; i += chunkSize) {
      chunks.push(ids.slice(i, i + chunkSize));
    }
    
    const requests = chunks.map(async (chunk) => {
      const endpoint = `/wp-json/wc/store/products?include=${chunk.join(',')}&per_page=${chunk.length}`;
      
      try {
        const response = await fetch(endpoint);
        if (!response.ok) return [];
        const data = await response.json();
        return Array.isArray(data) ? data : [];
      } catch (error) {
        console.warn('[ThemeSliders] Failed to fetch products:', error);
        return [];
      }
    });
    
    const results = await Promise.all(requests);
    return results.flat();
  };
  
  // Helper: Build individual product card swiper
  const buildProductCardSwiper = (card, images) => {
    const batyCard = card.querySelector('.baty-card');
    const imageContainer = batyCard?.querySelector('.wc-block-components-product-image');
    const productLink = imageContainer?.querySelector('a[href]');
    
    if (!batyCard || !imageContainer || !productLink) return;
    if (imageContainer.querySelector('.wc-product-swiper')) return;
    
    const productUrl = productLink.getAttribute('href');
    if (!productUrl) return;
    
    // Create Swiper DOM elements
    const swiperRoot = createSwiperContainer(images, productUrl);
    
    // Replace product link content
    productLink.innerHTML = '';
    productLink.appendChild(swiperRoot);
    
    // Add classes
    card.classList.add('has-product-swiper');
    imageContainer.classList.add('has-product-swiper');
    
    // Initialize Swiper
    const swiper = new Swiper(swiperRoot, {
      slidesPerView: 1,
      loop: images.length > 2,
      speed: 400,
      allowTouchMove: true,
      watchOverflow: true,
      autoplay: false,
      navigation: {
        nextEl: swiperRoot.querySelector('.swiper-button-next'),
        prevEl: swiperRoot.querySelector('.swiper-button-prev')
      },
      pagination: {
        el: swiperRoot.querySelector('.swiper-pagination'),
        clickable: true
      }
    });
    
    // Add hover interactions
    attachCardHoverEvents(card, swiper);
    swiperInstances.push(swiper);
  };
  
  // Helper: Create Swiper DOM structure
  const createSwiperContainer = (images, productUrl) => {
    const swiperRoot = document.createElement('div');
    swiperRoot.className = 'wc-product-swiper swiper';
    
    const wrapper = document.createElement('div');
    wrapper.className = 'swiper-wrapper';
    
    images.forEach((image, index) => {
      const slide = document.createElement('div');
      slide.className = 'swiper-slide';
      
      const slideLink = document.createElement('a');
      slideLink.href = productUrl;
      slideLink.setAttribute('aria-label', 'View product');
      if (index > 0) slideLink.tabIndex = -1;
      
      const slideImage = document.createElement('img');
      slideImage.src = image.src;
      if (image.srcset) slideImage.srcset = image.srcset;
      if (image.sizes) slideImage.sizes = image.sizes;
      slideImage.alt = image.alt;
      slideImage.loading = index === 0 ? 'eager' : 'lazy';
      slideImage.decoding = 'async';
      
      slideLink.appendChild(slideImage);
      slide.appendChild(slideLink);
      wrapper.appendChild(slide);
    });
    
    // Create navigation elements
    const prevButton = document.createElement('button');
    prevButton.className = 'swiper-button-prev';
    prevButton.type = 'button';
    prevButton.setAttribute('aria-label', 'Previous image');
    
    const nextButton = document.createElement('button');
    nextButton.className = 'swiper-button-next';
    nextButton.type = 'button';
    nextButton.setAttribute('aria-label', 'Next image');
    
    const pagination = document.createElement('div');
    pagination.className = 'swiper-pagination';
    
    swiperRoot.appendChild(wrapper);
    swiperRoot.appendChild(prevButton);
    swiperRoot.appendChild(nextButton);
    swiperRoot.appendChild(pagination);
    
    return swiperRoot;
  };
  
  // Helper: Attach hover events to product card
  const attachCardHoverEvents = (card, swiper) => {
    let hoverActive = false;
    
    card.addEventListener('mouseenter', () => {
      if (!swiper.destroyed && swiper.slides.length > 1) {
        hoverActive = true;
        swiper.slideNext();
      }
    });
    
    card.addEventListener('mouseleave', () => {
      if (!swiper.destroyed && hoverActive) {
        hoverActive = false;
        swiper.slideTo(0);
      }
    });
  };
  
  // ==========================================================================
  // 6. Grid Observer (for dynamically loaded products)
  // ==========================================================================
  
  const observeProductGridChanges = () => {
    const grids = document.querySelectorAll(
      '.wc-block-product-template, .wp-block-woocommerce-product-template'
    );
    
    if (!grids.length) return;
    
    if (gridObserver) gridObserver.disconnect();
    
    gridObserver = new MutationObserver((mutations) => {
      const hasNewNodes = mutations.some(m => m.addedNodes.length > 0);
      if (hasNewNodes) initProductCardSliders();
    });
    
    grids.forEach(grid => {
      gridObserver.observe(grid, { childList: true, subtree: true });
    });
  };
  
  // ==========================================================================
  // 7. Generic Swiper Initializer
  // ==========================================================================
  
  const initSwiper = (selector, config, name = 'unnamed') => {
    const element = document.querySelector(selector);
    if (!element) {
      return null;
    }
    
    // Prevent duplicate initialization
    if (element.swiperInstance) return element.swiperInstance;
    
    const options = {
      grabCursor: true,
      pagination: config.pagination ?? { el: '.swiper-pagination', clickable: true },
      navigation: config.navigation ?? { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
      ...config,
      on: {
        init: function() {
        },
        ...config.on
      }
    };
    
    const swiper = new Swiper(selector, options);
    element.swiperInstance = swiper;
    swiperInstances.push(swiper);
    
    return swiper;
  };
  
  // ==========================================================================
  // 8. Cleanup Function (prevent conflicts)
  // ==========================================================================
  
  const destroy = () => {
    // Destroy all swiper instances
    swiperInstances.forEach(swiper => {
      if (swiper && !swiper.destroyed) swiper.destroy(true, true);
    });
    swiperInstances = [];
    
    // Disconnect observer
    if (gridObserver) gridObserver.disconnect();
    
    // Clear cache
    productImageCache.clear();
  };
  
  // ==========================================================================
  // 9. Public API
  // ==========================================================================
  
  return {
    init,
    destroy,
    refresh: initProductCardSliders
  };
})();

// ==========================================================================
// 10. Search Module (Isolated)
// ==========================================================================

const ThemeSearch = (function() {
  'use strict';
  
  let productNames = [];
  let searchForm = null;
  let searchDropdown = null;
  let searchInput = null;
  
  const init = () => {
    searchForm = document.querySelector('.product-search-results-content form.wp-block-search');
    searchDropdown = document.querySelector('.product-search-results-content .search-chips');
    
    if (!searchForm || !searchDropdown) return;
    
    searchInput = searchForm.querySelector('input');
    if (!searchInput) return;
    
    loadProductNames();
    attachEvents();
    renderDropdown();
  };
  
  const loadProductNames = async () => {
    try {
      const res = await fetch('/wp-json/wc/store/products?per_page=50');
      const products = await res.json();
      productNames = products.map(p => p.name);
    } catch (err) {
      console.error('[ThemeSearch] Failed to load products:', err);
    }
  };
  
  const attachEvents = () => {
    searchForm.addEventListener('submit', saveSearch);
    searchInput.addEventListener('input', handleInput);
    searchDropdown.addEventListener('click', handleDropdownClick);
  };
  
  const saveSearch = () => {
    let searches = JSON.parse(localStorage.getItem('searches') || '[]');
    const value = searchInput.value.trim();
    
    if (value && !searches.includes(value)) {
      searches.unshift(value);
      searches = searches.slice(0, 5);
      localStorage.setItem('searches', JSON.stringify(searches));
    }
  };
  
  const handleInput = () => {
    renderDropdown(searchInput.value.trim());
  };
  
  const handleDropdownClick = (e) => {
    const removeBtn = e.target.closest('.remove-tag');
    
    if (removeBtn) {
      removeSearchTerm(removeBtn.dataset.term);
      return;
    }
    
    const item = e.target.closest('.dropdown-item');
    if (item) {
      searchInput.value = item.dataset.term;
      searchForm.submit();
    }
  };
  
  const removeSearchTerm = (term) => {
    let searches = JSON.parse(localStorage.getItem('searches') || '[]');
    searches = searches.filter(t => t !== term);
    localStorage.setItem('searches', JSON.stringify(searches));
    renderDropdown(searchInput.value);
  };
  
  const renderDropdown = (query = '') => {
    const recent = JSON.parse(localStorage.getItem('searches') || '[]');
    const lowerQuery = query.toLowerCase();
    
    const matchedProducts = productNames.filter(name => 
      name.toLowerCase().includes(lowerQuery)
    );
    
    const productsToShow = matchedProducts.slice(0, 5);
    const recentToShow = recent.slice(0, 5);
    
    if (!productsToShow.length && !recentToShow.length) {
      searchDropdown.innerHTML = '';
      return;
    }
    
    const historyHtml = recentToShow.length ? `
      <div class="dropdown-group history">
        ${recentToShow.map(term => `
          <div class="dropdown-item" data-term="${term}">
            ${term}
            <button class="remove-tag" data-term="${term}">✕</button>
          </div>
        `).join('')}
      </div>
    ` : '';
    
    const suggestionsHtml = productsToShow.length ? `
      <div class="dropdown-group suggestions">
        ${productsToShow.map(name => `
          <div class="dropdown-item" data-term="${name}">
            ${name}
          </div>
        `).join('')}
      </div>
    ` : '';
    
    searchDropdown.innerHTML = `
      <div class="dropdown-section">
        ${historyHtml}
        ${suggestionsHtml}
      </div>
    `;
  };
  
  return { init };
})();

// ==========================================================================
// 11. Initialize Everything
// ==========================================================================

document.addEventListener('DOMContentLoaded', () => {
  // Enable debug mode in development (optional)
  window.themeDebug = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
  
  ThemeSliders.init();
  ThemeSearch.init();
});

// Optional: Refresh sliders on AJAX navigation (for page loaders)
if (typeof wp !== 'undefined' && wp.hooks) {
  wp.hooks.addAction('wp_loaded', 'theme', () => {
    ThemeSliders.refresh();
  });
}