// popout.js - Pop-out window management for OBS capture
(function () {
    'use strict';

    // Use event delegation so dynamically-created buttons work
    document.addEventListener('click', function (e) {
        const btn = e.target.closest('#popoutChartBtn');
        if (btn) {
            window.open('/PopoutChart', 'jongvoter-chart',
                'width=800,height=450,menubar=no,toolbar=no,status=no');
            return;
        }

        const sbBtn = e.target.closest('#popoutScoreboardBtn');
        if (sbBtn) {
            window.open('/PopoutScoreboard', 'jongvoter-scoreboard',
                'width=600,height=400,menubar=no,toolbar=no,status=no');
            return;
        }
    });

    // Listen for data requests from pop-out chart windows
    document.addEventListener('DOMContentLoaded', function () {
        try {
            const chartChannel = new BroadcastChannel('jongvoter-chart');
            chartChannel.onmessage = function (e) {
                if (e.data.type === 'requestData') {
                    // Re-call setData which triggers broadcast with combined state
                    if (typeof stats !== 'undefined' && typeof VoteChart !== 'undefined') {
                        VoteChart.setData(stats);
                        VoteChart.render();
                    }
                }
                if (e.data.type === 'popoutCombineUpdate') {
                    // Pop-out sent combine/trash changes — apply to main window
                    if (typeof VoteChart !== 'undefined') {
                        VoteChart.setCombinedState(
                            e.data.combinedGroups || {},
                            e.data.trashedCategories || []
                        );
                        if (typeof stats !== 'undefined') {
                            // Suppress broadcast so we don't echo back to pop-out
                            VoteChart.suppressBroadcast(true);
                            VoteChart.setData(stats);
                            VoteChart.suppressBroadcast(false);
                        }
                        VoteChart.render();
                    }
                }
                if (e.data.type === 'pollToggle') {
                    // Pop-out requested poll toggle
                    if (typeof window.togglePoll === 'function') {
                        window.togglePoll();
                    }
                }
                if (e.data.type === 'requestPollState') {
                    // Pop-out wants current poll state
                    chartChannel.postMessage({
                        type: 'pollStateUpdate',
                        isOpen: typeof isOpen !== 'undefined' ? isOpen : false
                    });
                }
            };
        } catch (e) { }
    });
})();
