/**
 * aieo/brand-slider view script.
 *
 * Wraps the server-rendered <ul.aieo-brand-slider__track> with a vanilla
 * scroll-snap carousel. No third-party library — relies on CSS scroll-snap
 * + IntersectionObserver to manage prev/next button enabled state.
 *
 * The server already pre-renders the first N brands; this script only
 * handles interactivity (no AJAX needed for the default render path —
 * the AJAX bundle endpoint is reserved for blocks that defer hydration
 * entirely, which we may use in the future).
 */
(function () {
    'use strict';

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

        var viewport = root.querySelector('.aieo-brand-slider__viewport');
        var track    = root.querySelector('.aieo-brand-slider__track');
        var prev     = root.querySelector('.aieo-brand-slider__nav--prev');
        var next     = root.querySelector('.aieo-brand-slider__nav--next');
        if (!viewport || !track) return;

        var slides = Array.prototype.slice.call(track.children);
        if (slides.length === 0) return;

        var scrollByOne = function (dir) {
            var slide = slides[0];
            if (!slide) return;
            var step = slide.getBoundingClientRect().width + getGap();
            track.scrollBy({ left: dir * step, behavior: 'smooth' });
        };

        function getGap() {
            var cs = window.getComputedStyle(track);
            var g = parseFloat(cs.gap || cs.columnGap || '0');
            return isNaN(g) ? 0 : g;
        }

        if (prev) {
            prev.addEventListener('click', function () { scrollByOne(-1); });
        }
        if (next) {
            next.addEventListener('click', function () { scrollByOne(1); });
        }

        // Manage prev/next visibility based on scroll position.
        function updateNavState() {
            var atStart = track.scrollLeft <= 2;
            var atEnd   = track.scrollLeft + track.clientWidth >= track.scrollWidth - 2;
            if (prev) {
                if (atStart) { prev.setAttribute('hidden', ''); }
                else { prev.removeAttribute('hidden'); }
            }
            if (next) {
                if (atEnd) { next.setAttribute('hidden', ''); }
                else { next.removeAttribute('hidden'); }
            }
        }

        track.addEventListener('scroll', throttle(updateNavState, 80), { passive: true });
        window.addEventListener('resize', throttle(updateNavState, 120));
        updateNavState();

        // Keyboard support: left/right arrow keys when slider has focus.
        viewport.tabIndex = viewport.tabIndex || 0;
        viewport.addEventListener('keydown', function (e) {
            if (e.key === 'ArrowRight') { e.preventDefault(); scrollByOne(1); }
            if (e.key === 'ArrowLeft')  { e.preventDefault(); scrollByOne(-1); }
        });

        function throttle(fn, wait) {
            var t = 0, lastArgs = null;
            return function () {
                lastArgs = arguments;
                if (t) return;
                t = setTimeout(function () { t = 0; fn.apply(null, lastArgs); }, wait);
            };
        }
    }

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

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