(function ($) {
    "use strict";

    const initVideoAvatar = ($scope) => {
        const wrapper = $scope.find('.sifency-video-avatar-wrapper')[0];
        if (!wrapper) return;

        if (typeof gsap === 'undefined') {
            console.error('Sifency Error: GSAP is missing.');
            return;
        }

        // ─── Elements ─────────────────────────────────────────────
        const videoWrap = wrapper.querySelector('.sifency-va-video-wrap');
        const video = wrapper.querySelector('.sifency-va-player');       // <video> or null
        const iframe = wrapper.querySelector('.sifency-va-iframe');       // <iframe> or null
        const bubble = wrapper.querySelector('.sifency-va-bubble');       // null if hidden
        const miniOverlay = wrapper.querySelector('.sifency-va-mini-overlay');
        const btnCloseBubble = wrapper.querySelector('.sifency-va-bubble-close');
        const btnCloseMain = wrapper.querySelector('.sifency-va-close-main');

        // ─── Config ───────────────────────────────────────────────
        const config = JSON.parse(wrapper.dataset.config || '{}');
        const bubbleDelay = parseFloat(config.delay ?? 2);
        const expWidth = parseInt(config.expW ?? 300);
        const expHeight = parseInt(config.expH ?? 450);
        const defaultExp = !!config.defaultExp;   // start expanded?
        const showBubble = !!config.showBubble;   // bubble enabled?
        const isIframe = (config.source === 'youtube' || config.source === 'vimeo');

        let isExpanded = false;

        // ─── Helpers ──────────────────────────────────────────────
        const playMedia = () => {
            if (video) {
                video.muted = false;
                video.currentTime = 0;
                video.play().catch(() => { });
            }
            // iframes handle autoplay via their src params; nothing extra needed
        };

        const pauseMedia = () => {
            if (video) video.pause();
            // For iframes we can't pause, but we remove from DOM on close anyway
        };

        const expandPlayer = (instant = false) => {
            isExpanded = true;

            if (bubble) gsap.to(bubble, { scale: 0, duration: instant ? 0 : 0.3 });
            if (miniOverlay) gsap.to(miniOverlay, { autoAlpha: 0, duration: instant ? 0 : 0.3 });
            gsap.to(btnCloseMain, { autoAlpha: 1, duration: instant ? 0 : 0.3, delay: instant ? 0 : 0.3 });

            gsap.to(videoWrap, {
                width: expWidth,
                height: expHeight,
                borderRadius: '16px',
                duration: instant ? 0 : 0.6,
                ease: 'power3.inOut',
                onComplete: () => {
                    if (!isIframe) playMedia();
                }
            });
        };

        // ─── Initial State ────────────────────────────────────────
        gsap.set(wrapper, { autoAlpha: 1 });
        gsap.set(btnCloseMain, { autoAlpha: 0 });

        if (bubble) {
            gsap.set(bubble, { scale: 0, transformOrigin: 'bottom right' });
        }

        // ─── Default Expanded ─────────────────────────────────────
        if (defaultExp) {
            expandPlayer(true); // instant, no animation on load
            return; // skip bubble logic entirely
        }

        // ─── Bubble pop-up (delayed) ──────────────────────────────
        if (showBubble && bubble) {
            setTimeout(() => {
                if (!isExpanded) {
                    gsap.to(bubble, {
                        scale: 1,
                        duration: 0.6,
                        ease: 'elastic.out(1, 0.6)',
                    });
                }
            }, bubbleDelay * 1000);
        }

        // ─── Close Bubble ─────────────────────────────────────────
        if (btnCloseBubble) {
            btnCloseBubble.addEventListener('click', (e) => {
                e.stopPropagation();
                gsap.to(bubble, { scale: 0, duration: 0.3, ease: 'power2.in' });
            });
        }

        // ─── Expand on Click (Mini Avatar) ────────────────────────
        videoWrap.addEventListener('click', () => {
            if (isExpanded) {
                // Toggle play/pause only for native video
                if (video) {
                    video.paused ? video.play().catch(() => { }) : video.pause();
                }
                return;
            }
            expandPlayer(false);
        });

        // ─── Close Main Video ─────────────────────────────────────
        btnCloseMain.addEventListener('click', (e) => {
            e.stopPropagation();
            pauseMedia();

            const origin = _closeOrigin(wrapper);

            gsap.to(wrapper, {
                scale: 0,
                opacity: 0,
                transformOrigin: origin,
                duration: 0.5,
                ease: 'back.in(1.2)',
                onComplete: () => wrapper.remove(),
            });
        });
    };

    /**
     * Determine the correct GSAP transform-origin for the close animation
     * based on which position class is present.
     */
    const _closeOrigin = (wrapper) => {
        const cls = wrapper.className;
        if (cls.includes('sifency-pos-top-left')) return 'top left';
        if (cls.includes('sifency-pos-top-center')) return 'top center';
        if (cls.includes('sifency-pos-top-right')) return 'top right';
        if (cls.includes('sifency-pos-middle-left')) return 'center left';
        if (cls.includes('sifency-pos-middle-center')) return 'center center';
        if (cls.includes('sifency-pos-middle-right')) return 'center right';
        if (cls.includes('sifency-pos-bottom-left')) return 'bottom left';
        if (cls.includes('sifency-pos-bottom-center')) return 'bottom center';
        return 'bottom right'; // default / bottom-right / relative
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-video-avatar.default',
            initVideoAvatar
        );
    });

})(jQuery);