<?php
/**
 * admin-toc.php — sidebar table-of-contents for long admin pages.
 *
 * Rendered as an <aside> inside <main>, before the <article> content.
 * Uses IntersectionObserver to highlight the active section.
 */
?>
<aside id="admin-toc" class="admin-toc" aria-label="Sur cette page">
    <nav class="admin-toc-list" id="admin-toc-list">
        <!-- populated by JS -->
    </nav>
</aside>

<script>
(function() {
    function build() {
        var main = document.getElementById('main-content');
        var nav  = document.getElementById('admin-toc-list');
        var aside = document.getElementById('admin-toc');
        if (!main || !nav || !aside) return;

        var sections = main.querySelectorAll('section[aria-labelledby]');
        if (sections.length < 2) { aside.hidden = true; return; }

        var items = [];
        sections.forEach(function(sec) {
            var headingId = sec.getAttribute('aria-labelledby');
            var heading = document.getElementById(headingId);
            if (!heading) return;
            if (!sec.id) sec.id = headingId;

            var a = document.createElement('a');
            a.href = '#' + sec.id;
            a.textContent = heading.textContent.trim();
            a.style.display = 'block';
            nav.appendChild(a);
            items.push({ section: sec, link: a });
        });

        var observer = new IntersectionObserver(function(entries) {
            var best = null, bestRatio = 0;
            entries.forEach(function(e) {
                if (e.intersectionRatio > bestRatio) { bestRatio = e.intersectionRatio; best = e.target; }
            });
            items.forEach(function(item) {
                item.link.classList.toggle('admin-toc-active', item.section === best);
            });
        }, { rootMargin: '-10% 0px -70% 0px', threshold: [0, 0.25, 0.5, 0.75, 1] });

        items.forEach(function(item) { observer.observe(item.section); });
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', build);
    else build();
})();
</script>
