/**
 * aieo/brand-azindex view script.
 *
 * - Smooth-scrolls clicks on the A-Z chips to their letter section,
 *   accounting for sticky-header offset.
 * - Scrollspy: highlights the chip whose section is currently in view.
 * - Keyboard A-Z: pressing a letter key (when no input is focused) jumps
 *   to that letter's section, even if it's empty.
 * - Surfaces "(N)" count on the active chip via the .aieo-azbar__active-meta
 *   live region.
 */
(function () {
    'use strict';

    function init(root) {
        if (root.__aieoAzInit) return;
        root.__aieoAzInit = true;

        var bar       = root.querySelector('.aieo-azbar');
        var chips     = root.querySelectorAll('.aieo-azbar__chip');
        var sections  = root.querySelectorAll('.aieo-letter');
        var meta      = root.querySelector('.aieo-azbar__active-meta');
        if (!bar || chips.length === 0 || sections.length === 0) return;

        // Height occupied by anything pinned to the top of the viewport above the
        // bar: the WP admin bar (fixed) + the theme's global sticky header
        // (header.wp-block-template-part, position:sticky). Measured live so it's
        // correct on desktop AND mobile (the header is a different height each).
        var headerOffset = function () {
            var off = 0;
            var ab = document.getElementById('wpadminbar');
            if (ab && getComputedStyle(ab).position === 'fixed') { off += ab.getBoundingClientRect().height; }
            var hdr = document.querySelector('header.wp-block-template-part');
            if (hdr) {
                var pos = getComputedStyle(hdr).position;
                if (pos === 'sticky' || pos === 'fixed') { off += hdr.getBoundingClientRect().height; }
            }
            return Math.round(off);
        };

        // Glue the sticky bar directly UNDER the sticky header (CSS reads the var).
        var applyStickyTop = function () { bar.style.setProperty('--aieo-az-top', headerOffset() + 'px'); };
        applyStickyTop();
        var rzT;
        window.addEventListener('resize', function () { clearTimeout(rzT); rzT = setTimeout(applyStickyTop, 120); });

        var stickyOffset = function () {
            // Scroll-jump target must clear the sticky header AND this sticky bar.
            var barH = bar.getBoundingClientRect().height || 0;
            return Math.round(barH) + headerOffset() + 8;
        };

        // Smooth scroll on chip click; jump even for empty letters so deep-links work.
        chips.forEach(function (chip) {
            chip.addEventListener('click', function (e) {
                var letter = chip.getAttribute('data-letter');
                if (!letter) return;
                var target = root.querySelector('#letter-' + cssEscape(letter));
                if (!target) return;
                e.preventDefault();
                var top = target.getBoundingClientRect().top + window.pageYOffset - stickyOffset();
                window.scrollTo({ top: top, behavior: 'smooth' });
                history.replaceState(null, '', '#letter-' + letter);
                setActive(letter);
            });
        });

        // Scrollspy via IntersectionObserver — observe the section heading row;
        // the topmost intersecting one wins.
        if ('IntersectionObserver' in window) {
            var visible = {};
            var io = new IntersectionObserver(function (entries) {
                entries.forEach(function (e) {
                    var L = e.target.getAttribute('data-letter');
                    visible[L] = e.isIntersecting;
                });
                var pick = null;
                for (var i = 0; i < sections.length; i++) {
                    var L = sections[i].getAttribute('data-letter');
                    if (visible[L] && sections[i].getAttribute('data-empty') !== '1') { pick = L; break; }
                }
                if (pick) setActive(pick);
            }, { rootMargin: '-' + (stickyOffset() + 40) + 'px 0px -60% 0px', threshold: 0 });
            sections.forEach(function (s) { io.observe(s); });
        }

        // Keyboard A-Z jump.
        document.addEventListener('keydown', function (e) {
            if (e.metaKey || e.ctrlKey || e.altKey) return;
            var tag = (e.target && e.target.tagName) || '';
            if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (e.target && e.target.isContentEditable)) return;
            var key = (e.key || '').toUpperCase();
            if (key.length !== 1 || !/[A-Z]/.test(key)) return;
            var target = root.querySelector('#letter-' + key);
            if (!target) return;
            var top = target.getBoundingClientRect().top + window.pageYOffset - stickyOffset();
            window.scrollTo({ top: top, behavior: 'smooth' });
            history.replaceState(null, '', '#letter-' + key);
            setActive(key);
        });

        var lastActive = null;

        function setActive(letter) {
            if (letter === lastActive) { return; }
            lastActive = letter;

            var activeChip = null;
            chips.forEach(function (c) {
                var match = c.getAttribute('data-letter') === letter;
                c.classList.toggle('is-active', match);
                if (match) {
                    c.setAttribute('aria-current', 'true');
                    activeChip = c;
                } else {
                    c.removeAttribute('aria-current');
                }
            });

            if (activeChip) {
                ensureChipInView(activeChip);
            }
            if (meta) {
                var n = activeChip ? parseInt(activeChip.getAttribute('data-count') || '0', 10) : 0;
                meta.textContent = n > 0 ? letter + ' (' + n + ')' : letter;
            }
        }

        // On mobile the bar is a horizontally-scrolling strip
        // (overflow-x: auto, scroll-snap-x). When the scrollspy advances
        // the active letter to a chip that's outside the viewport, scroll
        // the bar so the active chip is centered. No-op on desktop where
        // the list wraps and isn't scrollable.
        function ensureChipInView(chip) {
            var list = chip.closest('.aieo-azbar__list');
            if (!list) { return; }
            // Only scroll if the list overflows (mobile / narrow viewport).
            if (list.scrollWidth <= list.clientWidth + 1) { return; }

            var chipCenter = chip.offsetLeft + (chip.offsetWidth / 2);
            var targetLeft = Math.max(0, chipCenter - (list.clientWidth / 2));
            // Skip noise scrolls when we're already within a few px of the target.
            if (Math.abs(list.scrollLeft - targetLeft) < 4) { return; }
            list.scrollTo({ left: targetLeft, behavior: 'smooth' });
        }

        function cssEscape(s) {
            if (window.CSS && window.CSS.escape) return window.CSS.escape(s);
            return String(s).replace(/([^\w-])/g, '\\$1');
        }

        // On load: honour deep-link to a #letter-X anchor.
        if (location.hash && /^#letter-/.test(location.hash)) {
            var L = location.hash.substring('#letter-'.length).toUpperCase();
            if (L.length === 1) setActive(L);
        }
    }

    function boot() {
        document.querySelectorAll('.aieo-brand-azindex').forEach(init);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
