(function () {
    'use strict';

    var searchEl = document.getElementById('maca-guest-strings-search');
    var groupEl = document.getElementById('maca-guest-strings-group');
    var customEl = document.getElementById('maca-guest-strings-custom-only');

    if (!searchEl) {
        return;
    }

    function applyFilters() {
        var q = (searchEl.value || '').trim().toLowerCase();
        var group = groupEl ? groupEl.value : '';
        var customOnly = customEl && customEl.checked;
        var groups = document.querySelectorAll('.maca-guest-strings-group');

        groups.forEach(function (details) {
            var groupName = details.getAttribute('data-group') || '';
            var groupMatch = !group || group === groupName;
            var visibleRows = 0;
            var rows = details.querySelectorAll('.maca-guest-strings-row');

            rows.forEach(function (row) {
                var hay = row.getAttribute('data-search') || '';
                var isCustom = row.getAttribute('data-custom') === '1';
                var match =
                    groupMatch &&
                    (!q || hay.indexOf(q) !== -1) &&
                    (!customOnly || isCustom);

                row.style.display = match ? '' : 'none';
                if (match) {
                    visibleRows += 1;
                }
            });

            details.style.display = visibleRows > 0 ? '' : 'none';
        });
    }

    searchEl.addEventListener('input', applyFilters);
    if (groupEl) {
        groupEl.addEventListener('change', applyFilters);
    }
    if (customEl) {
        customEl.addEventListener('change', applyFilters);
    }
})();
