<?php
/**
 * File Path: includes/helpers/class-mbs-cover-image-builder.php
 *
 * Cover Image Builder
 *
 * Shared helper that renders a static cover image with the appropriate
 * CSS metaphor class. Used by all image-based cover strategies
 * (MBS_Cover_Strategy_Format, MBS_Cover_Strategy_Default,
 * MBS_Cover_Strategy_Placeholder). Not used by MBS_Cover_Strategy_Video,
 * which renders its own <video> markup.
 *
 * The CSS metaphor map translates a format type key into the modifier class
 * appended to .mbs-cover. Unknown types fall back to mbs-cover-default.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Helpers
 * @since      1.0.0
 */

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

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

	/**
	 * Format type → CSS modifier class map.
	 *
	 * Keys are the format type strings stored in mbs_format_rows.format.
	 * Any type not present here falls back to mbs-cover-default.
	 *
	 * @var array<string, string>
	 */
	private static array $type_class_map = array(
		'ebook'     => 'mbs-cover-ebook',
		'paperback' => 'mbs-cover-paperback',
		'hardcover' => 'mbs-cover-hardcover',
		'audiobook' => 'mbs-cover-audiobook',
		'boardbook' => 'mbs-cover-boardbook',
		'special'   => 'mbs-cover-special',
	);

	/**
	 * Render a static cover image with the appropriate CSS metaphor class.
	 *
	 * @param string $url      Full image URL. Must be a valid URL — not validated here;
	 *                         callers are responsible for confirming via wp_get_attachment_url().
	 * @param string $type     Format type key used to select a CSS modifier class.
	 *                         Unrecognized values fall back to mbs-cover-default.
	 * @param int    $post_id  Book post ID. Used to build accessible alt text (ADV-03).
	 *                         Pass 0 when no post context is available.
	 * @return string          Escaped HTML string.
	 */
	public static function render( string $url, string $type, int $post_id = 0 ): string {
		$modifier = self::$type_class_map[ $type ] ?? 'mbs-cover-default';
		$classes  = 'mbs-cover ' . $modifier;

		// Dynamic descriptive alt text for WCAG 2.1 AA compliance (ADV-03).
		$title = $post_id ? get_the_title( $post_id ) : '';
		$alt   = $title
			? esc_attr( $title ) . ' book cover'
			: 'Book cover image';

		return sprintf(
			'<div class="%s"><img src="%s" alt="%s" loading="lazy"></div>',
			esc_attr( $classes ),
			esc_url( $url ),
			$alt
		);
	}
}
