/**
 * File Path: assets/js/mbs-layout-slider.js
 *
 * Slider Layout — prev/next button handler.
 *
 * Reads data-slider on each button to find its carousel track by ID,
 * then scrolls by one slide width on click.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */
( function () {
	'use strict';

	function getTrack( btn ) {
		var slider = document.getElementById( btn.getAttribute( 'data-slider' ) );
		return slider ? slider.querySelector( '.mbs-slider-track' ) : null;
	}

	function slideWidth( track ) {
		var slide = track.querySelector( '.mbs-slider-slide' );
		return slide ? ( slide.offsetWidth + 16 ) : 240;
	}

	function smoothScroll( track, delta ) {
		// Use scrollLeft for broad browser compatibility.
		// CSS scroll-behavior:smooth on the track animates it where supported.
		track.scrollLeft += delta;
	}

	function initSliders() {
		var prevBtns = document.querySelectorAll( '.mbs-slider-prev[data-slider]' );
		var nextBtns = document.querySelectorAll( '.mbs-slider-next[data-slider]' );

		prevBtns.forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				var track = getTrack( btn );
				if ( track ) { smoothScroll( track, -slideWidth( track ) ); }
			} );
		} );

		nextBtns.forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				var track = getTrack( btn );
				if ( track ) { smoothScroll( track, slideWidth( track ) ); }
			} );
		} );
	}

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