/**
 * @file assets/js/mbs-layout-filter.js
 * Client-side filtering for .mbs-layout-filter (PRO); event delegation on document, no jQuery, XSS-safe.
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global jQuery */

( function( $ ) {
	'use strict';

	/**
	 * Apply a filter to a single .mbs-layout-filter instance.
	 *
	 * @param {jQuery} $wrapper  The .mbs-layout-filter container.
	 * @param {string} filter    The data-filter value from the clicked button
	 *                           (e.g. "all", "genre:fantasy", "author:tolkien").
	 * @return {void}
	 */
	function applyFilter( $wrapper, filter ) {
		var $cards      = $wrapper.find( '.mbs-filter-card' );
		var $noResults  = $wrapper.find( '.mbs-filter-no-results' );
		var visibleCount = 0;

		if ( 'all' === filter ) {
			$cards.show();
			visibleCount = $cards.length;
		} else {
			// Parse "taxonomy:slug" — e.g. "genre:fantasy".
			var separatorIndex = filter.indexOf( ':' );
			if ( -1 === separatorIndex ) {
				// Malformed filter value — show all and bail.
				$cards.show();
				visibleCount = $cards.length;
			} else {
				var taxonomy = filter.slice( 0, separatorIndex );  // "genre"
				var slug     = filter.slice( separatorIndex + 1 ); // "fantasy"

				$cards.each( function() {
					var $card    = $( this );
					// data-genre / data-series / data-author each contain a
					// space-separated list of slugs (built by PHP implode( ' ', slugs )).
					var attrVal  = $card.attr( 'data-' + taxonomy ) || '';
					var slugList = attrVal.split( ' ' );

					if ( -1 !== $.inArray( slug, slugList ) ) {
						$card.show();
						visibleCount++;
					} else {
						$card.hide();
					}
				} );
			}
		}

		// Show/hide the "no results" message.
		if ( visibleCount === 0 ) {
			$noResults.show();
		} else {
			$noResults.hide();
		}
	}

	/**
	 * Update aria-pressed and .mbs-filter-active on the button bar.
	 *
	 * @param {jQuery} $bar      The .mbs-filter-bar container.
	 * @param {jQuery} $clicked  The button that was just activated.
	 * @return {void}
	 */
	function updateButtonState( $bar, $clicked ) {
		$bar.find( '.mbs-filter-btn' )
			.removeClass( 'mbs-filter-active' )
			.attr( 'aria-pressed', 'false' );

		$clicked
			.addClass( 'mbs-filter-active' )
			.attr( 'aria-pressed', 'true' );
	}

	// ── Event delegation — one handler covers all filter instances on the page ──

	$( document ).on( 'click', '.mbs-layout-filter .mbs-filter-btn', function() {
		var $btn     = $( this );
		var $wrapper = $btn.closest( '.mbs-layout-filter' );
		var $bar     = $btn.closest( '.mbs-filter-bar' );
		var filter   = $btn.attr( 'data-filter' ) || 'all';

		// Clicking the already-active button is a no-op.
		if ( $btn.hasClass( 'mbs-filter-active' ) ) {
			return;
		}

		updateButtonState( $bar, $btn );
		applyFilter( $wrapper, filter );
	} );

} )( jQuery );
