(function ($) {
    "use strict";

    /**
     * Wait until an element has a non-zero painted size, then invoke callback.
     * Uses ResizeObserver when available, falls back to a short rAF poll.
     */
    function whenSized(el, cb) {
        if (el.offsetWidth > 0 && el.offsetHeight > 0) {
            cb();
            return;
        }

        if (typeof ResizeObserver !== 'undefined') {
            var ro = new ResizeObserver(function (entries) {
                for (var i = 0; i < entries.length; i++) {
                    if (entries[i].contentRect.width > 0) {
                        ro.disconnect();
                        cb();
                        return;
                    }
                }
            });
            ro.observe(el);
        } else {
            // Fallback: poll for up to 2 s
            var attempts = 0;
            var poll = setInterval(function () {
                attempts++;
                if (el.offsetWidth > 0 || attempts > 40) {
                    clearInterval(poll);
                    if (el.offsetWidth > 0) cb();
                }
            }, 50);
        }
    }

    const initSifencyImageFX = ($scope) => {
        const $container = $scope.find('.sifency-fx-container');
        if (!$container.length) return;

        const el = $container[0];
        const data = $container.data();
        const type = data.animType;

        if (type === 'liquid') {
            // THREE must be global for hover-effect UMD to work.
            if (typeof hoverEffect === 'undefined') {
                console.warn('[SifencyFX] hoverEffect is undefined — check THREE is exposed as window.THREE and hover-effect.js loaded correctly.');
                return;
            }

            whenSized(el, function () {
                new hoverEffect({
                    parent: el,
                    intensity: parseFloat(data.intensity) || 0.2,
                    image1: data.img1,
                    image2: data.img2,
                    displacementImage: data.disp,
                    // Must match actual image aspect ratio; 1.0 causes black canvas for non-square images.
                    imagesRatio: el.offsetHeight / el.offsetWidth,
                    speedIn: 1.6,
                    speedOut: 1.2
                });
            });

        } else if (type === 'tilt') {
            if (window.VanillaTilt) {
                window.VanillaTilt.init(el, { max: 25, speed: 400 });
            }

        } else if (type === 'glitch') {
            // Glitch: handled via CSS class (sifency-fx-type-glitch)
        }
        // type === 'none' → plain <img> already rendered by PHP, nothing to init.
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-addons-animated-image.default',
            initSifencyImageFX
        );
    });

})(jQuery);