/* aieo/latest-posts-overlay — mobile slider bullet nav.
 * Only wires up below 768px (matches the CSS breakpoint).
 */
( function () {
    'use strict';

    var MOBILE_QUERY = '(max-width: 768px)';

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

        if ( ! window.matchMedia || ! window.matchMedia( MOBILE_QUERY ).matches ) {
            return;
        }

        var grid    = root.querySelector( '.aieo-latest-posts-overlay__grid' );
        var bullets = root.querySelector( '.aieo-latest-posts-overlay__bullets' );
        if ( ! grid || ! bullets ) { return; }

        var items = grid.querySelectorAll( '.aieo-latest-posts-overlay__item' );
        if ( items.length === 0 ) { return; }

        var current = 0;

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

        function paint() {
            var nodes = bullets.querySelectorAll( '.aieo-latest-posts-overlay__bullet' );
            nodes.forEach( function ( n, i ) {
                n.classList.toggle( 'is-active', i === current );
            } );
        }

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

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

        paint();
    }

    function boot() {
        document.querySelectorAll( '.aieo-latest-posts-overlay' ).forEach( init );
    }

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