/*
 * Category bar restored from the 4.2.3 interaction model.
 * It is intentionally isolated from the later 4.3.x category observers.
 */
(function () {
    'use strict';

    window.__yatoonCategoryBar423 = true;
    var isOpen = false;
    var lastTouch = 0;

    function getParts() {
        return {
            wrap: document.querySelector('.sbs-category-tabs'),
            more: document.getElementById('sbs-cat-more-btn'),
            menu: document.getElementById('sbs-cat-more-dropdown')
        };
    }

    function rebuildMenu(hiddenTabs, menu) {
        var wanted = hiddenTabs.map(function (tab) {
            return (tab.getAttribute('data-cat') || '') + '|' + (tab.textContent || '').trim();
        }).join('||');
        if (menu.getAttribute('data-yatoon-items') === wanted && menu.children.length === hiddenTabs.length) return;

        menu.innerHTML = '';
        hiddenTabs.forEach(function (tab) {
            var item = document.createElement('button');
            item.type = 'button';
            item.className = 'sbs-cat-dropdown-item' + (tab.classList.contains('active') ? ' active' : '');
            item.setAttribute('data-cat', tab.getAttribute('data-cat') || '');
            item.setAttribute('aria-pressed', tab.classList.contains('active') ? 'true' : 'false');
            item.textContent = (tab.textContent || '').trim();
            menu.appendChild(item);
        });
        menu.setAttribute('data-yatoon-items', wanted);
    }

    function adjustTabs() {
        var parts = getParts();
        if (!parts.wrap || !parts.more || !parts.menu) return;
        var wasOpen = isOpen;

        var tabs = Array.prototype.slice.call(parts.wrap.querySelectorAll('.sbs-cat-tab[data-cat]:not(.sbs-cat-more-btn)'));
        var visibleCount = window.innerWidth >= 769 ? 4 : (window.innerWidth >= 390 ? 3 : 2);
        visibleCount = Math.max(1, Math.min(visibleCount, tabs.length));

        tabs.forEach(function (tab, index) {
            var hidden = index >= visibleCount;
            tab.classList.toggle('sbs-cat-overflow', hidden);
            tab.style.setProperty('display', hidden ? 'none' : 'inline-flex', 'important');
            tab.style.fontSize = '';
            tab.style.padding = '';
        });

        var hiddenTabs = tabs.slice(visibleCount);
        rebuildMenu(hiddenTabs, parts.menu);

        var needed = hiddenTabs.length > 0;
        parts.more.classList.toggle('sbs-more-needed', needed);
        parts.more.style.setProperty('display', needed ? 'inline-flex' : 'none', 'important');
        if (wasOpen && needed) {
            setOpen(true);
        } else {
            parts.more.textContent = 'More \u2304';
            parts.more.setAttribute('aria-expanded', 'false');
            parts.menu.classList.remove('open');
            isOpen = false;
        }
    }

    function positionMenu() {
        var parts = getParts();
        if (!parts.more || !parts.menu) return;
        var host = document.querySelector('.sbs-step-1') || document.querySelector('.sbs-booking-main') || document.body;
        var buttonRect = parts.more.getBoundingClientRect();
        var hostRect = host.getBoundingClientRect();
        var width = Math.min(220, Math.max(180, host.clientWidth - 12));
        var left = buttonRect.right - hostRect.left - width;
        left = Math.max(6, Math.min(left, host.clientWidth - width - 6));

        parts.menu.style.setProperty('position', 'absolute', 'important');
        parts.menu.style.setProperty('top', (buttonRect.bottom - hostRect.top + 6) + 'px', 'important');
        parts.menu.style.setProperty('left', left + 'px', 'important');
        parts.menu.style.setProperty('width', width + 'px', 'important');
    }

    function setOpen(open) {
        var parts = getParts();
        if (!parts.more || !parts.menu || !parts.menu.children.length) return;
        if (open) positionMenu();
        parts.menu.classList.toggle('open', open);
        parts.more.textContent = open ? 'More \u2303' : 'More \u2304';
        parts.more.setAttribute('aria-expanded', open ? 'true' : 'false');
        isOpen = open;
    }

    function choose(item) {
        var slug = item.getAttribute('data-cat') || '';
        document.querySelectorAll('.sbs-cat-tab, .sbs-cat-dropdown-item').forEach(function (node) {
            node.classList.remove('active');
            node.setAttribute('aria-pressed', 'false');
        });
        document.querySelectorAll('.sbs-category-tabs .sbs-cat-tab[data-cat]').forEach(function (tab) {
            if ((tab.getAttribute('data-cat') || '') === slug) {
                tab.classList.add('active');
                tab.setAttribute('aria-pressed', 'true');
            }
        });
        item.classList.add('active');
        item.setAttribute('aria-pressed', 'true');
        var more = document.getElementById('sbs-cat-more-btn');
        if (more) more.classList.add('has-active');
        setOpen(false);

        var heading = document.getElementById('cat-' + slug);
        if (heading) {
            var nav = document.querySelector('.sbs-category-tabs-wrap');
            var offset = (nav ? nav.getBoundingClientRect().height : 0) + 12;
            var top = Math.max(0, heading.getBoundingClientRect().top + window.pageYOffset - offset);
            try { window.scrollTo({ top: top, behavior: 'smooth' }); }
            catch (error) { window.scrollTo(0, top); }
        }
    }

    function chooseVisible(tab) {
        var slug = tab.getAttribute('data-cat') || '';
        document.querySelectorAll('.sbs-cat-tab, .sbs-cat-dropdown-item').forEach(function (node) {
            node.classList.remove('active');
            node.setAttribute('aria-pressed', 'false');
        });
        var more = document.getElementById('sbs-cat-more-btn');
        if (more) more.classList.remove('has-active');
        tab.classList.add('active');
        tab.setAttribute('aria-pressed', 'true');
        setOpen(false);

        var heading = document.getElementById('cat-' + slug);
        if (heading) {
            var nav = document.querySelector('.sbs-category-tabs-wrap');
            var offset = (nav ? nav.getBoundingClientRect().height : 0) + 12;
            var top = Math.max(0, heading.getBoundingClientRect().top + window.pageYOffset - offset);
            try { window.scrollTo({ top: top, behavior: 'smooth' }); }
            catch (error) { window.scrollTo(0, top); }
        }
    }

    function controlFrom(target) {
        if (!target || !target.closest) return null;
        return target.closest('#sbs-cat-more-btn, #sbs-cat-more-dropdown .sbs-cat-dropdown-item[data-cat], .sbs-category-tabs .sbs-cat-tab[data-cat]');
    }

    function activate(event, fromTouch) {
        var control = controlFrom(event.target);
        if (!control) return false;
        if (event.cancelable) event.preventDefault();
        event.stopImmediatePropagation();
        if (fromTouch) lastTouch = Date.now();

        if (control.id === 'sbs-cat-more-btn') setOpen(!isOpen);
        else if (control.closest('#sbs-cat-more-dropdown')) choose(control);
        else chooseVisible(control);
        return true;
    }

    document.addEventListener('touchend', function (event) {
        activate(event, true);
    }, { capture: true, passive: false });

    document.addEventListener('click', function (event) {
        var control = controlFrom(event.target);
        if (control && Date.now() - lastTouch < 800) {
            if (event.cancelable) event.preventDefault();
            event.stopImmediatePropagation();
            return;
        }
        if (activate(event, false)) return;
        if (isOpen && (!event.target.closest || !event.target.closest('#sbs-cat-more-dropdown'))) setOpen(false);
    }, true);

    document.addEventListener('pointerover', function (event) {
        var control = controlFrom(event.target);
        if (control && control.id !== 'sbs-cat-more-btn') control.classList.add('is-hover');
    }, true);

    document.addEventListener('pointerout', function (event) {
        var control = controlFrom(event.target);
        if (control && (!event.relatedTarget || !control.contains(event.relatedTarget))) {
            control.classList.remove('is-hover');
        }
    }, true);

    document.addEventListener('focusin', function (event) {
        var control = controlFrom(event.target);
        if (control && control.id !== 'sbs-cat-more-btn') control.classList.add('is-hover');
    });

    document.addEventListener('focusout', function (event) {
        var control = controlFrom(event.target);
        if (control) control.classList.remove('is-hover');
    });

    function boot() {
        adjustTabs();
        window.setTimeout(adjustTabs, 250);
    }
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true });
    else boot();

    window.addEventListener('resize', function () {
        window.clearTimeout(window.__yatoonCategory423Resize);
        window.__yatoonCategory423Resize = window.setTimeout(adjustTabs, 100);
    });
}());
