(function () {
    'use strict';
    var SCROLL_OFFSET = 120;
    var INTERSECT_THRESHOLD = 0.15;
    var existing = document.getElementById('cat-nav');
    if (existing) existing.remove();
    var slot = document.getElementById('cat-nav-slot');
    if (slot) slot.innerHTML = '';
    var sections = document.querySelectorAll('.category-section[data-category]');
    if (!sections.length) return;
    var cats = [];
    var navCats = [];
    sections.forEach(function (sec) {
        var id = sec.getAttribute('data-category');
        var titleEl = sec.querySelector('.category-title');
        var name = titleEl ? titleEl.textContent.trim() : 'Category';
        var productCount = sec.querySelectorAll('.product-card').length;
        var showInNav = sec.getAttribute('data-nav') !== '0';
        var catObj = { id: id, name: name, count: productCount, el: sec };
        cats.push(catObj);
        if (showInNav) navCats.push(catObj);
    });
    if (!navCats.length) return;
    var nav = document.createElement('div');
    nav.id = 'cat-nav';
    var inner = document.createElement('div');
    inner.id = 'cat-nav-inner';
    inner.appendChild(makePill('all', 'All', sumCounts(cats), true));
    inner.appendChild(makeDivider());
    navCats.forEach(function (cat) {
        inner.appendChild(makePill(cat.id, cat.name, cat.count, false));
    });
    nav.appendChild(inner);
    var slot = document.getElementById('cat-nav-slot');
    if (slot) {
        slot.appendChild(nav);
    } else {
        var pageHome = document.getElementById('page-home');
        if (pageHome) {
            pageHome.insertBefore(nav, pageHome.firstChild);
        }
    }
    var scrolled = false;
    window.addEventListener('scroll', function () {
        var s = window.scrollY > 10;
        if (s !== scrolled) {
            scrolled = s;
            nav.classList.toggle('scrolled', s);
        }
    }, { passive: true });

    function checkOverflow() {
        nav.classList.toggle('can-scroll-left', inner.scrollLeft > 10);
        nav.classList.toggle('can-scroll-right', inner.scrollLeft < inner.scrollWidth - inner.clientWidth - 10);
    }
    inner.addEventListener('scroll', checkOverflow, { passive: true });
    window.addEventListener('resize', checkOverflow);
    setTimeout(checkOverflow, 100);

    inner.addEventListener('click', function (e) {
        var pill = e.target.closest('.cn-pill');
        if (!pill) return;
        e.preventDefault();
        var target = pill.getAttribute('data-cat');
        inner.querySelectorAll('.cn-pill').forEach(function (p) {
            p.classList.remove('cn-active');
        });
        pill.classList.add('cn-active');
        if (target === 'all') {
            var firstSection = sections[0];
            if (firstSection) {
                smoothScrollTo(firstSection, SCROLL_OFFSET);
            } else {
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
            return;
        }
        var sec = document.querySelector('.category-section[data-category="' + target + '"]');
        if (sec) {
            smoothScrollTo(sec, SCROLL_OFFSET);
            sec.classList.remove('cn-highlight');
            void sec.offsetWidth;
            sec.classList.add('cn-highlight');
            setTimeout(function () { sec.classList.remove('cn-highlight'); }, 800);
        }
    });
    if ('IntersectionObserver' in window) {
        var observer = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    setActivePill(entry.target.getAttribute('data-category'));
                }
            });
        }, {
            rootMargin: '-' + SCROLL_OFFSET + 'px 0px -50% 0px',
            threshold: INTERSECT_THRESHOLD
        });
        sections.forEach(function (sec) { observer.observe(sec); });
    }
    function makePill(catId, label, count, isActive) {
        var a = document.createElement('a');
        a.className = 'cn-pill' + (isActive ? ' cn-active' : '');
        a.href = '#cat-' + catId;
        a.setAttribute('data-cat', catId);

        if (catId === 'all') {
            var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            svg.setAttribute('viewBox', '0 0 24 24');
            svg.innerHTML = '<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>';
            a.appendChild(svg);
        }
        var span = document.createElement('span');
        span.textContent = label;
        a.appendChild(span);
        if (count > 0) {
            var badge = document.createElement('span');
            badge.className = 'cn-count';
            badge.textContent = count;
            a.appendChild(badge);
        }
        return a;
    }
    function makeDivider() {
        var d = document.createElement('span');
        d.className = 'cn-divider';
        return d;
    }
    function sumCounts(arr) {
        var total = 0;
        arr.forEach(function (c) { total += c.count; });
        return total;
    }
    function setActivePill(catId) {
        inner.querySelectorAll('.cn-pill').forEach(function (p) {
            p.classList.toggle('cn-active', p.getAttribute('data-cat') === catId);
        });
        var active = inner.querySelector('.cn-pill.cn-active');
        if (active) {
            var pillLeft = active.offsetLeft;
            var pillWidth = active.offsetWidth;
            var stripWidth = inner.offsetWidth;
            var target = pillLeft - (stripWidth / 2) + (pillWidth / 2);
            inner.scrollTo({ left: target, behavior: 'smooth' });
        }
    }
    function smoothScrollTo(el, offset) {
        var rect = el.getBoundingClientRect();
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        window.scrollTo({ top: Math.max(0, rect.top + scrollTop - offset), behavior: 'smooth' });
    }
})();
