// Burger btn + 5-fan menu on room.html. Pure scaffolding for now —
// sub-btns have no click handlers in this sprint. Behaviour owned here:
//   • Toggle #id_burger_btn.active on click.
//   • Closing burger via re-click / Escape / click-outside.
//   • Opening burger auto-closes the kit dialog (#id_kit_bag_dialog) and
//     the bud slide-out panel (html.bud-open) if either is open —
//     dispatched by clicking the owning btn, which routes through that
//     btn's own toggle/close path (no fetch on close).
//
// bindBurger() returns an AbortController so test code (and any future
// re-bind callers) can detach all listeners cleanly via ac.abort().

(function () {
    'use strict';

    function bindBurger() {
        var btn = document.getElementById('id_burger_btn');
        var fan = document.getElementById('id_burger_fan');
        if (!btn || !fan) return null;

        var ac = new AbortController();
        var sig = ac.signal;

        function _isOpen() {
            return btn.classList.contains('active');
        }

        function _closeKit() {
            var dialog = document.getElementById('id_kit_bag_dialog');
            var kitBtn = document.getElementById('id_kit_btn');
            if (dialog && dialog.hasAttribute('open') && kitBtn) {
                kitBtn.click();
            }
        }

        function _closeBud() {
            var budBtn = document.getElementById('id_bud_btn');
            if (document.documentElement.classList.contains('bud-open') && budBtn) {
                budBtn.click();
            }
        }

        function _open() {
            _closeKit();
            _closeBud();
            btn.classList.add('active');
            btn.setAttribute('aria-expanded', 'true');
            fan.setAttribute('aria-hidden', 'false');
        }

        function _close() {
            btn.classList.remove('active');
            btn.setAttribute('aria-expanded', 'false');
            fan.setAttribute('aria-hidden', 'true');
        }

        // 2 pulses, ~180ms ON / 120ms OFF — tighter cadence than
        // sig-select's countdown glow (600ms), but same shape.
        function _flashInactive(subBtn) {
            var pulses = 2;
            var onMs = 180;
            var offMs = 120;
            function pulse(remaining) {
                if (remaining <= 0) return;
                subBtn.classList.add('flash-inactive');
                setTimeout(function () {
                    subBtn.classList.remove('flash-inactive');
                    setTimeout(function () {
                        pulse(remaining - 1);
                    }, offMs);
                }, onMs);
            }
            pulse(pulses);
        }

        btn.addEventListener('click', function (e) {
            e.stopPropagation();
            if (_isOpen()) _close();
            else _open();
        }, { signal: sig });

        // Delegated click on the fan:
        //   • INACTIVE sub-btn → flash the --priRd glow twice (no real action
        //     bound yet for that surface).
        //   • ACTIVE sub-btn → close the burger fan so the surface's own
        //     handler (page-level direct listener on the sub-btn) takes over
        //     w. a clean visual. The per-page handler fires BEFORE this
        //     delegated one (target-phase before bubble-up), so the action
        //     already kicked off by the time we close.
        fan.addEventListener('click', function (e) {
            e.stopPropagation();
            var subBtn = e.target.closest('.burger-fan-btn');
            if (!subBtn) return;
            if (subBtn.classList.contains('active')) {
                _close();
            } else {
                _flashInactive(subBtn);
            }
        }, { signal: sig });

        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && _isOpen()) _close();
        }, { signal: sig });

        document.addEventListener('click', function (e) {
            if (!_isOpen()) return;
            if (btn.contains(e.target)) return;
            if (fan.contains(e.target)) return;
            _close();
        }, { signal: sig });

        return ac;
    }

    window.bindBurger = bindBurger;

    // Voice sub-btn (Phase C of the my-sea invite/voice sprint). Direct
    // listener on #id_voice_btn: an ACTIVE click lazy-loads voice-mesh.js
    // then joins the mesh (first click) or toggles mute (subsequent). An
    // INACTIVE click is left to the delegated fan handler's 2-pulse flash.
    // No stopPropagation on active — the delegated handler then closes the
    // fan (its existing .active behaviour).
    function bindVoiceBtn() {
        var vbtn = document.getElementById('id_voice_btn');
        if (!vbtn) return;
        vbtn.addEventListener('click', function () {
            if (!vbtn.classList.contains('active')) return;  // → delegated flash
            var roomId = vbtn.getAttribute('data-room-id');
            if (!roomId) return;
            function act() {
                if (!window.VoiceRoom) return;
                if (!vbtn.dataset.inCall) {
                    vbtn.dataset.inCall = '1';
                    vbtn.classList.add('in-call');
                    window.VoiceRoom.join(roomId);
                } else {
                    var muted = window.VoiceRoom.toggleMute();
                    vbtn.classList.toggle('muted', muted);
                }
            }
            if (window.VoiceRoom) {
                act();
            } else {
                var s = document.createElement('script');
                s.src = '/static/apps/voice/voice-mesh.js';
                s.onload = act;
                document.head.appendChild(s);
            }
        });
    }
    window.bindVoiceBtn = bindVoiceBtn;

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            bindBurger();
            bindVoiceBtn();
        });
    } else {
        bindBurger();
        bindVoiceBtn();
    }
}());
