<?php
/**
 * File Path: includes/layouts/class-mbs-layout-list.php
 *
 * List Layout
 *
 * FREE list layout for book archives and shortcodes.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Layout_List 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 '';   // ← LICENSE GATE (GP-T-1)
		}

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

		ob_start();
		echo '<div class="mbs-wrapper">';
		echo '<div class="mbs-layout mbs-layout-list">';

		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 query).
			$_mbs_author_terms = get_the_terms( $post_id, MBS_TAX_AUTHOR );
			$author_name       = ( $_mbs_author_terms && ! is_wp_error( $_mbs_author_terms ) ) ? $_mbs_author_terms[0]->name : '';
			// FE-016: mbs_teaser is the book tagline — render it independently,
			// not as a fallback label for the generic WP excerpt.
			$teaser      = trim( (string) get_post_meta( $post_id, 'mbs_teaser', true ) );

			echo '<div class="mbs-book-list-item">';
			echo MBS_Cover_Renderer::render( $post_id ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
			echo '<div class="mbs-book-info">';
			echo '<h3 class="mbs-book-title"><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></h3>';
			if ( $author_name ) {
				echo '<p class="mbs-book-author">' . esc_html( $author_name ) . '</p>';
			}
			// FE-016: Show teaser as a dedicated element when set; fall back to
			// WP excerpt otherwise so the info column is never left blank.
			if ( $teaser ) {
				echo '<p class="mbs-book-teaser">' . esc_html( wp_trim_words( $teaser, 25 ) ) . '</p>';
			} else {
				$_mbs_li_excerpt = wp_trim_words( get_the_excerpt(), 25 );
				if ( $_mbs_li_excerpt ) {
					echo '<p class="mbs-book-excerpt">' . esc_html( $_mbs_li_excerpt ) . '</p>';
				}
			}
			echo '<a class="mbs-view-book" href="' . esc_url( get_permalink() ) . '">' . esc_html__( 'View Book', 'my-book-showroom' ) . '</a>';
			echo '</div>';
			echo '</div>';
		}

		echo '</div>';
		echo '</div>';
		wp_reset_postdata();

		return ob_get_clean();
	}
}
