/**
 * Audace — In the editor, hijack clicks on the Navigation block burger so that
 * instead of opening the misleading native overlay panel, the user is taken
 * straight to the Menu Overlay template part for editing.
 *
 * Capture-phase listener on document so it fires before the native handler.
 * Iframe canvas (Site Editor / Post Editor) is supported by attaching to
 * each iframe's contentDocument when it appears.
 */
(function () {
    'use strict';

    if (typeof AudaceOverlay === 'undefined' || !AudaceOverlay.editUrl) return;

    function onClick(e) {
        var opener = e.target.closest && e.target.closest('.wp-block-navigation__responsive-container-open');
        if (opener) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            window.top.location.href = AudaceOverlay.editUrl;
            return;
        }
        // Fallback: if the native overlay still managed to open (race / extension /
        // older Gutenberg), wire up the close button so users aren't stuck.
        var closer = e.target.closest && e.target.closest('.wp-block-navigation__responsive-container-close');
        if (closer) return; // native handler will close it; don't interfere.
    }

    function closeNativeOverlay(doc) {
        var open = doc.querySelector('.wp-block-navigation__responsive-container.is-menu-open');
        if (!open) return false;
        var btn = open.querySelector('.wp-block-navigation__responsive-container-close');
        if (btn) { btn.click(); return true; }
        // Fallback: forcibly hide it.
        open.classList.remove('is-menu-open');
        var nav = open.closest('.wp-block-navigation');
        if (nav) nav.classList.remove('has-modal-open');
        return true;
    }

    function attach(doc) {
        if (!doc || doc.__audaceOverlayBound) return;
        doc.__audaceOverlayBound = true;
        doc.addEventListener('click', onClick, true);
        // ESC closes any native overlay that managed to slip through.
        doc.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') closeNativeOverlay(doc);
        });
    }

    attach(document);

    // The canvas often renders in an iframe (Site Editor, Post Editor preview).
    function scanIframes() {
        var frames = document.querySelectorAll('iframe');
        for (var i = 0; i < frames.length; i++) {
            try {
                attach(frames[i].contentDocument);
            } catch (err) { /* cross-origin, ignore */ }
        }
    }

    scanIframes();
    var mo = new MutationObserver(scanIframes);
    mo.observe(document.body, { childList: true, subtree: true });
})();
