(function () {
    'use strict';

    function normalize(value) {
        return String(value || '')
            .toLowerCase()
            .normalize('NFKD')
            .replace(/[\u0300-\u036f]/g, '')
            .trim();
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('[data-erp-mega-search]').forEach(function (root) {
            var input = root.querySelector('[data-erp-mega-search-input]');
            var empty = root.querySelector('[data-erp-mega-search-empty]');
            if (!input) {
                return;
            }

            var links = Array.prototype.slice.call(root.querySelectorAll('[data-mega-search-item]'));
            var cards = Array.prototype.slice.call(root.querySelectorAll('[data-hr-section], .erp-mega-browse-card'));

            function applyFilter() {
                var needle = normalize(input.value);
                var visibleCount = 0;

                links.forEach(function (link) {
                    var hay = normalize(link.getAttribute('data-mega-search-text') || link.textContent);
                    var match = needle === '' || hay.indexOf(needle) !== -1;
                    link.hidden = !match;
                    link.classList.toggle('d-none', !match);
                    if (match) {
                        visibleCount += 1;
                    }
                });

                cards.forEach(function (card) {
                    var any = card.querySelectorAll('[data-mega-search-item]:not(.d-none):not([hidden])').length > 0;
                    card.hidden = needle !== '' && !any;
                    card.classList.toggle('d-none', needle !== '' && !any);
                });

                if (empty) {
                    empty.hidden = visibleCount > 0 || needle === '';
                }
            }

            input.addEventListener('input', applyFilter);
        });
    });
})();
