(function ($) {
    "use strict";

    const initRevealFrame = ($scope) => {
        const main = $scope.find('.sa-reveal-frame-main')[0];
        const circle = $scope.find('.sa-reveal-frame-circle')[0];
        const circleWrap = $scope.find('.sa-reveal-frame-circle-wrapper')[0];
        const revealLayer = $scope.find('.sa-reveal-frame-reveal-layer')[0];
        const baseLayer = $scope.find('.sa-reveal-frame-base-layer')[0];

        if (!main) return;

        // If neither the circle nor the reveal layer exist there is nothing
        // to animate — bail out gracefully.
        if (!circle && !revealLayer) return;

        gsap.registerPlugin(ScrollTrigger);

        const tl = gsap.timeline({
            scrollTrigger: {
                trigger: main,
                start: "top top",
                end: "+=300%",
                pin: true,
                scrub: 1,
                anticipatePin: 1
            }
        });

        // ── Step 0: Hold first frame (100 vh) ──────────────────────────
        // Only add a hold if the base layer exists.
        if (baseLayer) {
            tl.to({}, { duration: 1 });
        }

        // ── Step 1: Grow circle (200 vh) ───────────────────────────────
        if (circle) {
            tl.fromTo(
                circle,
                { scale: 0, transformOrigin: "center center" },
                { scale: 25, duration: 2, ease: "none" }
            );
        }

        // ── Step 2: Fade in revealed content (last 100 vh of reveal) ───
        if (revealLayer) {
            tl.fromTo(
                revealLayer,
                { opacity: 0, y: 50, pointerEvents: "none" },
                { opacity: 1, y: 0, pointerEvents: "auto", duration: 1 },
                circle ? "-=1" : undefined   // overlap only when circle is present
            );
        }

        // ── Step 3: Fade out base layer (first 100 vh of reveal) ───────
        if (baseLayer) {
            tl.to(
                baseLayer,
                { opacity: 0, pointerEvents: "none", duration: 1 },
                circle ? "-=2" : "-=1"
            );
        }

        // ── Step 4: Hold final frame (100 vh) ──────────────────────────
        if (revealLayer) {
            tl.to({}, { duration: 1 });
        }
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-reveal-frame.default',
            initRevealFrame
        );
    });

})(jQuery);