(function ($) {
    "use strict";

    let SifencyPreloaderHandler = function ($scope, $) {

        let isEdit = elementorFrontend.isEditMode();

        let $wrapper = $scope.find(".sifency-preloader-wrapper"),
            $overlay = $wrapper.find(".sifency-preloader-overlay"),
            settings = $wrapper.data("pl-settings") || { timeout: 3000 };

        if (!isEdit) {
            $('body').addClass('sifency-preloader-active');
        }

        let hidePreloader = () => {
            if ($overlay.hasClass('sifency-loaded')) return;

            $overlay.addClass("sifency-loaded");

            // Delay enabling scroll to allow transition to finish smoothly
            setTimeout(() => {
                $('body').removeClass('sifency-preloader-active');
            }, 800);
            
            // Trigger events and refresh animations
            window.dispatchEvent(new Event('resize'));
            window.dispatchEvent(new Event('sifency/preloader/done'));
            
            if (window.ScrollTrigger) {
                window.ScrollTrigger.refresh();
            }

            // Secondary refresh after layout settles
            setTimeout(() => {
                if (window.ScrollTrigger) {
                    window.ScrollTrigger.refresh();
                }
            }, 100);

            setTimeout(() => {
                $wrapper.remove();
            }, 1200);
        };

        if (isEdit) {
            hidePreloader();
            return;
        }

        // ── Fill Counter style ──────────────────────────────────────────
        let $fillCounter = $wrapper.find('.sifency-loader-fill-counter');
        if ($fillCounter.length) {
            let fcCount  = $fillCounter.find('.sifency-fc-count')[0];
            let fcIcon   = $fillCounter.find('.sifency-fc-icon')[0];
            let fcFillL  = $fillCounter.find('.sifency-fc-fill-left')[0];
            let fcFillR  = $fillCounter.find('.sifency-fc-fill-right')[0];
            let fcFillT  = $fillCounter.find('.sifency-fc-fill-top')[0];
            let fcFillB  = $fillCounter.find('.sifency-fc-fill-bottom')[0];
            let fcMaskTL = $fillCounter.find('.sifency-fc-mask-tl')[0];
            let fcMaskTR = $fillCounter.find('.sifency-fc-mask-tr')[0];
            let fcMaskBL = $fillCounter.find('.sifency-fc-mask-bl')[0];
            let fcMaskBR = $fillCounter.find('.sifency-fc-mask-br')[0];

            if (fcCount && fcFillL) {
                let loadTime  = 1500;
                let startTime = performance.now();

                let runLoader = (now) => {
                    let progress = Math.min((now - startTime) / loadTime, 1);
                    let ease     = 1 - Math.pow(1 - progress, 3);
                    let percent  = Math.round(ease * 100);

                    fcCount.textContent = percent + '%';
                    fcFillL.style.width  = ease * 50 + '%';
                    fcFillR.style.width  = ease * 50 + '%';
                    fcFillT.style.height = ease * 50 + '%';
                    fcFillB.style.height = ease * 50 + '%';

                    if (progress < 1) {
                        requestAnimationFrame(runLoader);
                    } else {
                        // Show icon
                        fcCount.style.display = 'none';
                        if (fcIcon) {
                            fcIcon.style.display    = 'block';
                            fcIcon.style.transition = 'transform 0.6s ease';
                            fcIcon.style.transform  = 'rotate(45deg)';
                        }
                        // Open masks after brief delay
                        setTimeout(() => {
                            [fcMaskTL, fcMaskTR, fcMaskBL, fcMaskBR].filter(Boolean).forEach(m => {
                                m.style.transition = 'transform 0.85s cubic-bezier(0.77, 0, 0.175, 1)';
                            });
                            if (fcMaskTL) fcMaskTL.style.transform = 'scaleY(0)';
                            if (fcMaskTR) fcMaskTR.style.transform = 'scaleX(0)';
                            if (fcMaskBL) fcMaskBL.style.transform = 'scaleX(0)';
                            if (fcMaskBR) fcMaskBR.style.transform = 'scaleY(0)';

                            setTimeout(() => hidePreloader(), 780);
                        }, 350);
                    }
                };
                requestAnimationFrame(runLoader);
                return; // fill-counter handles its own lifecycle
            }
        }

        if (document.readyState === 'complete') {
            hidePreloader();
        } else {
            $(window).on("load", function () {
                hidePreloader();
            });
        }

        setTimeout(function () {
            hidePreloader();
        }, settings.timeout);
    };

    $(window).on("elementor/frontend/init", function () {
        elementorFrontend.hooks.addAction(
            "frontend/element_ready/sifency-preloader.default",
            SifencyPreloaderHandler
        );
    });

})(jQuery);