<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Element_Star_Rating extends Jalpi_Element {
    public static function type(): string { return 'star-rating'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id      = sanitize_html_class( $node['id'] ?? '' );
        $content = $node['content'] ?? [];
        $styles  = $node['styles']  ?? [];
        $a       = $renderer->get_css_attrs( $node );

        $max       = max( 1, intval( $content['maxRating'] ?? 5 ) );
        $rating    = max( 0, min( $max, intval( $content['rating'] ?? 4 ) ) );
        $label     = esc_html( $content['label']     ?? '' );
        $color     = Jalpi_Sanitizer::sanitize_color( $content['starColor'] ?? '#f59e0b' ) ?: '#f59e0b';
        $size      = Jalpi_Sanitizer::sanitize_dimension( $content['size'] ?? '24px' ) ?: '24px';
        $align     = in_array( $content['align'] ?? 'left', [ 'left','center','right' ], true ) ? $content['align'] : 'left';

        $base_css = $renderer->styles_to_css( $styles );
        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{' . $base_css . '}' );

        $stars = '';
        for ( $i = 1; $i <= $max; $i++ ) {
            $filled  = $i <= $rating;
            $stars  .= '<span class="jalpi-star' . ( $filled ? ' is-filled' : '' ) . '" aria-hidden="true">'
                     . ( $filled ? '★' : '☆' )
                     . '</span>';
        }

        $aria = 'aria-label="' . esc_attr( $rating ) . ' out of ' . esc_attr( $max ) . ' stars"';
        $cls  = 'jalpi-el jalpi-star-rating jalpi-star-rating--' . esc_attr( $align ) . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        return '<div class="' . $cls . '"' . $a['id_attr'] . '>'
             . '<div class="jalpi-star-rating__stars" ' . $aria . ' role="img"'
             . ' style="font-size:' . esc_attr( $size ) . ';--jalpi-star-color:' . esc_attr( $color ) . ';">'
             . $stars . '</div>'
             . ( $label ? '<div class="jalpi-star-rating__label">' . $label . '</div>' : '' )
             . '</div>';
    }
}
