{{-- SPA 导航兼容：一次性注册 livewire:navigated，避免内联脚本在每次换页时重复绑定。 --}}
<script data-navigate-once>
(function () {
    'use strict';

    function teardownSidebarCommonFunctionsSticky() {
        var state = window.__dberpSidebarCommonFunctionsSticky;

        if (!state) {
            return;
        }

        if (state.observer) {
            state.observer.disconnect();
        }

        if (state.sentinel && state.sentinel.parentNode) {
            state.sentinel.parentNode.removeChild(state.sentinel);
        }

        window.__dberpSidebarCommonFunctionsSticky = null;
    }

    function initSidebarCommonFunctionsSticky() {
        teardownSidebarCommonFunctionsSticky();

        var stickyEl = document.querySelector('.dberp-sidebar-common-functions-sticky');

        if (!stickyEl) {
            return;
        }

        var sentinel = document.createElement('div');
        sentinel.setAttribute('data-dberp-sidebar-sticky-sentinel', '1');
        sentinel.style.cssText = 'height:0;overflow:hidden;pointer-events:none;';
        stickyEl.parentNode.insertBefore(sentinel, stickyEl);

        var observer = new IntersectionObserver(
            function (entries) {
                entries.forEach(function (entry) {
                    stickyEl.classList.toggle('dberp-sticky-active', !entry.isIntersecting);
                });
            },
            {
                root: stickyEl.closest('.fi-sidebar-nav'),
                threshold: 0,
            },
        );

        observer.observe(sentinel);

        window.__dberpSidebarCommonFunctionsSticky = {
            observer: observer,
            sentinel: sentinel,
        };
    }

    function initAdminPageAfterSpaNavigation() {
        initSidebarCommonFunctionsSticky();
    }

    if (window.__dberpAdminSpaNavCompatBound) {
        initAdminPageAfterSpaNavigation();

        return;
    }

    window.__dberpAdminSpaNavCompatBound = true;

    document.addEventListener('livewire:navigated', initAdminPageAfterSpaNavigation);

    initAdminPageAfterSpaNavigation();
})();
</script>
