<?php
/**
 * The Template for displaying rating
 *
 * Renders the brand star rating with a single CSS-masked star shape (defined in
 * scss/.../ratings.scss) instead of inline SVG. Orange fill is driven by the
 * `--rating` custom property, giving true fractional fill.
 *
 * Expected $args:
 *   rating          float   0–5
 *   rating_count    int     shown as "(count)" for stars-only overall
 *   review_count    int     used in the "X of Y reviews" summary
 *   show_only_stars bool    stars without trailing "out of 5" text
 *   show_overall    bool    compact single-star summary / count
 *
 * @package Brandy
 * @version 2.0
 */

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

if ( ! \wc_review_ratings_enabled() ) {
	return;
}

$rating          = isset( $args['rating'] ) ? (float) $args['rating'] : 0;
$rating_count    = $args['rating_count'] ?? 0;
$review_count    = $args['review_count'] ?? 0;
$show_only_stars = ! empty( $args['show_only_stars'] );
$show_overall    = ! empty( $args['show_overall'] );

// Clamp to the 0–5 range the stars can express.
if ( $rating < 0 ) {
	$rating = 0;
} elseif ( $rating > 5 ) {
	$rating = 5;
}

if ( empty( $rating ) && empty( $rating_count ) ) {
	return;
}

// Compact overall summary renders a single decorative star (intentional design).
$is_compact = ( ! $show_only_stars && $show_overall );

$stars_classes = 'brandy-ratings__stars brandy-ratings__stars--rated';
if ( $is_compact ) {
	$stars_classes .= ' brandy-ratings__stars--single';
}

$aria_label = sprintf(
	/* translators: %s: numeric rating value out of five. */
	esc_attr__( 'Rated %s out of 5', 'brandy' ),
	$rating
);
?>

<div class="brandy-ratings" role="img" aria-label="<?php echo esc_attr( $aria_label ); ?>">
	<div class="<?php echo esc_attr( $stars_classes ); ?>" style="--rating: <?php echo esc_attr( $rating ); ?>;" aria-hidden="true"></div>

	<?php if ( $is_compact ) : ?>
		<p class="brandy-ratings__text" aria-hidden="true">
			<?php
			printf(
				// Translators: %1$s rating value, %2$s review number.
				( $review_count < 2 ) ? esc_html__( '%1$s of %2$s review', 'brandy' ) : esc_html__( '%1$s of %2$s reviews', 'brandy' ),
				esc_attr( $rating ),
				esc_attr( $review_count )
			);
			?>
		</p>
	<?php elseif ( ! $show_only_stars ) : ?>
		<p class="brandy-ratings__text" aria-hidden="true">
			<?php
			// Translators: %s rating value out of five.
			printf( esc_html__( '%s out of 5', 'brandy' ), esc_attr( $rating ) );
			?>
		</p>
	<?php elseif ( $show_overall ) : ?>
		<span class="brandy-ratings__text-overall" aria-hidden="true">(<?php echo esc_html( $rating_count ); ?>)</span>
	<?php endif; ?>
</div>
