/**
 * Kubelio Swiper Initialization
 * 
 * Optimized with Intersection Observer for Lazy Initialization.
 */
(function () {
    'use strict';

    /**
     * Align the prev/next navigation arrows to the vertical center of a slide
     * element (e.g. the product/post thumbnail) instead of the full slide height
     * (which also includes the title/price below the image).
     *
     * Works by setting the `--swiper-navigation-top-offset` CSS variable that the
     * theme's swiper styles already use for the arrows' `top` position.
     *
     * @param {HTMLElement} container The `.rt-swiper` wrapper.
     * @param {string}      selector  The slide element to align to (itemWrapper).
     */
    function alignNavigationToWrapper(container, selector) {
        if (!selector) return;

        const wrapper = container.querySelector(".swiper-slide " + selector);
        if (!wrapper) return;

        const apply = function () {
            container.style.setProperty("--swiper-navigation-top-offset", (wrapper.offsetHeight / 2) + "px");
        };

        apply();

        // Re-measure once the thumbnail image has loaded (its height is unknown
        // before that when there is no fixed aspect-ratio).
        const img = wrapper.querySelector("img");
        if (img && !img.complete) {
            img.addEventListener("load", apply, { once: true });
        }
    }

    /**
     * Initialize a single swiper instance
     */
    function initSingleSwiper(swiperElement) {
        if (swiperElement.classList.contains('swiper-initialized')) return;

        const swiperContainer = swiperElement.closest(".rt-swiper");
        const swiperOptions = swiperElement.getAttribute("data-options");
        const options = JSON.parse(swiperOptions || "{}");

        // `itemWrapper` is a custom option (not a native Swiper option); pull it
        // out so it is not forwarded to Swiper, and use it to align the arrows.
        const itemWrapper = options.itemWrapper;
        delete options.itemWrapper;

        const defaults = {
            navigation: {
                nextEl: swiperContainer.querySelector(".swiper-button-next"),
                prevEl: swiperContainer.querySelector(".swiper-button-prev"),
            },
            pagination: {
                el: swiperContainer.querySelector(".swiper-pagination"),
                clickable: true,
            },
            on: {
                init: function () {
                    swiperContainer.classList.add("rt-swiper-initialized");
                    alignNavigationToWrapper(swiperContainer, itemWrapper);
                },
                resize: function () {
                    alignNavigationToWrapper(swiperContainer, itemWrapper);
                },
            },
        };

        // Initialize Swiper
        new Swiper(swiperElement, Object.assign({}, defaults, options));
    }

    /**
     * Main initialization function
     */
    function kubelioSwiperInit() {
        const sliders = document.querySelectorAll(".js-swiper:not(.swiper-initialized)");

        if (!('IntersectionObserver' in window)) {
            // Fallback for old browsers
            sliders.forEach(slider => initSingleSwiper(slider));
            return;
        }

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    initSingleSwiper(entry.target);
                    observer.unobserve(entry.target);
                }
            });
        }, {
            rootMargin: '100px', // Start loading 100px before it enters the viewport
            threshold: 0.01
        });

        sliders.forEach(slider => observer.observe(slider));
    }

    // Expose to window for AJAX use
    window.kubelioSwiperInit = kubelioSwiperInit;

    // Run on DOM Ready
    document.addEventListener("DOMContentLoaded", kubelioSwiperInit);

    // Re-initialize swiper on common AJAX events (e.g. WooCommerce checkout/cart)
    if (typeof jQuery !== "undefined") {
        jQuery(document.body).on("updated_checkout updated_cart updated_cart_totals", function () {
            kubelioSwiperInit();
        });
    }
})();