jQuery(window).on('elementor/frontend/init', function () {

    elementorFrontend.hooks.addAction(
        'frontend/element_ready/sifency_onepage_nav.default',
        function ($scope) {

            const $items   = $scope.find('.sifency-one-page-nav-item');
            if (!$items.length) return;

            const sections = [];
            const headerOffset = document.querySelector('.elementor-sticky--active')
                ? document.querySelector('.elementor-sticky--active').offsetHeight
                : 0;

            /* --------------------------------
             * Collect Sections
             * -------------------------------- */
            $items.each(function () {
                const id = this.dataset.section;
                const el = document.getElementById(id);
                if (el) sections.push(el);
            });

            if (!sections.length) return;

            /* --------------------------------
             * Intersection Observer
             * -------------------------------- */
            const observer = new IntersectionObserver(
                (entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            setActive(entry.target.id);
                        }
                    });
                },
                {
                    rootMargin: `-${headerOffset + 100}px 0px -40% 0px`,
                    threshold: 0.35
                }
            );

            sections.forEach(section => observer.observe(section));

            function setActive(id) {
                $items.removeClass('is-active');
                $scope.find(`[data-section="${id}"]`).addClass('is-active');
            }

            /* --------------------------------
             * Smooth Scroll (OFFSET SAFE)
             * -------------------------------- */
            $scope.on('click', '.sifency-nav-link', function () {
                const id = jQuery(this).closest('.sifency-one-page-nav-item').data('section');
                const target = document.getElementById(id);
                if (!target) return;

                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            });

            /* --------------------------------
             * Scroll Snap (COMPATIBILITY)
             * -------------------------------- */
            if ($scope.data('snap') === true) {
                // Disable Lenis if active to allow native CSS snap
                if (window.sifencyLenis) {
                    window.sifencyLenis.destroy();
                }
                
                document.documentElement.style.scrollSnapType = 'y mandatory';
                document.documentElement.style.scrollBehavior = 'smooth';
            }
        }
    );
});
