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

class Jalpi_Element_Testimonial extends Jalpi_Element {
    public static function type(): string { return 'testimonial'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id       = sanitize_html_class( $node['id'] ?? '' );
        $content  = $node['content'] ?? [];
        $styles   = $node['styles']  ?? [];
        $text     = esc_html( $content['text']      ?? '' );
        $name     = esc_html( $content['name']      ?? '' );
        $role     = esc_html( $content['role']      ?? '' );
        $avatar   = esc_url(  $content['avatarUrl'] ?? '' );
        $rating   = min( 5, max( 0, intval( $content['rating'] ?? 5 ) ) );
        $a        = $renderer->get_css_attrs( $node );

        $stars = str_repeat( '<span class="jalpi-testi__star">&#9733;</span>', $rating )
               . str_repeat( '<span class="jalpi-testi__star jalpi-testi__star--empty">&#9733;</span>', 5 - $rating );

        $lazy       = Jalpi_Settings::get( 'performance', 'enable_lazy_loading', '1' ) ? ' loading="lazy"' : '';
        $avatar_html = $avatar ? '<img class="jalpi-testi__avatar" src="' . $avatar . '" alt="' . esc_attr( $name ) . '"' . $lazy . '>' : '<span class="jalpi-testi__avatar jalpi-testi__avatar--placeholder" aria-hidden="true"></span>';

        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{display:block;' . $renderer->styles_to_css( $styles ) . '}' );

        return '<div class="jalpi-el jalpi-testimonial jalpi-' . esc_attr( $id ) . $a['extra_cls'] . '"' . $a['id_attr'] . '>'
             /* translators: %s: star rating number */
             . '<div class="jalpi-testi__stars" aria-label="' . esc_attr( sprintf( __( '%s out of 5 stars', 'jalpi-page-builder' ), $rating ) ) . '">' . $stars . '</div>'
             . '<blockquote class="jalpi-testi__quote">' . $text . '</blockquote>'
             . '<footer class="jalpi-testi__author">'
             .   $avatar_html
             .   '<div class="jalpi-testi__author-info">'
             .     '<strong class="jalpi-testi__name">' . $name . '</strong>'
             .     ( $role ? '<span class="jalpi-testi__role">' . $role . '</span>' : '' )
             .   '</div>'
             . '</footer>'
             . '</div>';
    }
}
