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

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

class MBS_Layout_Card 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-card">';

		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 : '';
			$teaser      = trim( (string) get_post_meta( $post_id, 'mbs_teaser', true ) );

			echo '<div class="mbs-book-card">';
			echo '<div class="mbs-card-cover-wrap">';
			echo MBS_Cover_Renderer::render( $post_id ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted renderer returns pre-escaped HTML
			echo '<div class="mbs-card-overlay"><a class="mbs-card-overlay-btn" href="' . esc_url( get_permalink() ) . '">' . esc_html__( 'View Book', 'my-book-showroom' ) . '</a></div>';
			echo '</div>';
			// FE-017: Use BEM info-panel classes matching mbs-front-card-hover.css;
			// add author + teaser so card layout is visually distinct from grid layout.
			echo '<div class="mbs-book-card__info">';
			echo '<h3 class="mbs-book-card__title"><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></h3>';
			if ( $author_name ) {
				echo '<p class="mbs-book-card__author">' . esc_html( $author_name ) . '</p>';
			}
			if ( $teaser ) {
				echo '<p class="mbs-book-card__teaser">' . esc_html( wp_trim_words( $teaser, 20, '…' ) ) . '</p>';
			}
			echo '</div>';
			echo '</div>';
		}

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

		return ob_get_clean();
	}
}
