// Wrapper initializer for RSS NewsSync Swiper instances.
// - Only initializes elements matching provided selectors.
// - Uses a queue pushed by PHP via wp_add_inline_script (attached to swiper-js).
// - Guards against double-initialization and missing Swiper global.

(function () {
    'use strict';

    function initInstance(item) {
        try {
            if (typeof Swiper === 'undefined') return;
            var selector = item.selector || '.rsp-carousel';
            var opts = item.options || {};
            var els = document.querySelectorAll(selector);
            if (!els || !els.length) return;
            Array.prototype.forEach.call(els, function (el) {
                // Avoid double init
                if (el.dataset.rspSwiperInit) return;
                // create instance
                new Swiper(el, opts);
                el.dataset.rspSwiperInit = '1';
            });
        } catch (e) {
            // Do not break the page; debug removed to avoid console output in production
        }
    }

    // Process any queued inits set by PHP (wp_add_inline_script pushes items into the new queue)
    function processQueue() {
        var q = (window.newssync_swiper_queue || []);
        for (var i = 0; i < q.length; i++) {
            initInstance(q[i]);
        }
    }

    // Expose an API to register additional inits at runtime (register on both old and new globals for compatibility)
    window.newssync_swiper_register = function (item) {
        window.newssync_swiper_queue = window.newssync_swiper_queue || [];
        window.newssync_swiper_queue.push(item);
        // Try init immediately in case Swiper is already available
        initInstance(item);
    };

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