(() => {
    'use strict';

    // ─── Constants ────────────────────────────────────────────────────────────────

    const SWIPER_SELECTOR = '.swiper-container, .swiper';
    const SWIPER_DATA_KEY = '__swiperInstance';
    const EDIT_MODE_DELAY = 200;

    const WIDGETS = [
        'sifency-addons-testimonials',
        'sifency-addons-blog-post',
        'sifency-addons-clients',
        'sifency-addons-event',
        'sifency-addons-projects',
        'sifency-addons-services',
        'sifency-addons-team',
        'sifency-addons-digital-goods-post',
        'products-slider-sifency',
        'sifency-nested-slider',
        'sifency-addons-awards',
        'sifency-addons-career',
        'sifency-related-products',
        'sifency-products',
        'sifency-addons-edd-grid',
        'sifency-digital-item-images-slider',
        'sifency-advanced-timeline',
        'sifency-device-slider',
        'sifency-device-carousel',
        'sifency-image-slider',
        'sifency-google-reviews',
        'sifency-social-feed',
    ];

    // ─── Helpers ──────────────────────────────────────────────────────────────────

    /**
     * Safely parse JSON — returns null on failure instead of throwing.
     * @param {string|undefined} raw
     * @returns {object|null}
     */
    const parseJSON = (raw) => {
        if (!raw) return null;
        try { return JSON.parse(raw); }
        catch { return null; }
    };

    /**
     * Destroy an existing Swiper instance attached to an element.
     * @param {Element} el
     */
    const destroyExisting = (el) => {
        const existing = el[SWIPER_DATA_KEY];
        if (existing?.destroy) {
            existing.destroy(true, true);
            delete el[SWIPER_DATA_KEY];
        }
    };

    // ─── Core Handler ─────────────────────────────────────────────────────────────

    /**
     * Initialises (or re-initialises) a Swiper for the given Elementor scope.
     * @param {jQuery} $scope
     */
    const initSwiper = ($scope) => {
        const container = $scope[0].querySelector(SWIPER_SELECTOR);
        if (!container) return;

        const options = parseJSON(container.dataset.swiperOptions);
        if (!options) return;

        destroyExisting(container);

        const instance = new Swiper(container, options);
        container[SWIPER_DATA_KEY] = instance;

        if (elementorFrontend.isEditMode()) {
            setTimeout(() => instance.update(), EDIT_MODE_DELAY);
        }
    };

    // ─── Elementor Bootstrap ──────────────────────────────────────────────────────

    window.addEventListener('elementor/frontend/init', () => {
        const { hooks } = elementorFrontend;

        WIDGETS.forEach((widget) => {
            hooks.addAction(`frontend/element_ready/${widget}.default`, initSwiper);
        });
    });

})();