/* aieo/post-related-brands — slider behaviour.
 * Builds bullet nav, syncs current index with scroll position, and
 * optionally auto-rotates. One IIFE per block instance on the page.
 */
( function () {
    'use strict';

    function init( root ) {
        if ( root.dataset.aieoBrandsInit === '1' ) { return; }
        root.dataset.aieoBrandsInit = '1';

        var track   = root.querySelector( '.aieo-post-related-brands__track' );
        var bullets = root.querySelector( '.aieo-post-related-brands__bullets' );
        if ( ! track ) { return; }

        var items = track.querySelectorAll( '.aieo-post-related-brands__item' );
        if ( items.length < 2 ) { return; }

        var current = 0;
        var autoRotate = root.dataset.autoRotate === '1';
        var rotateMs   = parseInt( root.dataset.rotateMs, 10 ) || 4000;

        if ( bullets ) {
            bullets.innerHTML = '';
            items.forEach( function ( _, idx ) {
                var b = document.createElement( 'div' );
                b.className = 'aieo-post-related-brands__bullet';
                b.addEventListener( 'click', function () {
                    current = idx;
                    scrollTo( idx );
                    paint();
                } );
                bullets.appendChild( b );
            } );
        }

        function paint() {
            if ( ! bullets ) { return; }
            var nodes = bullets.querySelectorAll( '.aieo-post-related-brands__bullet' );
            nodes.forEach( function ( n, i ) {
                n.classList.toggle( 'is-active', i === current );
            } );
        }

        function scrollTo( idx ) {
            var target = items[ idx ];
            if ( ! target ) { return; }
            track.scrollTo( { left: target.offsetLeft, behavior: 'smooth' } );
        }

        track.addEventListener( 'scroll', function () {
            var closest = 0;
            var diff = Infinity;
            items.forEach( function ( it, i ) {
                var d = Math.abs( it.offsetLeft - track.scrollLeft );
                if ( d < diff ) { diff = d; closest = i; }
            } );
            if ( closest !== current ) {
                current = closest;
                paint();
            }
        }, { passive: true } );

        paint();

        if ( autoRotate ) {
            setInterval( function () {
                current = ( current + 1 ) % items.length;
                scrollTo( current );
                paint();
            }, rotateMs );
        }
    }

    function boot() {
        document.querySelectorAll( '.aieo-post-related-brands' ).forEach( init );
    }

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