/**
 * Flavor Menu – Frontend Scripts
 * Hierarchical filtering with sectioned layout, subnav, and scroll-spy.
 */
(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.flavor-menu').forEach(initMenu);
    });

    function initMenu(menu) {
        var filterBtns = menu.querySelectorAll('.flavor-menu__filters .flavor-filter-btn');
        var flatGrid   = menu.querySelector('.flavor-menu__grid--flat');
        var subnav     = menu.querySelector('.flavor-menu__subnav');
        var hierarchy  = {};
        var scrollSpyActive = false;
        var scrollSpyRaf    = null;

        try { hierarchy = JSON.parse(menu.getAttribute('data-hierarchy') || '{}'); } catch(e) {}

        if (!filterBtns.length) return;

        // --- Main filter click ---
        filterBtns.forEach(function (btn) {
            btn.addEventListener('click', function () {
                var filter      = this.getAttribute('data-filter');
                var hasChildren = this.getAttribute('data-has-children') === '1';

                // Set active on main filter
                filterBtns.forEach(function (b) { b.classList.remove('is-active'); });
                this.classList.add('is-active');

                // Hide all sectioned views
                menu.querySelectorAll('.flavor-menu__sections').forEach(function (s) { s.style.display = 'none'; });
                stopScrollSpy();

                if (filter === '*') {
                    // Show flat grid, show all cards, hide subnav
                    showFlatGrid(flatGrid, '*');
                    hideSubnav(subnav);
                } else if (hasChildren && hierarchy[filter] && hierarchy[filter].length > 0) {
                    var sectionsEl = menu.querySelector('.flavor-menu__sections[data-parent="' + escAttr(filter) + '"]');
                    if (sectionsEl) {
                        // card-grid layout: show sectioned view
                        hideFlatGrid(flatGrid);
                        showSections(menu, filter);
                        buildSubnav(menu, subnav, filter, hierarchy[filter]);
                        startScrollSpy(menu, subnav, filter);
                    } else {
                        // horizontal layout: no sections exist — filter flat grid by parent slug
                        showFlatGrid(flatGrid, filter);
                        hideSubnav(subnav);
                    }
                } else {
                    // Simple parent without children: flat grid filtered
                    showFlatGrid(flatGrid, filter);
                    hideSubnav(subnav);
                }
            });
        });

        // Default filter
        var defaultFilter = menu.getAttribute('data-default-filter');
        if (defaultFilter) {
            var defaultBtn = menu.querySelector('.flavor-filter-btn[data-filter="' + escAttr(defaultFilter) + '"]');
            if (defaultBtn) { defaultBtn.click(); }
        }
    }

    // --- Flat grid ---
    function showFlatGrid(grid, filter) {
        grid.style.display = '';
        grid.querySelectorAll('.flavor-menu__card, .flavor-hcard').forEach(function (card) {
            var cats = card.getAttribute('data-categories') || '';
            if (filter === '*' || cats.indexOf(filter) !== -1) {
                card.classList.remove('is-hidden');
                card.classList.add('is-visible');
            } else {
                card.classList.remove('is-visible');
                card.classList.add('is-hidden');
            }
        });
    }

    function hideFlatGrid(grid) {
        grid.style.display = 'none';
    }

    // --- Sectioned view ---
    function showSections(menu, parentSlug) {
        var sections = menu.querySelector('.flavor-menu__sections[data-parent="' + escAttr(parentSlug) + '"]');
        if (sections) { sections.style.display = ''; }
    }

    // --- Hilfsfunktion: sicheres Escaping für HTML-Ausgabe ---
    function escHtml(str) {
        var d = document.createElement('div');
        d.appendChild(document.createTextNode(String(str)));
        return d.innerHTML;
    }

    // --- Hilfsfunktion: sicheres Escaping für CSS-Attribut-Selektoren ---
    function escAttr(str) {
        return String(str).replace(/["\\]/g, '\\$&');
    }

    // --- Subnav ---
    function buildSubnav(menu, subnav, parentSlug, children) {
        // Buttons sicher per DOM API erstellen – kein innerHTML mit Nutzerdaten
        subnav.innerHTML = '';

        var allBtn = document.createElement('button');
        allBtn.className = 'flavor-subnav-btn is-active';
        allBtn.setAttribute('data-sub', '*');
        allBtn.textContent = 'All';
        subnav.appendChild(allBtn);

        children.forEach(function (c) {
            var btn = document.createElement('button');
            btn.className = 'flavor-subnav-btn';
            btn.setAttribute('data-sub', c.slug);
            btn.textContent = c.name; // textContent escapt automatisch
            subnav.appendChild(btn);
        });

        subnav.style.display = '';

        // Subnav click: smooth scroll to section
        subnav.querySelectorAll('.flavor-subnav-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var sub = this.getAttribute('data-sub');
                setActiveSubnav(subnav, this);

                if (sub === '*') {
                    // Scroll to top of sectioned area
                    var sections = menu.querySelector('.flavor-menu__sections[data-parent="' + escAttr(parentSlug) + '"]');
                    if (sections) { sections.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
                } else {
                    var section = menu.querySelector('.flavor-menu__section[data-section="' + escAttr(sub) + '"]');
                    if (section) { section.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
                }
            });
        });
    }

    function hideSubnav(subnav) {
        if (subnav) {
            subnav.style.display = 'none';
            subnav.innerHTML = '';
        }
    }

    function setActiveSubnav(subnav, activeBtn) {
        subnav.querySelectorAll('.flavor-subnav-btn').forEach(function (b) { b.classList.remove('is-active'); });
        activeBtn.classList.add('is-active');
    }

    // --- Scroll spy ---
    var currentSpyCleanup = null;

    function startScrollSpy(menu, subnav, parentSlug) {
        stopScrollSpy();

        var onScroll = function () {
            var sections = menu.querySelectorAll('.flavor-menu__sections[data-parent="' + escAttr(parentSlug) + '"] .flavor-menu__section');
            if (!sections.length) return;

            var viewportTop = window.scrollY + 120; // offset for headers
            var activeSlug  = '*';

            sections.forEach(function (sec) {
                var rect = sec.getBoundingClientRect();
                var top  = rect.top + window.scrollY;
                if (viewportTop >= top) {
                    activeSlug = sec.getAttribute('data-section');
                }
            });

            // Update subnav
            var btns = subnav.querySelectorAll('.flavor-subnav-btn');
            btns.forEach(function (b) {
                b.classList.remove('is-active');
                if (b.getAttribute('data-sub') === activeSlug) {
                    b.classList.add('is-active');
                }
            });

            // If above all sections, activate "Alle"
            var anyActive = subnav.querySelector('.flavor-subnav-btn.is-active');
            if (!anyActive) {
                var allBtn = subnav.querySelector('.flavor-subnav-btn[data-sub="*"]');
                if (allBtn) { allBtn.classList.add('is-active'); }
            }
        };

        window.addEventListener('scroll', onScroll, { passive: true });
        currentSpyCleanup = function () { window.removeEventListener('scroll', onScroll); };
    }

    function stopScrollSpy() {
        if (currentSpyCleanup) {
            currentSpyCleanup();
            currentSpyCleanup = null;
        }
    }
})();
