<section class="container py-5 my-2 my-sm-3 my-lg-4 my-xl-5" id="popular-products-section">
    <div class="row align-items-lg-center py-xxl-3">

        <!-- Products -->
        <div class="col-md-6 col-xl-5 offset-xl-1 order-md-2 mb-4 mb-md-0">
            <div class="ps-md-3 ps-lg-4 ps-xl-0">
                <div class="d-flex align-items-center justify-content-between pb-4 mb-md-1 mb-lg-2 mb-xl-3">
                    <h2 class="me-3 mb-0">Popular products</h2>

                    <!-- Slider prev/next buttons -->
                    <div class="d-flex gap-2">
                        <button type="button"
                            class="btn btn-icon btn-outline-secondary animate-slide-start rounded-circle me-1"
                            id="popularPrev" aria-label="Prev">
                            <i class="ci-chevron-left fs-lg animate-target"></i>
                        </button>
                        <button type="button"
                            class="btn btn-icon btn-outline-secondary animate-slide-end rounded-circle"
                            id="popularNext" aria-label="Next">
                            <i class="ci-chevron-right fs-lg animate-target"></i>
                        </button>
                    </div>
                </div>

                <!-- Products master slider -->
                <div class="swiper"
                    data-swiper='{
            "spaceBetween": 24,
            "loop": true,
            "speed": 400,
            "controlSlider": "#sliderImages",
            "navigation": {
              "prevEl": "#popularPrev",
              "nextEl": "#popularNext"
            }
          }'>
                    <div class="swiper-wrapper" id="popular-products-container">
                        <!-- Products will be loaded via AJAX -->
                    </div>
                </div>
            </div>
        </div>

        <!-- Images -->
        <div class="col-md-6 col-xl-5 order-md-1">
            <div class="position-relative">
                <div class="ratio d-none d-md-block" style="--cz-aspect-ratio: calc(720 / 636 * 100%)">
                </div>
                <div class="ratio ratio-4x3 d-md-none"></div>
                <div class="swiper position-absolute top-0 start-0 w-100 h-100 user-select-none"
                    id="sliderImages"
                    data-swiper='{
            "allowTouchMove": false,
            "loop": true,
            "effect": "fade",
            "fadeEffect": {
              "crossFade": true
            }
          }'>
                    <div class="swiper-wrapper" id="popular-images-container">
                        <!-- Images will be loaded via AJAX -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading state -->
    <div class="text-center py-5 d-none" id="popular-products-loading">
        <div class="row row-cols-2 row-cols-md-3 row-cols-lg-4 gy-4 gy-md-5 pb-xxl-3">
            @for ($i = 1; $i <= 6; $i++)
                <div class="col mb-2 mb-sm-3 mb-md-0">
                    <div class="shimmer-wrapper">
                        <div class="shimmer">
                            <div class="shimmer-content rounded">
                                <div class="shimmer-line shimmer-image rounded mb-3"
                                    style="height: 0; padding-bottom: 100%; position: relative;">
                                    <div
                                        style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.1); border-radius: 4px;">
                                    </div>
                                </div>
                                <div class="shimmer-line shimmer-title rounded mb-2"
                                    style="height: 20px; width: 80%;"></div>
                                <div class="shimmer-line shimmer-price rounded" style="height: 16px; width: 60%;">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            @endfor
        </div>
    </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const productsContainer = document.getElementById('popular-products-container');
    const imagesContainer = document.getElementById('popular-images-container');
    const loadingSpinner = document.getElementById('popular-products-loading');
    const section = document.getElementById('popular-products-section');

    if (!productsContainer || !imagesContainer || !loadingSpinner) {
        return;
    }

    // Load popular products on page load
    loadPopularProducts();

    function loadPopularProducts() {
        // Show loading spinner
        if (loadingSpinner) {
            loadingSpinner.classList.remove('d-none');
        }

        // Make AJAX request for popular products
        fetch('{{ route("product.ajax.highlights") }}?type=best_sellers&limit=6')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.products) {
                    // Parse the HTML to extract individual product cards
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = data.products;
                    
                    const productCards = tempDiv.querySelectorAll('.col');
                    const productsArray = Array.from(productCards);
                    
                    // Split products into two slides (3 products each)
                    const slide1 = productsArray.slice(0, 3);
                    const slide2 = productsArray.slice(3, 6);
                    
                    // Create slides with product lists
                    productsContainer.innerHTML = '';
                    
                    [slide1, slide2].forEach((slide, index) => {
                        const slideDiv = document.createElement('div');
                        slideDiv.className = 'swiper-slide';
                        
                        const listDiv = document.createElement('div');
                        listDiv.className = 'd-flex flex-column gap-3 gap-lg-4';
                        
                        slide.forEach(product => {
                            // Convert product card to list item format
                            const productImg = product.querySelector('img');
                            const productLink = product.querySelector('a');
                            const productPrice = product.querySelector('.h6, .price');
                            
                            const listItem = document.createElement('div');
                            listItem.className = 'd-flex align-items-center position-relative bg-body-tertiary rounded overflow-hidden animate-underline';
                            
                            const img = document.createElement('img');
                            img.src = productImg ? productImg.src : '/img/shop/fashion/thumbs/0' + (index * 3 + slide.indexOf(product) + 1) + '.png';
                            img.width = 110;
                            img.alt = 'Thumbnail';
                            
                            const navDiv = document.createElement('div');
                            navDiv.className = 'nav flex-column gap-2 min-w-0 p-3';
                            
                            const link = document.createElement('a');
                            link.className = 'nav-link text-dark-emphasis stretched-link w-100 min-w-0 p-0';
                            link.href = productLink ? productLink.href : '#';
                            
                            const span = document.createElement('span');
                            span.className = 'animate-target text-truncate';
                            span.textContent = productLink ? productLink.textContent.trim() : 'Product Name';
                            
                            const price = document.createElement('div');
                            price.className = 'h6 mb-0';
                            price.textContent = productPrice ? productPrice.textContent : '$0.00';
                            
                            link.appendChild(span);
                            navDiv.appendChild(link);
                            navDiv.appendChild(price);
                            listItem.appendChild(img);
                            listItem.appendChild(navDiv);
                            listDiv.appendChild(listItem);
                        });
                        
                        slideDiv.appendChild(listDiv);
                        productsContainer.appendChild(slideDiv);
                    });
                    
                    // Load corresponding images
                    loadPopularImages();
                    
                } else {
                    // Handle error
                    productsContainer.innerHTML = '<div class="swiper-slide"><div class="text-center py-4">Error loading products</div></div>';
                }
            })
            .catch(error => {
                console.error('Error loading popular products:', error);
                productsContainer.innerHTML = '<div class="swiper-slide"><div class="text-center py-4">Error loading products</div></div>';
            })
            .finally(() => {
                // Hide loading spinner
                if (loadingSpinner) {
                    loadingSpinner.classList.add('d-none');
                }
                
                // Re-initialize Swiper
                if (window.Swiper) {
                    const swiperElements = section.querySelectorAll('.swiper');
                    swiperElements.forEach(element => {
                        if (element.swiper) {
                            element.swiper.update();
                        }
                    });
                }
            });
    }

    function loadPopularImages() {
        // Load images for the slider
        const images = [
            '/img/home/fashion/v1/popular/01.jpg',
            '/img/home/fashion/v1/popular/02.jpg'
        ];
        
        imagesContainer.innerHTML = '';
        
        images.forEach((src, index) => {
            const slideDiv = document.createElement('div');
            slideDiv.className = 'swiper-slide';
            
            const ratioDiv = document.createElement('div');
            ratioDiv.className = index === 0 ? 'ratio d-none d-md-block' : 'ratio d-none d-md-block';
            ratioDiv.style.setProperty('--cz-aspect-ratio', 'calc(720 / 636 * 100%)');
            
            const mobileRatioDiv = document.createElement('div');
            mobileRatioDiv.className = 'ratio ratio-4x3 d-md-none';
            
            const img = document.createElement('img');
            img.src = src;
            img.className = 'position-absolute top-0 start-0 w-100 h-100 object-fit-cover rounded-5';
            img.alt = 'Image';
            
            if (index === 1) {
                img.style.objectPosition = 'center top';
            }
            
            slideDiv.appendChild(ratioDiv);
            slideDiv.appendChild(mobileRatioDiv);
            slideDiv.appendChild(img);
            imagesContainer.appendChild(slideDiv);
        });
    }
});
</script>
