(function () {
    'use strict';

    function normalize(value) {
        return String(value || '').toLocaleLowerCase().trim();
    }

    function initializeFilter(root) {
        var details = root.querySelector('details');
        var search = root.querySelector('[data-doctors-specialty-search]');
        var clear = root.querySelector('[data-doctors-specialty-clear]');
        var summary = root.querySelector('[data-doctors-specialty-summary]');
        var chips = root.querySelector('[data-doctors-specialty-chips]');
        var noResults = root.querySelector('[data-doctors-specialty-no-results]');
        var options = Array.prototype.slice.call(
            root.querySelectorAll('[data-doctors-specialty-option]')
        );
        var checkboxes = Array.prototype.slice.call(
            root.querySelectorAll('input[type="checkbox"][name="specialty_ids[]"]')
        );

        var allLabel = String(root.getAttribute('data-all-label') || 'All Specialties');
        var countLabel = String(root.getAttribute('data-count-label') || 'specialties selected');
        var noResultsLabel = String(
            root.getAttribute('data-no-results-label')
            || 'No specialties match the search.'
        );

        function selectedBoxes() {
            return checkboxes.filter(function (box) {
                return box.checked;
            });
        }

        function optionLabel(box) {
            var option = box.closest('[data-doctors-specialty-option]');
            var label = option ? option.querySelector('span') : null;
            return label ? String(label.textContent || '').trim() : String(box.value || '');
        }

        function renderSelection() {
            var selected = selectedBoxes();
            if (selected.length === 0) {
                summary.textContent = allLabel;
            } else if (selected.length === 1) {
                summary.textContent = optionLabel(selected[0]);
            } else {
                summary.textContent = selected.length + ' ' + countLabel;
            }

            chips.innerHTML = '';
            selected.slice(0, 4).forEach(function (box) {
                var chip = document.createElement('span');
                chip.textContent = optionLabel(box);
                chips.appendChild(chip);
            });
            if (selected.length > 4) {
                var more = document.createElement('span');
                more.textContent = '+' + (selected.length - 4);
                chips.appendChild(more);
            }

            var scope = document.querySelector('[data-doctors-filter-scope]');
            if (scope) {
                scope.textContent = summary.textContent;
            }
        }

        function applySearch() {
            var query = normalize(search ? search.value : '');
            var visible = 0;

            options.forEach(function (option) {
                var value = normalize(option.getAttribute('data-search-value'));
                var matches = query === '' || value.indexOf(query) !== -1;
                option.hidden = !matches;
                if (matches) visible += 1;
            });

            if (noResults) {
                var showNoResults = options.length > 0 && visible === 0;
                noResults.hidden = !showNoResults;
                noResults.textContent = showNoResults ? noResultsLabel : '';
            }
        }

        checkboxes.forEach(function (box) {
            box.addEventListener('change', renderSelection);
        });

        if (search) {
            search.addEventListener('input', applySearch);
            search.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    event.preventDefault();
                }
                if (event.key === 'Escape' && details) {
                    details.open = false;
                }
            });
        }

        if (clear) {
            clear.addEventListener('click', function () {
                checkboxes.forEach(function (box) {
                    box.checked = false;
                });
                if (search) search.value = '';
                applySearch();
                renderSelection();
            });
        }

        document.addEventListener('click', function (event) {
            if (
                details
                && details.open
                && !root.contains(event.target)
            ) {
                details.open = false;
            }
        });

        renderSelection();
        applySearch();

        window.setTimeout(function () {
            var checked = selectedBoxes().length;
            var gate = {
                availableOptions: options.length,
                selectedOptions: checked,
                searchReady: !!search,
                clearReady: !!clear,
                summaryReady: !!summary,
                formBindings: checkboxes.every(function (box) {
                    return box.name === 'specialty_ids[]' && box.value !== '';
                }),
                status: options.length > 0
                    && !!search
                    && !!clear
                    && !!summary
                    ? 'PASS'
                    : 'FAIL'
            };
            window.__DDB_DOCTORS_P13_SPECIALTY_FILTER_GATE__ = gate;
            document.documentElement.setAttribute(
                'data-doctors-p13-specialty-filter-gate',
                gate.status
            );
        }, 80);
    }

    function initialize() {
        var root = document.querySelector('[data-doctors-specialty-filter]');
        if (root) initializeFilter(root);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize, {once: true});
    } else {
        initialize();
    }
})();
