/**
 * File Path: assets/js/mbs-author-directory.js
 *
 * My Book Showroom — Author Directory A-Z Filter
 *
 * Client-side letter filter for [mbs_author_directory] shortcode.
 * When a letter button is clicked, only author cards whose data-initial
 * attribute matches that letter remain visible. Clicking 'All' restores
 * all cards. No framework dependency.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function () {
	'use strict';

	/**
	 * Initialize a single author directory widget.
	 *
	 * @param {HTMLElement} wrapper  The .mbs-author-directory element.
	 */
	function initDirectory( wrapper ) {
		var nav = wrapper.querySelector( '.mbs-author-filter' );
		if ( ! nav ) {
			return; // show_filter=false — nothing to wire up
		}

		var cards = wrapper.querySelectorAll( '.mbs-author-card' );

		function applyFilter( letter ) {
			cards.forEach( function ( card ) {
				if ( letter === 'all' || card.dataset.initial === letter ) {
					card.hidden = false;
				} else {
					card.hidden = true;
				}
			} );
		}

		nav.addEventListener( 'click', function ( e ) {
			var btn = e.target.closest( '.mbs-author-filter-btn' );
			if ( ! btn ) {
				return;
			}

			// Update active state.
			nav.querySelectorAll( '.mbs-author-filter-btn' ).forEach( function ( b ) {
				b.classList.remove( 'is-active' );
			} );
			btn.classList.add( 'is-active' );

			applyFilter( btn.dataset.filter );
		} );
	}

	// Initialize every directory on the page — supports multiple shortcodes
	// on the same page without interference.
	document.querySelectorAll( '.mbs-author-directory' ).forEach( initDirectory );

} )();
