/**
 * Helpers.js - Consolidated JavaScript utilities for showcase and slider layouts
 * Loaded directly in index.js for React admin compatibility
 */

// Showcase functionality (converted from jQuery to vanilla JS)
window.initializeShowcase = function () {
    console.log('Initializing showcase layouts...');

    const showcaseContainers = document.querySelectorAll('.wcps-showcase');

    showcaseContainers.forEach(container => {
        // Skip if already initialized
        if (container.dataset.initialized === 'true') {
            return;
        }

        const $showcase = jQuery(container);
        const $featuredContainer = $showcase.find('.wcps-showcase-featured-container');

        // Load first product on init
        const firstProductHtml = $showcase.find('.wcps-showcase-details .wcps-product-detail[data-index="0"]').html();
        if (firstProductHtml) {
            $featuredContainer.html(firstProductHtml);
        }

        // Initialize gallery click events
        initGalleryClicks($showcase);

        // Thumbnail click event
        $showcase.find('.wcps-showcase-thumb').on('click', function () {
            const index = jQuery(this).data('index');
            const productHtml = $showcase.find('.wcps-showcase-details .wcps-product-detail[data-index="' + index + '"]').html();

            // Update active thumbnail
            $showcase.find('.wcps-showcase-thumb').removeClass('active');
            jQuery(this).addClass('active');

            // Fade out/in the featured product
            $featuredContainer.fadeOut(200, function () {
                jQuery(this).html(productHtml).fadeIn(200);

                // Re-initialize gallery click events after product switch
                initGalleryClicks($showcase);
            });
        });

        // Mark as initialized
        container.dataset.initialized = 'true';
    });

    console.log(`Initialized ${showcaseContainers.length} showcase containers`);

    // Function to initialize gallery thumbnail click events
    function initGalleryClicks($showcase) {
        $showcase.find('.wcps-product-showcase').each(function () {
            const $productShowcase = jQuery(this);
            const $mainImage = $productShowcase.find('.wcps-product-showcase-image > img').first();

            if ($mainImage.length === 0) return; // Exit if no main image

            // Store original main image attributes
            const originalSrc = $mainImage.attr('src');
            const originalSrcset = $mainImage.attr('srcset');
            const originalSizes = $mainImage.attr('sizes');

            // Add click event for each gallery image
            $productShowcase.find('.wcps-gallery-image').on('click', function () {
                const $galleryImg = jQuery(this).find('img');

                if ($galleryImg.length) {
                    // Get gallery image attributes
                    const newSrc = $galleryImg.attr('src');
                    const newSrcset = $galleryImg.attr('srcset');
                    const newSizes = $galleryImg.attr('sizes');

                    // Create larger version URL by removing thumbnail size from URL
                    const largerSrc = newSrc.replace(/-\d+x\d+(?=\.[a-z]+$)/i, '');

                    // Update the main image
                    $mainImage.fadeOut(200, function () {
                        // If larger image URL was created, use it
                        jQuery(this).attr('src', largerSrc || newSrc);

                        // Only update srcset and sizes if they exist on the gallery image
                        if (newSrcset) jQuery(this).attr('srcset', newSrcset);
                        if (newSizes) jQuery(this).attr('sizes', newSizes);

                        jQuery(this).fadeIn(200);
                    });

                    // Visual indicator for active thumbnail
                    $productShowcase.find('.wcps-gallery-image').removeClass('active');
                    jQuery(this).addClass('active');
                }
            });
        });
    }
};

// Slider functionality using Slick.js
window.initializeSlider = function () {
    console.log('Initializing slider layouts...');

    // Check if Slick.js is available
    if (typeof jQuery === 'undefined' || typeof jQuery.fn.slick === 'undefined') {
        console.warn('Slick.js not available - slider initialization skipped');
        return;
    }

    const sliderContainers = document.querySelectorAll('.wcps-slider-container');

    sliderContainers.forEach(container => {
        const $slider = jQuery(container);

        // Skip if already initialized
        if ($slider.hasClass('slick-initialized')) {
            return;
        }

        // Extract configuration from the inline script that was generated by PHP
        // The Pro version generates inline scripts with slick configuration
        let config = {
            dots: true,
            arrows: true,
            infinite: true,
            speed: 300,
            slidesToShow: 3,
            slidesToScroll: 1,
            autoplay: true,
            autoplaySpeed: 3000,
            responsive: [
                {
                    breakpoint: 1024,
                    settings: {
                        slidesToShow: 3,
                        slidesToScroll: 1
                    }
                },
                {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: 2,
                        slidesToScroll: 1
                    }
                },
                {
                    breakpoint: 480,
                    settings: {
                        slidesToShow: 1,
                        slidesToScroll: 1
                    }
                }
            ]
        };

        // Look for existing script tag with configuration
        const scriptTag = container.parentNode.querySelector('script');
        if (scriptTag && scriptTag.textContent.includes('slick(')) {
            try {
                // Extract JSON configuration from the script
                const configMatch = scriptTag.textContent.match(/\.slick\((\{.*?\})\)/s);
                if (configMatch) {
                    const extractedConfig = JSON.parse(configMatch[1]);
                    config = { ...config, ...extractedConfig };
                }
            } catch (error) {
                console.warn('Could not parse slider configuration, using defaults:', error);
            }
        }

        try {
            $slider.slick(config);
            console.log('Slider initialized successfully with config:', config);
        } catch (error) {
            console.error('Error initializing slider:', error);
        }
    });

    console.log(`Processed ${sliderContainers.length} slider containers`);
};

// Combined initialization function
window.initializeLayouts = function () {
    console.log('Initializing all layouts...');
    console.log('jQuery available:', typeof jQuery !== 'undefined');
    console.log('Slick available:', typeof jQuery !== 'undefined' && typeof jQuery.fn.slick !== 'undefined');

    // Debug: Check what elements are in the DOM
    console.log('Showcase elements found:', document.querySelectorAll('.wcps-showcase').length);
    console.log('Slider elements found:', document.querySelectorAll('.wcps-slider-container').length);

    // Initialize showcases
    if (typeof window.initializeShowcase === 'function') {
        window.initializeShowcase();
    }

    // Initialize sliders
    if (typeof window.initializeSlider === 'function') {
        window.initializeSlider();
    }
};

// Auto-initialize when DOM and jQuery are ready
function initWhenReady() {
    if (typeof jQuery !== 'undefined') {
        window.initializeLayouts();
    } else {
        // Wait for jQuery to be available
        setTimeout(initWhenReady, 100);
    }
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initWhenReady);
} else {
    initWhenReady();
}

// Also initialize when new content is added (for React updates)
const observer = new MutationObserver(function (mutations) {
    let shouldReinit = false;

    mutations.forEach(function (mutation) {
        if (mutation.type === 'childList') {
            mutation.addedNodes.forEach(function (node) {
                if (node.nodeType === 1) { // Element node
                    if (node.classList.contains('wcps-showcase') ||
                        node.classList.contains('wcps-slider-container') ||
                        node.querySelector('.wcps-showcase') ||
                        node.querySelector('.wcps-slider-container')) {
                        shouldReinit = true;
                    }
                }
            });
        }
    });

    if (shouldReinit) {
        setTimeout(window.initializeLayouts, 100);
    }
});

// Start observing
observer.observe(document.body, {
    childList: true,
    subtree: true
});

// Manual trigger function for React components
window.triggerLayoutInit = function () {
    console.log('Manual layout initialization triggered');
    setTimeout(window.initializeLayouts, 50);
};

console.log('Helpers.js loaded - Layout initialization ready');