<?php
/**
 * File Path: layouts/class-mbs-layout-filter.php
 *
 * Filter Layout (PRO)
 *
 * Renders a grid of book cards with a live filter bar. Client-side filtering only.
 *
 * Gates: mbs_is_registered() + mbs_is_pro() (GP-T-1).
 * Output: single .mbs-wrapper (R4 rule).
 * Cover: MBS_Cover_Renderer::render() (R5 rule).
 *
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class MBS_Layout_Filter implements MBS_Layout { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	public function render( WP_Query $query, array $options = [] ): string {
		if ( ! mbs_is_registered() ) {
			return '';
		}

		if ( ! mbs_is_pro() ) {
			// SV-16: Return HTML comment only — no visible element to site visitors (GP-T-3).
			return '<!-- MBS: Filter layout requires PRO license -->';
		}

		if ( ! $query->have_posts() ) {
			return '<p>' . esc_html__( 'No books found.', 'my-book-showroom' ) . '</p>';
		}

		$posts = array();
		while ( $query->have_posts() ) {
			$query->the_post();
			$post_id = get_the_ID();

			// V2-A-004: get_the_terms() reads from WP_Query's pre-warmed term cache (no extra DB queries).
			$genres  = get_the_terms( $post_id, MBS_TAX_GENRE );
			$genres  = ( $genres && ! is_wp_error( $genres ) ) ? $genres : array();
			$series  = get_the_terms( $post_id, MBS_TAX_SERIES );
			$series  = ( $series && ! is_wp_error( $series ) ) ? $series : array();
			$authors = get_the_terms( $post_id, MBS_TAX_AUTHOR );
			$authors = ( $authors && ! is_wp_error( $authors ) ) ? $authors : array();

			$posts[] = array(
				'id'      => $post_id,
				'title'   => get_the_title(),
				'link'    => get_permalink(),
				'genres'  => $genres,
				'series'  => $series,
				'authors' => $authors,
			);
		}
		wp_reset_postdata();

		$filter_terms = array(
			'genre'  => array(),
			'series' => array(),
			'author' => array(),
		);

		foreach ( $posts as $book ) {
			foreach ( $book['genres'] as $term ) {
				$filter_terms['genre'][ $term->slug ] = $term->name;
			}
			foreach ( $book['series'] as $term ) {
				$filter_terms['series'][ $term->slug ] = $term->name;
			}
			foreach ( $book['authors'] as $term ) {
				$filter_terms['author'][ $term->slug ] = $term->name;
			}
		}

		$instance_id = 'mbs-filter-' . wp_unique_id();

		ob_start();
		?>
		<div class="mbs-wrapper">
		<div class="mbs-layout mbs-layout-filter" id="<?php echo esc_attr( $instance_id ); ?>">

			<div class="mbs-filter-bar" role="group" aria-label="<?php esc_attr_e( 'Filter books', 'my-book-showroom' ); ?>">
				<button type="button" class="mbs-filter-btn mbs-filter-active" data-filter="all" aria-pressed="true">
					<?php esc_html_e( 'All', 'my-book-showroom' ); ?>
				</button>

				<?php if ( ! empty( $filter_terms['genre'] ) ) : ?>
					<span class="mbs-filter-group-label"><?php esc_html_e( 'Genre', 'my-book-showroom' ); ?></span>
					<?php foreach ( $filter_terms['genre'] as $slug => $name ) : ?>
						<button type="button" class="mbs-filter-btn" data-filter="genre:<?php echo esc_attr( $slug ); ?>" aria-pressed="false">
							<?php echo esc_html( $name ); ?>
						</button>
					<?php endforeach; ?>
				<?php endif; ?>

				<?php if ( ! empty( $filter_terms['series'] ) ) : ?>
					<span class="mbs-filter-group-label"><?php esc_html_e( 'Series', 'my-book-showroom' ); ?></span>
					<?php foreach ( $filter_terms['series'] as $slug => $name ) : ?>
						<button type="button" class="mbs-filter-btn" data-filter="series:<?php echo esc_attr( $slug ); ?>" aria-pressed="false">
							<?php echo esc_html( $name ); ?>
						</button>
					<?php endforeach; ?>
				<?php endif; ?>

				<?php if ( ! empty( $filter_terms['author'] ) ) : ?>
					<span class="mbs-filter-group-label"><?php esc_html_e( 'Author', 'my-book-showroom' ); ?></span>
					<?php foreach ( $filter_terms['author'] as $slug => $name ) : ?>
						<button type="button" class="mbs-filter-btn" data-filter="author:<?php echo esc_attr( $slug ); ?>" aria-pressed="false">
							<?php echo esc_html( $name ); ?>
						</button>
					<?php endforeach; ?>
				<?php endif; ?>
			</div>

			<div class="mbs-filter-grid" aria-live="polite" aria-atomic="false">
				<?php foreach ( $posts as $book ) :
					$genre_slugs  = implode( ' ', wp_list_pluck( $book['genres'],  'slug' ) );
					$series_slugs = implode( ' ', wp_list_pluck( $book['series'],  'slug' ) );
					$author_slugs = implode( ' ', wp_list_pluck( $book['authors'], 'slug' ) );
					$author_name  = ! empty( $book['authors'] ) ? $book['authors'][0]->name : '';
				?>
					<div class="mbs-book-card mbs-filter-card"
					     data-genre="<?php echo esc_attr( $genre_slugs ); ?>"
					     data-series="<?php echo esc_attr( $series_slugs ); ?>"
					     data-author="<?php echo esc_attr( $author_slugs ); ?>">
						<?php echo MBS_Cover_Renderer::render( $book['id'] );  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML ?>
						<div class="mbs-book-info">
							<h3 class="mbs-book-title">
								<a href="<?php echo esc_url( $book['link'] ); ?>">
									<?php echo esc_html( $book['title'] ); ?>
								</a>
							</h3>
							<?php if ( $author_name ) : ?>
								<p class="mbs-book-author"><?php echo esc_html( $author_name ); ?></p>
							<?php endif; ?>
							<a class="mbs-view-book" href="<?php echo esc_url( $book['link'] ); ?>"><?php esc_html_e( 'View Book', 'my-book-showroom' ); ?></a>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<?php /* JS-toggled: shown by mbs-front.js filter logic when no books match the active filter.
			         display:none must remain inline — mbs-front.js reads the inline style to determine
			         the initial hidden state. Do not move to CSS. */ ?>
			<p class="mbs-filter-no-results" style="display:none;">
				<?php esc_html_e( 'No books match the selected filter.', 'my-book-showroom' ); ?>
			</p>
		</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
