(function () {
    'use strict';

    function normalize(value) {
        var text = String(value || '').toLocaleLowerCase('pt');
        return typeof text.normalize === 'function'
            ? text.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
            : text;
    }

    function formatMoney(value) {
        return new Intl.NumberFormat('pt-PT', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(Number(value) || 0) + ' MT';
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('[data-rmbz-music-dashboard]').forEach(function (dashboard) {
            var search = dashboard.querySelector('[data-mg-search]');
            var buttons = Array.prototype.slice.call(dashboard.querySelectorAll('[data-mg-filter]'));
            var tracks = Array.prototype.slice.call(dashboard.querySelectorAll('[data-mg-track]'));
            var count = dashboard.querySelector('[data-mg-count]');
            var empty = dashboard.querySelector('[data-mg-empty]');
            var activeFilter = 'all';

            function refresh() {
                var term = normalize(search ? search.value : '');
                var visible = 0;
                tracks.forEach(function (track) {
                    var haystack = normalize(track.getAttribute('data-search'));
                    var flags = String(track.getAttribute('data-flags') || '').split(/\s+/);
                    var show = (!term || haystack.indexOf(term) !== -1)
                        && (activeFilter === 'all' || flags.indexOf(activeFilter) !== -1);
                    track.hidden = !show;
                    if (show) visible++;
                });
                if (count) count.textContent = visible + ' resultado(s)';
                if (empty) empty.hidden = visible !== 0;
            }

            if (search) search.addEventListener('input', refresh);
            buttons.forEach(function (button) {
                button.addEventListener('click', function () {
                    activeFilter = button.getAttribute('data-mg-filter') || 'all';
                    buttons.forEach(function (item) {
                        var selected = item === button;
                        item.classList.toggle('on', selected);
                        item.setAttribute('aria-pressed', selected ? 'true' : 'false');
                    });
                    refresh();
                });
            });

            dashboard.querySelectorAll('.rmbz-mg-details').forEach(function (details) {
                details.addEventListener('toggle', function () {
                    if (!details.open) return;
                    dashboard.querySelectorAll('.rmbz-mg-details[open]').forEach(function (other) {
                        if (other !== details) other.open = false;
                    });
                });
            });

            var dialog = dashboard.querySelector('[data-mg-boost-dialog]');
            var form = dashboard.querySelector('[data-mg-boost-form]');
            if (dialog && form) {
                var musicInput = form.querySelector('[data-mg-boost-music-id]');
                var title = form.querySelector('[data-mg-boost-title]');
                var state = form.querySelector('[data-mg-boost-state]');
                var total = form.querySelector('[data-mg-boost-total]');
                var balanceStatus = form.querySelector('[data-mg-boost-balance-status]');
                var submit = form.querySelector('[data-mg-boost-submit]');
                var durationInputs = Array.prototype.slice.call(form.querySelectorAll('input[name="boost_days"]'));
                var balance = Number(form.getAttribute('data-balance') || 0);

                function updatePrice() {
                    var selected = durationInputs.find(function (input) { return input.checked; });
                    var cost = selected ? Number(selected.getAttribute('data-cost') || 0) : 0;
                    durationInputs.forEach(function (input) {
                        var card = input.closest('.rmbz-mg-duration');
                        if (card) card.classList.toggle('selected', input.checked);
                    });
                    if (total) total.textContent = formatMoney(cost);
                    var enough = balance + 0.0001 >= cost;
                    if (balanceStatus) {
                        balanceStatus.textContent = enough ? 'Saldo suficiente' : 'Saldo insuficiente';
                        balanceStatus.classList.toggle('ok', enough);
                    }
                    if (submit) submit.disabled = !enough;
                }

                function closeDialog() {
                    if (typeof dialog.close === 'function') dialog.close();
                    else dialog.removeAttribute('open');
                }

                dashboard.querySelectorAll('[data-mg-boost-open]').forEach(function (opener) {
                    opener.addEventListener('click', function () {
                        if (musicInput) musicInput.value = opener.getAttribute('data-music-id') || '';
                        if (title) title.textContent = opener.getAttribute('data-music-title') || '';
                        if (state) {
                            state.textContent = opener.getAttribute('data-boost-active') === '1'
                                ? 'A nova campanha soma outro período de destaque a esta música.'
                                : 'Escolhe o período. A campanha começa imediatamente após o débito.';
                        }
                        updatePrice();
                        if (typeof dialog.showModal === 'function') dialog.showModal();
                        else dialog.setAttribute('open', 'open');
                    });
                });

                form.querySelectorAll('[data-mg-boost-close]').forEach(function (button) {
                    button.addEventListener('click', closeDialog);
                });
                durationInputs.forEach(function (input) {
                    input.addEventListener('change', updatePrice);
                });
                dialog.addEventListener('click', function (event) {
                    if (event.target === dialog) closeDialog();
                });
                form.addEventListener('submit', function () {
                    if (!submit || submit.disabled) return;
                    submit.disabled = true;
                    submit.innerHTML = '<span class="ms">progress_activity</span>A ativar...';
                });
                updatePrice();
            }

            refresh();
        });
    });
}());