/* Comportamentos exclusivos da página dashboard.php */

(function(){
    function dashPairingModal(){ return document.getElementById('dashboardPairingModal'); }
    function dashShowPairing(){
        var modal = dashPairingModal();
        if (!modal) return;
        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modal).show();
        } else {
            modal.style.display = 'block';
            modal.classList.add('show');
            modal.removeAttribute('aria-hidden');
            modal.setAttribute('aria-modal', 'true');
            modal.setAttribute('role', 'dialog');
            document.body.classList.add('modal-open');
            document.body.style.overflow = 'hidden';
            var old = document.querySelector('.dashboard-pairing-backdrop');
            if (old) old.remove();
            var backdrop = document.createElement('div');
            backdrop.className = 'modal-backdrop fade show dashboard-pairing-backdrop';
            document.body.appendChild(backdrop);
        }
        setTimeout(function(){ var input = document.getElementById('dashboardPairingCode'); if (input) input.focus(); }, 120);
    }
    function dashHidePairing(){
        var modal = dashPairingModal();
        if (!modal) return;
        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modal).hide();
            return;
        }
        modal.classList.remove('show');
        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
        modal.removeAttribute('aria-modal');
        modal.removeAttribute('role');
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.querySelectorAll('.dashboard-pairing-backdrop').forEach(function(el){ el.remove(); });
    }

    function dashPad(n){
        return String(n).padStart(2, '0');
    }

    function dashDefaultDate(){
        var dt = new Date();
        dt.setDate(dt.getDate() + 30);
        return dt.getFullYear() + '-' + dashPad(dt.getMonth() + 1) + '-' + dashPad(dt.getDate()) + 'T' + dashPad(dt.getHours()) + ':' + dashPad(dt.getMinutes());
    }

    function dashGetModal(){
        return document.getElementById('dashboardActivateModal');
    }

    function dashRemoveBackdrop(){
        document.querySelectorAll('.modal-backdrop.dashboard-activate-backdrop').forEach(function(el){
            el.parentNode.removeChild(el);
        });
    }

    function dashShowModal(){
        var modal = dashGetModal();
        if (!modal) return;

        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modal).show();
            return;
        }

        dashRemoveBackdrop();
        modal.style.display = 'block';
        modal.removeAttribute('aria-hidden');
        modal.setAttribute('aria-modal', 'true');
        modal.setAttribute('role', 'dialog');
        modal.classList.add('show');
        document.body.classList.add('modal-open');
        document.body.style.overflow = 'hidden';
        document.body.style.paddingRight = '0px';

        var backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show dashboard-activate-backdrop';
        document.body.appendChild(backdrop);
    }

    function dashHideModal(){
        var modal = dashGetModal();
        if (!modal) return;

        if (window.bootstrap && window.bootstrap.Modal) {
            var instance = window.bootstrap.Modal.getOrCreateInstance(modal);
            instance.hide();
            return;
        }

        modal.classList.remove('show');
        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
        modal.removeAttribute('aria-modal');
        modal.removeAttribute('role');
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.body.style.paddingRight = '';
        dashRemoveBackdrop();
    }

    function dashOpenActivate(btn){
        var mac = btn.getAttribute('data-mac') || '';
        var macInput = document.getElementById('dashActivateMac');
        var valInput = document.getElementById('dashActivateValidade');
        var m3uInput = document.querySelector('#dashboardActivateForm input[name="m3u_url"]');

        if (macInput) macInput.value = mac;
        if (valInput && !valInput.value) valInput.value = dashDefaultDate();

        dashShowModal();
        setTimeout(function(){
            if (m3uInput) m3uInput.focus();
        }, 150);
    }

    document.addEventListener('click', function(e){
        var pairingBtn = e.target.closest('#btnDashboardPairing');
        if (pairingBtn) {
            e.preventDefault();
            e.stopPropagation();
            dashShowPairing();
            return;
        }
        if (e.target.closest('#dashboardPairingModal [data-bs-dismiss="modal"]') || e.target.classList.contains('dashboard-pairing-backdrop')) {
            e.preventDefault();
            dashHidePairing();
            return;
        }

        var activateBtn = e.target.closest('.btn-dashboard-activate');
        if (activateBtn) {
            e.preventDefault();
            e.stopPropagation();
            dashOpenActivate(activateBtn);
            return;
        }

        if (e.target.closest('#dashboardActivateModal [data-bs-dismiss="modal"]') || e.target.classList.contains('dashboard-activate-backdrop')) {
            e.preventDefault();
            dashHideModal();
        }
    }, true);

    document.addEventListener('keydown', function(e){
        if (e.key === 'Escape') { dashHidePairing(); dashHideModal(); }
    });

    document.addEventListener('DOMContentLoaded', function(){
        var codeInput = document.getElementById('dashboardPairingCode');
        if (codeInput) {
            codeInput.addEventListener('input', function(){ this.value = this.value.replace(/\D/g, '').slice(0, 4); });
            var codeModal = document.getElementById('dashboardPairingModal');
            if (codeModal) codeModal.addEventListener('shown.bs.modal', function(){ codeInput.focus(); });
        }

        var runtime = document.getElementById('dashboardRuntime');
        var autoMac = runtime ? String(runtime.dataset.autoMac || '') : '';
        if (autoMac) {
            var autoButton = document.createElement('button');
            autoButton.setAttribute('data-mac', autoMac);
            dashOpenActivate(autoButton);
        }

        var form = document.getElementById('dashboardActivateForm');
        if (!form) return;

        form.addEventListener('submit', function(){
            var submit = form.querySelector('button[type="submit"]');
            if (submit) {
                submit.disabled = true;
                submit.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Ativando...';
            }
        });
    });
})();
