<?php
/**
 * File Path: includes/blocks/class-mbs-block-tags.php
 *
 * Tags Block — Render
 *
 * PHP render_callback for the mbs/tags Gutenberg block.
 * Registered by MBS_Blocks_Registry via MBS_Block_Definitions::get().
 *
 * Displays all books carrying a specific mbs_tag taxonomy term.
 * Delegates entirely to MBS_Shortcode_Books::render() — zero duplicate
 * business logic. All PRO gates and query filters are inherited.
 *
 * Attributes:
 *   slug     (string) — Term slug for mbs_tag. Required.
 *   per_page (number) — Books per page. -1 = all. Default 20.
 *
 * License gate: mbs_is_registered() — returns empty string when false.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Blocks
 * @since      1.0.0
 */

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

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

	/**
	 * Render the Tags 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 '';
		}

		$slug = sanitize_title( $attributes['slug'] ?? '' );
		if ( '' === $slug ) {
			return '';
		}

		// Optionally render the term description above the book grid.
		$output = '';
		$term   = get_term_by( 'slug', $slug, MBS_TAX_TAG );
		if ( $term instanceof WP_Term && ! empty( $term->description ) ) {
			$output .= '<div class="mbs-wrapper mbs-tag-description">'
				. wp_kses_post( wpautop( $term->description ) )
				. '</div>';
		}

		// BLK-TAGS-1: Pass layout='grid' so books render in a grid.
		// Without this the shortcode defaults to mbs_get_setting('formatting',
		// 'default_layout', 'hero'), displaying books as full-width hero rows.
		//
		// BLK-TAGS-2: Suppress pagination in the editor preview.
		// ServerSideRender pagination links are real <a> tags; clicking them
		// navigates the editor page to the paginated URL, producing a REST 404.
		$in_editor = defined( 'REST_REQUEST' ) && REST_REQUEST;
		$output .= MBS_Shortcode_Books::render( array(
			'layout'          => 'grid',
			'tag'             => $slug,
			'limit'           => (int) ( $attributes['per_page'] ?? 20 ),
			'show_pagination' => ! $in_editor,
		) );

		return $output;
	}
}
