(function( $ ) {
    'use strict';

    var SifencyModalHandler = function( $scope, $ ) {

        var $btn          = $scope.find('.sifency-modal-trigger-btn');
        var $modalWrapper = $scope.find('.sifency-modal-overlay-wrapper');
        var $closeBtn     = $modalWrapper.find('.sifency-modal-close');
        var $backdrop     = $modalWrapper.find('.sifency-modal-backdrop');
        var isAnimating   = false;

        // Move the overlay to <body> so it is never clipped by overflow/z-index
        if ( $modalWrapper.parent().is( $scope.find('.sifency-modal-widget-wrapper') ) ) {
            $modalWrapper.appendTo('body');
        }

        // ── Helper: detect the longest animation/transition duration on the container ──
        function getCloseDuration() {
            var el = $modalWrapper.find('.sifency-modal-container')[0];
            if ( ! el ) { return 380; }

            var style    = window.getComputedStyle(el);
            var transDur = style.transitionDuration  || '0s';
            var animDur  = style.animationDuration   || '0s';

            function parseSecs( str ) {
                // handles comma-separated multi-value lists, picks the max
                return str.split(',').reduce(function(max, s) {
                    var v = parseFloat(s.trim());
                    if ( isNaN(v) ) { return max; }
                    var ms = s.indexOf('ms') > -1 ? v : v * 1000;
                    return Math.max(max, ms);
                }, 0);
            }

            var ms = Math.max( parseSecs(transDur), parseSecs(animDur) );
            return ms > 50 ? ms + 40 : 380;   // minimum 380 ms fallback
        }

        // ── OPEN ─────────────────────────────────────────────────────────────────────────
        $btn.on('click', function(e) {
            e.preventDefault();
            if ( isAnimating ) { return; }

            // 1. Make the wrapper visible (display: flex) while it is still opacity:0
            //    so CSS can compute the initial transform state of the container.
            $modalWrapper[0].style.display = 'flex';

            // 2. Force the browser to paint the frame with display:flex + opacity:0
            //    BEFORE adding is-open. This is what makes the transition work.
            $modalWrapper[0].offsetHeight; // ← reflow trigger (do NOT remove)

            // 3. Now add is-open — the browser will transition FROM the starting state.
            $modalWrapper.addClass('is-open').attr('aria-hidden', 'false');
            $('body').addClass('sifency-noscroll');
        });

        // ── CLOSE ────────────────────────────────────────────────────────────────────────
        function closeModal() {
            if ( ! $modalWrapper.hasClass('is-open') || isAnimating ) { return; }

            isAnimating = true;

            // 1. Remove is-open, add is-closing → triggers CSS exit animation
            $modalWrapper.removeClass('is-open').addClass('is-closing');

            var duration = getCloseDuration();

            setTimeout(function() {
                // 2. After animation finishes, fully hide the overlay
                $modalWrapper[0].style.display = 'none';
                $modalWrapper.removeClass('is-closing').attr('aria-hidden', 'true');

                if ( ! $('.sifency-modal-overlay-wrapper.is-open').length ) {
                    $('body').removeClass('sifency-noscroll');
                }
                isAnimating = false;
            }, duration);
        }

        $closeBtn.on('click', closeModal);
        $backdrop.on('click', closeModal);

        $( document ).on('keyup', function(e) {
            if ( e.key === 'Escape' && $modalWrapper.hasClass('is-open') ) {
                closeModal();
            }
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-widget-modal.default',
            SifencyModalHandler
        );
    });

})( jQuery );