<?php
/**
 * File Path: includes/blocks/class-mbs-block-term-list.php
 *
 * Term List Block — Render
 *
 * PHP render_callback for the mbs/term-list Gutenberg block.
 * Registered by MBS_Blocks_Registry::register_term_list_block().
 *
 * Displays all terms from a selected MBS taxonomy (authors, series, genres,
 * or tags) as a responsive linked grid. Each term links to its archive page.
 * Equivalent to MBT's "All Terms in Taxonomy" block.
 *
 * Attributes:
 *   taxonomy   (string)  — MBS taxonomy slug; one of MBS_TAX_AUTHOR, MBS_TAX_SERIES,
 *                          MBS_TAX_GENRE, MBS_TAX_TAG. Default: MBS_TAX_AUTHOR.
 *   columns    (number)  — Grid columns (1–6). Default: 3.
 *   show_count (boolean) — Show book count per term. Default: false.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Blocks
 * @since      1.0.0
 */

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

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

	/**
	 * Render the Term List block.
	 *
	 * @param array $attributes Block attributes from the editor.
	 * @return string Rendered HTML.
	 */
	public static function render( array $attributes ): string {
		if ( ! mbs_is_registered() ) {
			return '';
		}

		$valid_taxonomies = array( MBS_TAX_AUTHOR, MBS_TAX_SERIES, MBS_TAX_GENRE, MBS_TAX_TAG );

		$taxonomy   = sanitize_key( $attributes['taxonomy'] ?? MBS_TAX_AUTHOR );
		$columns    = max( 1, min( 6, (int) ( $attributes['columns'] ?? 3 ) ) );
		$show_count = ! empty( $attributes['show_count'] );

		// Reject any taxonomy slug not belonging to MBS.
		if ( ! in_array( $taxonomy, $valid_taxonomies, true ) ) {
			$taxonomy = MBS_TAX_AUTHOR;
		}

		$terms = get_terms( array(
			'taxonomy'   => $taxonomy,
			'hide_empty' => true,
			'orderby'    => 'name',
			'order'      => 'ASC',
		) );

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return '';
		}

		ob_start();
		?>
		<div class="mbs-term-list mbs-term-list--cols-<?php echo esc_attr( $columns ); ?>"
		     style="--mbs-term-cols: <?php echo esc_attr( $columns ); ?>;">
			<?php foreach ( $terms as $term ) :
				$link = get_term_link( $term );
				if ( is_wp_error( $link ) ) {
					continue;
				}
			?>
				<a class="mbs-term-list__item" href="<?php echo esc_url( $link ); ?>">
					<span class="mbs-term-list__name"><?php echo esc_html( $term->name ); ?></span>
					<?php if ( $show_count ) : ?>
						<span class="mbs-term-list__count">
							<?php echo esc_html(
								sprintf(
									/* translators: %d: number of books */
									_n( '%d book', '%d books', (int) $term->count, 'my-book-showroom' ),
									(int) $term->count
								)
							); ?>
						</span>
					<?php endif; ?>
				</a>
			<?php endforeach; ?>
		</div>
		<?php
		return ob_get_clean();
	}
}
