/*jshint esversion: 6 */
(function () {
    "use strict";

    // Variables injected by meeting.blade.php:
    // signalingURL, userInfo { username, meetingId }, moderator

    // Bootstrap is bundled inside tabler.min.js as window.tabler.bootstrap
    const BS = (window.tabler && window.tabler.bootstrap) || window.bootstrap;

    let isForceMuted = false;
    let fmSocket = null;

    // ─── Toast helper ────────────────────────────────────────────────────────────

    function showToast(message, type) {
        const container = document.getElementById('toastContainer');
        if (!container) return;

        const id = 'fm-toast-' + Date.now();
        const bg = type === 'warning' ? 'bg-warning text-dark' : 'bg-info text-white';

        container.insertAdjacentHTML('beforeend', `
            <div id="${id}" class="toast align-items-center ${bg} border-0" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="d-flex">
                    <div class="toast-body fw-semibold">${message}</div>
                    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `);

        const el = document.getElementById(id);
        const toast = new BS.Toast(el, { delay: 4000 });
        toast.show();
        el.addEventListener('hidden.bs.toast', () => el.remove());
    }

    // ─── Mic button enforcement ───────────────────────────────────────────────────

    function applyMicCapture() {
        const toggleMic = document.getElementById('toggleMic');
        if (!toggleMic) return;

        toggleMic.addEventListener('click', function (e) {
            if (!isForceMuted) return;
            // Capture phase: stop meeting.js from handling this click
            e.stopImmediatePropagation();
            showToast('You are muted by the host and cannot unmute yourself.', 'warning');
        }, true); // capture = true ensures this runs before meeting.js bubble handlers
    }

    // ─── Force mute / unmute handlers ────────────────────────────────────────────

    function onForceMuted() {
        isForceMuted = true;

        const toggleMic = document.getElementById('toggleMic');
        if (toggleMic) {
            // If currently unmuted (mic icon visible), programmatically click to mute
            if (toggleMic.querySelector('.bi-mic') && !toggleMic.querySelector('.bi-mic-mute')) {
                toggleMic.click();
            }
            toggleMic.style.opacity = '0.5';
            toggleMic.title = 'Muted by host';
        }

        showToast('You have been muted by the host.', 'warning');
    }

    function onForceUnmuted() {
        isForceMuted = false;

        const toggleMic = document.getElementById('toggleMic');
        if (toggleMic) {
            toggleMic.style.opacity = '';
            toggleMic.title = 'Mute/Unmute Mic';
        }

        showToast('You can now unmute your microphone.', 'info');
    }

    // ─── Moderator panel ─────────────────────────────────────────────────────────

    function buildModeratorPanel() {
        const panel = document.createElement('div');
        panel.id = 'fm-panel';
        panel.innerHTML = `
            <div class="card" style="
                position: fixed;
                bottom: 90px;
                right: 16px;
                width: 240px;
                z-index: 1050;
                display: none;
            ">
                <div class="card-header d-flex align-items-center justify-content-between py-2">
                    <strong style="font-size:0.85rem;">Force Mute Controls</strong>
                    <button type="button" id="fm-panel-toggle" class="btn btn-sm btn-ghost-secondary p-1">
                        <i class="bi bi-chevron-down"></i>
                    </button>
                </div>
                <div id="fm-panel-body" class="card-body p-2" style="max-height:220px; overflow-y:auto;">
                    <p class="text-muted small text-center m-0">No participants yet.</p>
                </div>
            </div>
        `;
        document.body.appendChild(panel);

        // Toggle collapse
        document.getElementById('fm-panel-toggle').addEventListener('click', function () {
            const body = document.getElementById('fm-panel-body');
            const icon = this.querySelector('i');
            if (body.style.display === 'none') {
                body.style.display = '';
                icon.className = 'bi bi-chevron-down';
            } else {
                body.style.display = 'none';
                icon.className = 'bi bi-chevron-up';
            }
        });

        return panel;
    }

    function renderParticipants(participants, forceMuted, meetingId) {
        const panel = document.getElementById('fm-panel');
        if (!panel) return;

        panel.style.display = '';

        const body = document.getElementById('fm-panel-body');
        const others = participants.filter(u => u !== userInfo.username);

        if (others.length === 0) {
            body.innerHTML = '<p class="text-muted small text-center m-0">No other participants.</p>';
            return;
        }

        body.innerHTML = others.map(username => {
            const muted = forceMuted.includes(username);
            return `
                <div class="d-flex align-items-center justify-content-between mb-1" style="font-size:0.82rem;">
                    <span class="text-truncate me-2" style="max-width:130px;" title="${username}">
                        ${username}
                        ${muted ? '<i class="bi bi-mic-mute text-danger ms-1" title="Force muted"></i>' : ''}
                    </span>
                    ${muted
                        ? `<button class="btn btn-sm btn-success py-0 px-2 fm-unmute-btn" data-username="${username}" data-meeting="${meetingId}" title="Allow to unmute">Unmute</button>`
                        : `<button class="btn btn-sm btn-danger py-0 px-2 fm-mute-btn" data-username="${username}" data-meeting="${meetingId}" title="Force mute">Mute</button>`
                    }
                </div>
            `;
        }).join('');

        // Bind buttons
        body.querySelectorAll('.fm-mute-btn').forEach(btn => {
            btn.addEventListener('click', function () {
                fmSocket.emit('forceMute', {
                    targetUsername: this.dataset.username,
                    meetingId: this.dataset.meeting
                });
            });
        });

        body.querySelectorAll('.fm-unmute-btn').forEach(btn => {
            btn.addEventListener('click', function () {
                fmSocket.emit('forceUnmute', {
                    targetUsername: this.dataset.username,
                    meetingId: this.dataset.meeting
                });
            });
        });
    }

    // ─── Leave / End meeting (moderator only) ────────────────────────────────────

    let bypassLeaveIntercept = false;

    function bindLeaveIntercept(isModerator) {
        if (!isModerator) return;

        const leaveBtn  = document.getElementById('leave');
        const leaveModal = document.getElementById('modal-leave-options');
        if (!leaveBtn || !leaveModal) return;

        function getModal() {
            return BS.Modal.getOrCreateInstance(leaveModal);
        }

        // Capture phase — intercept before meeting.js handles the click
        leaveBtn.addEventListener('click', function (e) {
            if (bypassLeaveIntercept) return;
            e.stopImmediatePropagation();
            e.preventDefault();
            getModal().show();
        }, true);

        document.getElementById('btn-just-leave').addEventListener('click', function () {
            getModal().hide();
            leaveModal.addEventListener('hidden.bs.modal', function onHidden() {
                leaveModal.removeEventListener('hidden.bs.modal', onHidden);
                bypassLeaveIntercept = true;
                leaveBtn.click();
            });
        });

        document.getElementById('btn-leave-end').addEventListener('click', function () {
            fmSocket.emit('endMeeting', { meetingId: userInfo.meetingId });
            getModal().hide();
            leaveModal.addEventListener('hidden.bs.modal', function onHidden() {
                leaveModal.removeEventListener('hidden.bs.modal', onHidden);
                bypassLeaveIntercept = true;
                leaveBtn.click();
            });
        });
    }

    // ─── Init ─────────────────────────────────────────────────────────────────────

    function init() {
        applyMicCapture();

        const isModerator = moderator === '1' || moderator === true || moderator === 'true';

        if (isModerator) {
            buildModeratorPanel();
            bindLeaveIntercept(isModerator);
        }

        fmSocket = io(signalingURL + '/force-mute', {
            rejectUnauthorized: false // allow self-signed certs in dev
        });

        fmSocket.on('connect', function () {
            fmSocket.emit('joinRoom', {
                meetingId: userInfo.meetingId,
                username: userInfo.username,
                isModerator: isModerator
            });
        });

        // Received by everyone: check if it's for me
        fmSocket.on('forceMuteTarget', function (data) {
            if (data.username === userInfo.username) {
                onForceMuted();
            }
        });

        fmSocket.on('forceUnmuteTarget', function (data) {
            if (data.username === userInfo.username) {
                onForceUnmuted();
            }
        });

        // Server re-confirms force-mute state on reconnect
        fmSocket.on('youAreForceMuted', function () {
            onForceMuted();
        });

        // Moderator receives updated participant list
        if (isModerator) {
            fmSocket.on('participantList', function (data) {
                renderParticipants(data.participants, data.forceMuted, userInfo.meetingId);
            });
        }

        // Host ended the meeting — redirect all participants
        fmSocket.on('meetingEnded', function () {
            if (isModerator) return; // moderator is already leaving via the leave button
            showToast('The meeting has been ended by the host.', 'warning');
            setTimeout(function () {
                window.location.href = '/dashboard';
            }, 2000);
        });
    }

    // Wait for meeting.js to finish setting up the DOM before attaching capture listener
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
