<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class StarRatingWidget extends WidgetBase {
	public function get_type(): string { return 'star_rating'; }
	public function get_title(): string { return 'Avaliação'; }
	public function get_icon(): string { return 'star'; }
	public function get_defaults(): array {
		return array( 'rating' => '5', 'max' => '5', 'align' => 'left', 'show_score' => '1' );
	}
	public function sanitize_settings( array $settings ): array {
		$rating = max( 0, min( 10, (float) ( $settings['rating'] ?? 5 ) ) );
		$max    = max( 1, min( 10, (int) ( $settings['max'] ?? 5 ) ) );
		$align  = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true ) ? (string) $settings['align'] : 'left';
		return array(
			'rating'     => (string) $rating,
			'max'        => (string) $max,
			'align'      => $align,
			'show_score' => empty( $settings['show_score'] ) || $settings['show_score'] === '0' ? '0' : '1',
		);
	}
	public function render( Node $node, array $context = array() ): string {
		$s      = $node->settings;
		$rating = (float) ( $s['rating'] ?? 5 );
		$max    = max( 1, (int) ( $s['max'] ?? 5 ) );
		$align  = esc_attr( (string) ( $s['align'] ?? 'left' ) );
		$stars  = '';
		for ( $i = 1; $i <= $max; $i++ ) {
			$full = $i <= (int) floor( $rating );
			$half = ! $full && ( $i - 0.5 ) <= $rating;
			$cls  = $full ? 'is-full' : ( $half ? 'is-half' : 'is-empty' );
			$stars .= '<span class="ab-star ' . $cls . '" aria-hidden="true">★</span>';
		}
		$score = ( $s['show_score'] ?? '1' ) !== '0'
			? '<span class="ab-star-score">' . esc_html( number_format_i18n( $rating, 1 ) ) . '</span>'
			: '';
		return '<div class="ab-star-rating" style="text-align:' . $align . '" role="img" aria-label="' . esc_attr( $rating . ' de ' . $max ) . '">' . $stars . $score . '</div>';
	}
}
