<?php
/**
 * File Path: includes/helpers/class-mbs-star-rating.php
 *
 * Star Rating Helper
 *
 * @package    My_Book_Showroom
 * @since      1.0.0
 */

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

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

	/**
	 * Render a read-only star rating.
	 *
	 * SV-03 fix: full production implementation replacing the stub.
	 * Rounds to nearest 0.5. Returns '' when $rating <= 0.
	 *
	 * @param float    $rating  Rating value (0–5 scale).
	 * @param int|null $count   Optional review count shown in parentheses.
	 * @return string           Accessible HTML, or '' when rating is 0 or below.
	 */
	public static function render_read_only( float $rating, ?int $count = null ): string {
		if ( $rating <= 0 ) {
			return '';
		}

		$max         = 5;
		$rounded     = min( $max, max( 0.0, round( $rating * 2 ) / 2 ) );
		$full_stars  = (int) floor( $rounded );
		$half_star   = ( $rounded - $full_stars ) >= 0.5;
		$empty_stars = $max - $full_stars - ( $half_star ? 1 : 0 );

		$stars_html  = str_repeat( '<span class="mbs-star mbs-star--full" aria-hidden="true">&#9733;</span>', $full_stars );
		if ( $half_star ) {
			$stars_html .= '<span class="mbs-star mbs-star--half" aria-hidden="true">&#11240;</span>';
		}
		$stars_html .= str_repeat( '<span class="mbs-star mbs-star--empty" aria-hidden="true">&#9734;</span>', $empty_stars );

		$score_text = number_format_i18n( $rounded, 1 );
		$count_html = ( null !== $count && $count > 0 )
			? ' <span class="mbs-rating__count">(' . number_format_i18n( $count ) . ')</span>'
			: '';

		$aria_label = sprintf(
			/* translators: 1: numeric rating e.g. "4.5", 2: max stars e.g. "5" */
			esc_attr__( 'Rated %1$s out of %2$s stars', 'my-book-showroom' ),
			$score_text,
			$max
		);

		return sprintf(
			'<span class="mbs-rating" role="img" aria-label="%s">%s<span class="mbs-rating__score">%s</span>%s</span>',
			$aria_label,
			$stars_html,
			esc_html( $score_text ),
			$count_html
		);
	}
}
