(function () {
    'use strict';

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

    function initBookingCategoryFilter() {
        const list = document.querySelector('.sbs-services-list');
        const tabWrap = document.querySelector('.sbs-category-tabs');
        if (!list || !tabWrap) return;

        const headings = Array.from(list.querySelectorAll('.sbs-category-title'));
        if (!headings.length) return;

        headings.forEach((heading) => {
            const slug = String(heading.id || '').replace(/^cat-/, '');
            heading.dataset.yatoonCategory = slug;
            let node = heading.nextElementSibling;
            while (node && !node.classList.contains('sbs-category-title')) {
                if (node.classList.contains('sbs-service-item')) {
                    node.dataset.yatoonCategory = slug;
                }
                node = node.nextElementSibling;
            }
        });

        // The server renders All services as the initial state. Always normalize
        // to it on load so an older cached category script cannot leave cards hidden.
        let activeCategory = 'all';

        function setCategory(slug, moveFocus) {
            if (!slug) return;
            activeCategory = slug;
            tabWrap.dataset.yatoonActiveCategory = slug;
            const showAll = slug === 'all';
            headings.forEach((heading) => {
                const shouldHide = !showAll && heading.dataset.yatoonCategory !== slug;
                heading.toggleAttribute('hidden', shouldHide);
            });
            list.querySelectorAll('.sbs-service-item[data-yatoon-category]').forEach((card) => {
                const shouldHide = !showAll && card.dataset.yatoonCategory !== slug;
                card.toggleAttribute('hidden', shouldHide);
            });
            document.querySelectorAll('.sbs-cat-tab[data-cat], .sbs-cat-dropdown-item[data-cat]').forEach((button) => {
                const selected = button.dataset.cat === slug;
                button.classList.toggle('active', selected);
                button.setAttribute('aria-pressed', selected ? 'true' : 'false');
            });
            const selectedOverflow = Array.from(document.querySelectorAll('.sbs-cat-dropdown-item[data-cat]'))
                .find((button) => button.dataset.cat === slug);
            const moreButton = document.getElementById('sbs-cat-more-btn');
            if (moreButton) {
                const selectedLabel = selectedOverflow ? selectedOverflow.textContent.trim() : '';
                moreButton.dataset.selectedLabel = selectedLabel;
                moreButton.classList.toggle('has-active', Boolean(selectedLabel));
                moreButton.setAttribute(
                    'aria-label',
                    selectedLabel ? 'Selected category: ' + selectedLabel + '. Open more categories.' : 'More service categories'
                );
                if (moreButton.getAttribute('aria-expanded') !== 'true') {
                    moreButton.textContent = (selectedLabel || 'More') + ' ⌄';
                }
            }
            const label = document.getElementById('sbs-service-results-label');
            if (label) {
                const activeTab = Array.from(document.querySelectorAll('.sbs-cat-tab[data-cat], .sbs-cat-dropdown-item[data-cat]'))
                    .find((button) => button.dataset.cat === slug);
                label.textContent = activeTab ? activeTab.textContent.trim() : '';
            }
            if (moveFocus) {
                const visibleHeading = headings.find((heading) => !heading.hidden);
                if (visibleHeading) {
                    visibleHeading.setAttribute('tabindex', '-1');
                    visibleHeading.focus({ preventScroll: true });
                }
            }
        }

        if (!document.getElementById('sbs-service-results-label')) {
            const label = document.createElement('p');
            label.id = 'sbs-service-results-label';
            label.className = 'sbs-visually-hidden';
            label.setAttribute('aria-live', 'polite');
            list.parentNode.insertBefore(label, list);
        }

        document.addEventListener('click', (event) => {
            const button = event.target.closest('.sbs-cat-tab[data-cat]:not(.sbs-cat-more-btn), .sbs-cat-dropdown-item[data-cat]');
            if (!button) return;
            event.preventDefault();
            event.stopImmediatePropagation();
            const requestedCategory = button.dataset.cat;
            setCategory(button.classList.contains('active') && requestedCategory !== 'all' ? 'all' : requestedCategory, false);
            document.getElementById('sbs-cat-more-dropdown')?.classList.remove('open');
            document.getElementById('sbs-cat-more-btn')?.setAttribute('aria-expanded', 'false');
        }, true);

        const search = document.getElementById('sbs-service-search');
        if (search) {
            search.addEventListener('input', () => {
                if (search.value.trim()) {
                    headings.forEach((heading) => { heading.hidden = false; });
                    list.querySelectorAll('.sbs-service-item[data-yatoon-category]').forEach((card) => { card.hidden = false; });
                } else {
                    setCategory(activeCategory, false);
                }
            });
        }

        setCategory(activeCategory, false);
    }

    function initStepAccessibility() {
        const progress = document.getElementById('sbs-progress-bar');
        if (!progress) return;

        function sync() {
            progress.querySelectorAll('[data-step], .sbs-progress-step').forEach((step) => {
                const isActive = step.classList.contains('active') || step.classList.contains('current');
                if (isActive) step.setAttribute('aria-current', 'step');
                else step.removeAttribute('aria-current');
            });
        }

        sync();
        new MutationObserver(sync).observe(progress, { subtree: true, attributes: true, attributeFilter: ['class'] });
    }

    function initServiceDescriptionToggles() {
        document.addEventListener('click', (event) => {
            const button = event.target.closest('.sbs-read-more');
            if (!button) return;
            const wrap = button.closest('.sbs-service-desc-wrap');
            const shortDescription = wrap?.querySelector('.sbs-desc-short');
            const fullDescription = wrap?.querySelector('.sbs-desc-full');
            if (!wrap || !shortDescription || !fullDescription) return;

            event.preventDefault();
            event.stopPropagation();
            const willExpand = button.getAttribute('aria-expanded') !== 'true';
            wrap.classList.toggle('is-expanded', willExpand);
            shortDescription.hidden = willExpand;
            fullDescription.hidden = !willExpand;
            button.setAttribute('aria-expanded', willExpand ? 'true' : 'false');
            button.textContent = willExpand ? button.dataset.showLess : button.dataset.readMore;
        }, true);
    }

    function initDialogAccessibility() {
        let previousFocus = null;

        document.addEventListener('click', (event) => {
            const trigger = event.target.closest('button, a');
            if (trigger) previousFocus = trigger;
        }, true);

        const observer = new MutationObserver(() => {
            document.querySelectorAll('.ysp-overlay, .sbs-modal, [role="dialog"]').forEach((dialog) => {
                const visible = !dialog.hidden && dialog.getAttribute('aria-hidden') !== 'true' && getComputedStyle(dialog).display !== 'none';
                if (!visible || dialog.dataset.yatoonA11yOpen === '1') return;
                dialog.dataset.yatoonA11yOpen = '1';
                dialog.setAttribute('role', 'dialog');
                dialog.setAttribute('aria-modal', 'true');
                const close = dialog.querySelector('[data-ysp-close], .sbs-modal-close, [aria-label="Close"]');
                const focusTarget = close || dialog.querySelector('button, input, select, textarea, a[href]');
                if (focusTarget) window.setTimeout(() => focusTarget.focus(), 0);
            });
        });
        observer.observe(document.body, { subtree: true, attributes: true, attributeFilter: ['class', 'style', 'aria-hidden'] });

        document.addEventListener('keydown', (event) => {
            if (event.key !== 'Escape') return;
            const dialogs = Array.from(document.querySelectorAll('.ysp-overlay, .sbs-modal, [role="dialog"]')).filter((dialog) => {
                return !dialog.hidden && getComputedStyle(dialog).display !== 'none';
            });
            const dialog = dialogs[dialogs.length - 1];
            if (!dialog) return;
            const close = dialog.querySelector('[data-ysp-close], .sbs-modal-close, [aria-label="Close"]');
            if (close) {
                close.click();
                if (previousFocus && document.contains(previousFocus)) previousFocus.focus();
            }
        });
    }

    function initAdminEnhancements() {
        if (!document.body.classList.contains('yatoon-app-shell-on')) return;
        document.querySelectorAll('.wrap > h1').forEach((heading) => {
            if (!heading.parentElement.querySelector('.yatoon-page-kicker')) {
                const kicker = document.createElement('span');
                kicker.className = 'yatoon-page-kicker';
                kicker.textContent = 'Yatoon workspace';
                heading.parentElement.insertBefore(kicker, heading);
            }
        });
    }

    ready(() => {
        initBookingCategoryFilter();
        initServiceDescriptionToggles();
        initStepAccessibility();
        initDialogAccessibility();
        initAdminEnhancements();
    });
}());
