<?php
/**
 * Products Section
 *
 * @var array $products
 * @var array $settings
 */

$title    = trim($settings['title'] ?? '');
$subtitle = trim($settings['subtitle'] ?? '');

$productCount = is_array($products) ? count($products) : 0;
$__settingsModel = new \Core\App\Models\Settings();
$__cardAutoRotate = (int)$__settingsModel->get('product_image_autorotate', 1);
$__badgePresets = product_badge_presets();
$__badgeLegacyMap = product_badge_legacy_map();

// Thresholds
$__productCardsMarkupFile = __DIR__ . '/partials/product_cards_markup.php';

// Thresholds
$desktopVisible = 5;
$mobileVisible  = 2;

// Enable slider automatically if products exceed visible count
$enableSlider = $productCount > $desktopVisible;
?>

<section class="home-section products-section reveal" id="products-section">
    <div class="container">

        <?php if ($title || $subtitle): ?>
            <div class="section-head section-head--styled">
                <?php if ($title): ?>
                    <h2>
                        <?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>
                    </h2>
                <?php endif; ?>

                <?php if ($subtitle): ?>
                    <p class="section-subtitle">
                        <?= htmlspecialchars($subtitle, ENT_QUOTES, 'UTF-8') ?>
                    </p>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <div class="products-row-wrapper <?= $enableSlider ? 'is-slider' : 'is-grid' ?>"
             data-desktop-visible="<?= $desktopVisible ?>"
             data-mobile-visible="<?= $mobileVisible ?>">

            <div class="products-cards-grid">
                <?php include $__productCardsMarkupFile; ?>
            </div>

        </div>

    </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const section = document.getElementById('products-section');
    if (!section) return;

    const wrapper = section.querySelector('.products-row-wrapper');
    const grid = section.querySelector('.products-cards-grid');
    const searchInputs = document.querySelectorAll('.header-search-bar input[name="q"], .search-form input[name="q"], .mobile-menu-search input[name="q"]');
    if (!wrapper || !grid) return;

    const originalGridHtml = grid.innerHTML;
    const originalMode = wrapper.classList.contains('is-slider') ? 'slider' : 'grid';
    const sectionsToToggle = Array.from(document.querySelectorAll('.hero-section, .home-ads-section, .home-faq-section, .home-section')).filter(function(el){
        return el !== section;
    });

    let activeController = null;
    let debounceTimer = null;
    let latestQuery = '';

    function preloadImage(src, callback) {
        if (!src) {
            callback(false);
            return;
        }

        const image = new Image();
        image.onload = function(){ callback(true); };
        image.onerror = function(){ callback(false); };
        image.src = src;
    }

    function initProductCardAutoRotate(scope) {
        const root = scope || document;
        const cards = root.querySelectorAll('.product-thumb[data-card-gallery][data-card-autorotate="1"]');

        cards.forEach(function(card){
            if (card.dataset.cardRotateReady === '1') {
                return;
            }

            let gallery = [];
            try {
                gallery = JSON.parse(card.getAttribute('data-card-gallery') || '[]');
            } catch (error) {
                gallery = [];
            }

            if (!Array.isArray(gallery) || gallery.length < 2) {
                card.dataset.cardRotateReady = '0';
                return;
            }

            const primaryImage = card.querySelector('.product-thumb-image--primary');
            const secondaryImage = card.querySelector('.product-thumb-image--secondary');
            if (!primaryImage || !secondaryImage) {
                card.dataset.cardRotateReady = '0';
                return;
            }

            card.dataset.cardRotateReady = '1';

            let activeIndex = 0;
            let activeLayer = card.dataset.cardActiveLayer === 'secondary' ? 'secondary' : 'primary';
            let timer = null;
            let paused = false;
            let switching = false;

            function getVisibleImage() {
                return activeLayer === 'primary' ? primaryImage : secondaryImage;
            }

            function getHiddenImage() {
                return activeLayer === 'primary' ? secondaryImage : primaryImage;
            }

            function applyVisibility() {
                primaryImage.classList.toggle('is-visible', activeLayer === 'primary');
                secondaryImage.classList.toggle('is-visible', activeLayer === 'secondary');
                card.dataset.cardActiveLayer = activeLayer;
            }

            function switchTo(nextIndex) {
                if (switching || nextIndex === activeIndex || !gallery[nextIndex]) {
                    return;
                }

                switching = true;
                const nextSrc = gallery[nextIndex];
                const hiddenImage = getHiddenImage();
                const visibleImage = getVisibleImage();

                preloadImage(nextSrc, function(success){
                    if (!success) {
                        switching = false;
                        return;
                    }

                    hiddenImage.src = nextSrc;
                    hiddenImage.alt = visibleImage.alt;

                    requestAnimationFrame(function(){
                        activeLayer = activeLayer === 'primary' ? 'secondary' : 'primary';
                        applyVisibility();
                        activeIndex = nextIndex;

                        window.setTimeout(function(){
                            switching = false;
                        }, 760);
                    });
                });
            }

            function nextImage() {
                const nextIndex = (activeIndex + 1) % gallery.length;
                switchTo(nextIndex);
            }

            function start() {
                stop();
                if (gallery.length < 2 || paused) {
                    return;
                }
                timer = window.setInterval(nextImage, 3400);
            }

            function stop() {
                if (timer) {
                    window.clearInterval(timer);
                    timer = null;
                }
            }

            card.addEventListener('mouseenter', function(){
                paused = true;
                stop();
            });

            card.addEventListener('mouseleave', function(){
                paused = false;
                start();
            });

            card.addEventListener('touchstart', function(){
                paused = true;
                stop();
            }, { passive: true });

            card.addEventListener('touchend', function(){
                paused = false;
                start();
            }, { passive: true });

            applyVisibility();
            start();
        });
    }

    function setSearchMode(isSearching) {
        sectionsToToggle.forEach(function(el){
            el.style.display = isSearching ? 'none' : '';
        });
        wrapper.classList.toggle('is-grid', isSearching || originalMode === 'grid');
        wrapper.classList.toggle('is-slider', !isSearching && originalMode === 'slider');
        grid.style.overflow = isSearching ? 'visible' : '';
        grid.style.scrollSnapType = isSearching ? 'none' : '';
    }

    function syncInputs(value, sourceInput) {
        searchInputs.forEach(function(input){
            if (input !== sourceInput && input.value !== value) {
                input.value = value;
            }
        });
    }

    function restoreOriginal() {
        if (activeController) {
            activeController.abort();
            activeController = null;
        }
        latestQuery = '';
        grid.innerHTML = originalGridHtml;
        setSearchMode(false);
        initProductCardAutoRotate(grid);
    }

    function performSearch(query) {
        if (activeController) {
            activeController.abort();
        }

        activeController = new AbortController();
        latestQuery = query;

        fetch('/api/home-search?q=' + encodeURIComponent(query), {
            credentials: 'same-origin',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            signal: activeController.signal
        })
        .then(function(response){
            if (!response.ok) {
                throw new Error('Search request failed');
            }
            return response.text();
        })
        .then(function(html){
            if (latestQuery !== query) {
                return;
            }
            grid.innerHTML = html;
            setSearchMode(true);
            initProductCardAutoRotate(grid);
        })
        .catch(function(error){
            if (error.name === 'AbortError') {
                return;
            }
            restoreOriginal();
        });
    }

    if (searchInputs.length) {
        searchInputs.forEach(function(input){
            input.form && input.form.addEventListener('submit', function(event){
                if (document.body.classList.contains('page-home') || section) {
                    event.preventDefault();
                }
            });

            input.addEventListener('input', function(){
                const query = this.value.trim();
                syncInputs(this.value, this);

                clearTimeout(debounceTimer);

                if (query === '') {
                    restoreOriginal();
                    return;
                }

                debounceTimer = setTimeout(function(){
                    performSearch(query);
                }, 220);
            });
        });
    }

    initProductCardAutoRotate(grid);
});
</script>