/**
 * Audace — Menu Overlay
 *
 * Replaces the native Navigation block burger overlay with our fully-designable
 * #audace-menu-overlay (rendered from the menu-overlay template part).
 *
 * - Hijacks clicks on .wp-block-navigation__responsive-container-open
 * - Closes on ESC, on overlay close button, on backdrop click
 * - Locks body scroll while open
 */
(function () {
    'use strict';

    // Measure the site header height into a CSS var (used by the full-height option).
    function measureHeader() {
        var header = document.querySelector('.audace-site-header')
            || document.querySelector('header.wp-site-blocks > header')
            || document.querySelector('header');
        var h = header ? Math.round(header.getBoundingClientRect().height) : 0;
        document.documentElement.style.setProperty('--audace-header-h', h + 'px');
    }
    measureHeader();
    window.addEventListener('resize', measureHeader);
    window.addEventListener('load', measureHeader);

    var overlay = document.getElementById('audace-menu-overlay');
    if (!overlay) return;

    var lastFocus = null;

    function openOverlay() {
        lastFocus = document.activeElement;
        overlay.hidden = false;
        overlay.setAttribute('aria-hidden', 'false');
        document.documentElement.classList.add('audace-overlay-open');
        document.body.style.overflow = 'hidden';
        var focusable = overlay.querySelector('a, button, input, [tabindex]:not([tabindex="-1"])');
        if (focusable) focusable.focus();
    }

    function closeOverlay() {
        overlay.hidden = true;
        overlay.setAttribute('aria-hidden', 'true');
        document.documentElement.classList.remove('audace-overlay-open');
        document.body.style.overflow = '';
        if (lastFocus && typeof lastFocus.focus === 'function') lastFocus.focus();
    }

    // Close the overlay, then scroll the target so it sits right below the
    // admin bar + site header. Manual math (not scrollIntoView) so we can
    // honor the exact viewport offset on mobile.
    // For `position: sticky` elements, getBoundingClientRect().top returns
    // the stuck offset (≈ header height), not the in-flow position. Walk
    // the offsetParent chain instead — offsetTop ignores sticky and gives
    // the element's natural document-relative position.
    function absoluteTop(el) {
        var y = 0;
        while (el && el !== document.body) {
            y += el.offsetTop || 0;
            el = el.offsetParent;
        }
        return y;
    }

    function jumpToAnchor(hash) {
        var target = hash && document.querySelector(hash);
        if (!target) return false;
        closeOverlay();

        requestAnimationFrame(function () {
            // Desktop: library active → jump by slide INDEX (instant).
            // With sticky slides, index-based navigation is reliable even
            // when scrollY doesn't reflect the visually-on-top slide.
            // Mobile: library not bound → plain smooth scroll to offset.
            var snap = window.audaceScrollSnap;
            if (snap && snap.isActive && snap.isActive() &&
                typeof snap.snapToElement === 'function' &&
                snap.snapToElement(target)) {
                // jumped via index
            } else {
                var header  = document.querySelector('.audace-site-header, header.wp-block-template-part, header');
                var headerH = header ? header.getBoundingClientRect().height : 0;
                var y = absoluteTop(target) - headerH;
                window.scrollTo({ top: y, behavior: 'smooth' });
            }
            if (history.replaceState) history.replaceState(null, '', hash);
        });
        return true;
    }

    // Hijack every native Navigation burger + handle overlay anchor links.
    document.addEventListener('click', function (e) {
        var opener = e.target.closest('.wp-block-navigation__responsive-container-open');
        if (opener) {
            e.preventDefault();
            e.stopPropagation();
            openOverlay();
            return;
        }
        if (e.target.closest('.audace-menu-overlay__close')) {
            e.preventDefault();
            closeOverlay();
            return;
        }
        if (overlay.contains(e.target)) {
            var anchor = e.target.closest('a');
            if (anchor) {
                var href = anchor.getAttribute('href') || '';
                var hashIdx = href.indexOf('#');
                var hash = hashIdx >= 0 ? href.substring(hashIdx) : '';
                var target = hash.length > 1 ? document.querySelector(hash) : null;
                e.preventDefault();
                e.stopPropagation();
                if (target) {
                    jumpToAnchor(hash);
                } else {
                    closeOverlay();
                    if (href && href !== '#' && hashIdx !== 0) {
                        window.location.href = href;
                    }
                }
                return;
            }
        }
        // Click on the overlay backdrop (the overlay container itself, not its inner content).
        if (e.target === overlay) {
            closeOverlay();
        }
    }, true);

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && !overlay.hidden) {
            closeOverlay();
        }
    });

    // On initial page load, if the URL has an anchor, scroll to it using the
    // same logic as a menu click (so slides-container pinning is honored).
    function initialHashJump() {
        var hash = window.location.hash;
        if (!hash || hash.length < 2) return;
        // Wait for slides-container layout to be ready so audaceScrollYFor
        // returns the correct target scrollY.
        requestAnimationFrame(function () {
            requestAnimationFrame(function () { jumpToAnchor(hash); });
        });
    }
    if (document.readyState === 'complete') {
        initialHashJump();
    } else {
        window.addEventListener('load', initialHashJump);
    }
})();