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

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

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id       = sanitize_html_class( $node['id'] ?? '' );
        $content  = $node['content']  ?? [];
        $styles   = $node['styles']   ?? [];
        $settings = $node['settings'] ?? [];
        $items    = (array) ( $content['items'] ?? [] );
        $layout   = $content['layout'] ?? 'grid';
        $cols     = max( 1, min( 4, intval( $content['cols'] ?? 3 ) ) );
        $a        = $renderer->get_css_attrs( $node );

        $st  = function( $k, $d = '' ) use ( $settings ) { return isset( $settings[ $k ] ) && $settings[ $k ] !== '' ? $settings[ $k ] : $d; };
        $esc = 'esc_attr';
        $px  = function( $v ) { return $v; };

        $prefix   = '.jalpi-el.jalpi-' . $id;
        $base_css = $renderer->styles_to_css( $styles );
        $gap      = $esc( $st( 'ts_gap', '24px' ) );

        // ── Wrapper layout ───────────────────────────────────────────────────
        if ( 'carousel' === $layout ) {
            $renderer->add_css( $prefix . '{display:flex;flex-direction:row;gap:' . $gap . ';overflow-x:auto;scroll-snap-type:x mandatory;-webkit-overflow-scrolling:touch;' . $base_css . '}' );
            $renderer->set_needs_js( 'carousel' );
        } else {
            $renderer->add_css( $prefix . '{display:grid;grid-template-columns:repeat(' . $cols . ',1fr);gap:' . $gap . ';' . $base_css . '}' );
        }

        // ── Card ─────────────────────────────────────────────────────────────
        $shadow_map = [
            'none' => 'none',
            'sm'   => '0 1px 8px rgba(0,0,0,.06)',
            'md'   => '0 4px 20px rgba(0,0,0,.10)',
            'lg'   => '0 8px 32px rgba(0,0,0,.16)',
            'xl'   => '0 16px 48px rgba(0,0,0,.20)',
        ];
        $card_bg     = $esc( $st( 'ts_card_bg', '#ffffff' ) );
        $card_radius = $esc( $st( 'ts_card_radius', '16px' ) );
        $card_pad    = $esc( $st( 'ts_card_pad', '28px' ) );
        $card_shadow = $shadow_map[ $st( 'ts_card_shadow', 'sm' ) ] ?? $shadow_map['sm'];
        $bd_type     = $st( 'ts_bd_type', 'none' );
        $bd_css      = ( $bd_type && $bd_type !== 'none' )
            ? 'border:' . $esc( $st( 'ts_bd_width', '1px' ) ) . ' ' . $esc( $bd_type ) . ' ' . $esc( $st( 'ts_bd_color', '#e5e7eb' ) ) . ';'
            : '';
        $card_align  = $esc( $st( 'ts_align', 'left' ) );
        $card_css    = 'background:' . $card_bg . ';border-radius:' . $card_radius . ';padding:' . $card_pad . ';box-shadow:' . $card_shadow . ';' . $bd_css
                     . 'text-align:' . $card_align . ';display:flex;flex-direction:column;position:relative;overflow:hidden;';
        if ( 'carousel' === $layout ) {
            $card_css .= 'flex:0 0 280px;min-width:280px;scroll-snap-align:start;';
        }
        $renderer->add_css( $prefix . ' .jalpi-tc{' . $card_css . '}' );

        // ── Quote mark ───────────────────────────────────────────────────────
        $qmark_color = $esc( $st( 'ts_qmark_color', 'rgba(99,102,241,0.10)' ) );
        $qmark_size  = $esc( $st( 'ts_qmark_size', '72px' ) );
        $qmark_left  = $card_align === 'center' ? '50%' : '14px';
        $qmark_tform = $card_align === 'center' ? 'transform:translateX(-50%);' : '';
        $renderer->add_css( $prefix . ' .jalpi-tc__qmark{position:absolute;top:10px;left:' . $qmark_left . ';' . $qmark_tform
                           . 'font-size:' . $qmark_size . ';line-height:1;color:' . $qmark_color . ';font-family:Georgia,serif;pointer-events:none;user-select:none;z-index:0;}' );

        // ── Stars ────────────────────────────────────────────────────────────
        $star_color = $esc( $st( 'ts_star_color', '#f59e0b' ) );
        $star_empty = $esc( $st( 'ts_star_empty', '#d1d5db' ) );
        $star_size  = $esc( $st( 'ts_star_size', '16px' ) );
        $star_just  = $card_align === 'center' ? 'center' : ( $card_align === 'right' ? 'flex-end' : 'flex-start' );
        $renderer->add_css( $prefix . ' .jalpi-tc__stars{display:flex;gap:3px;margin-bottom:12px;justify-content:' . $star_just . ';position:relative;z-index:1;}' );
        $renderer->add_css( $prefix . ' .jalpi-tc__star{font-size:' . $star_size . ';line-height:1;color:' . $star_empty . ';}' );
        $renderer->add_css( $prefix . ' .jalpi-tc__star.is-filled{color:' . $star_color . ';}' );

        // ── Quote text ───────────────────────────────────────────────────────
        // ── Helper: build typography CSS string from prefix ──────────────────
        $typo_css = function( $pfx, $defaults = [] ) use ( $st, $esc ) {
            $out = '';
            $fam = $st( $pfx . '_fontFamily' );
            if ( $fam ) $out .= 'font-family:' . $esc( $fam ) . ';';
            $fsz = $st( $pfx . '_fontSize',    $defaults['fontSize']    ?? '' );
            if ( $fsz ) $out .= 'font-size:' . $esc( $fsz ) . ';';
            $fw  = $st( $pfx . '_fontWeight',  $defaults['fontWeight']  ?? '' );
            if ( $fw  ) $out .= 'font-weight:' . $esc( $fw ) . ';';
            $lh  = $st( $pfx . '_lineHeight',  $defaults['lineHeight']  ?? '' );
            if ( $lh  ) $out .= 'line-height:' . $esc( $lh ) . ';';
            $ls  = $st( $pfx . '_letterSpacing' );
            if ( $ls  ) $out .= 'letter-spacing:' . $esc( $ls ) . ';';
            $tt  = $st( $pfx . '_textTransform' );
            if ( $tt  ) $out .= 'text-transform:' . $esc( $tt ) . ';';
            return $out;
        };

        // ── Quote text ───────────────────────────────────────────────────────
        $q_color  = $esc( $st( 'ts_quote_color', '#374151' ) );
        $q_fstyle = $esc( $st( 'ts_quote_fstyle', 'italic' ) );
        $q_typo   = $typo_css( 'ts_q', [ 'fontSize' => '15px', 'fontWeight' => '400', 'lineHeight' => '1.75' ] );
        $renderer->add_css( $prefix . ' .jalpi-tc__quote{color:' . $q_color . ';font-style:' . $q_fstyle . ';' . $q_typo . 'margin:0 0 20px;flex-grow:1;position:relative;z-index:1;}' );

        // ── Author footer ────────────────────────────────────────────────────
        $author_just = $star_just;
        $renderer->add_css( $prefix . ' .jalpi-tc__footer{display:flex;align-items:center;gap:12px;padding-top:16px;border-top:1px solid rgba(0,0,0,.06);margin-top:auto;justify-content:' . $author_just . ';position:relative;z-index:1;}' );

        // ── Avatar ───────────────────────────────────────────────────────────
        $av_size   = $esc( $st( 'ts_avatar_size', '44px' ) );
        $av_radius = $esc( $st( 'ts_avatar_radius', '50%' ) );
        $renderer->add_css( $prefix . ' .jalpi-tc__avatar{width:' . $av_size . ';height:' . $av_size . ';border-radius:' . $av_radius . ';object-fit:cover;flex-shrink:0;}' );
        $renderer->add_css( $prefix . ' .jalpi-tc__avatar-ph{width:' . $av_size . ';height:' . $av_size . ';border-radius:' . $av_radius . ';background:linear-gradient(135deg,#667eea,#764ba2);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:600;flex-shrink:0;font-size:calc(' . $av_size . ' * 0.42);}' );

        // ── Name & role ──────────────────────────────────────────────────────
        $name_color = $esc( $st( 'ts_name_color', '#111827' ) );
        $name_typo  = $typo_css( 'ts_name', [ 'fontSize' => '14px', 'fontWeight' => '600', 'lineHeight' => '1.3' ] );
        $role_color = $esc( $st( 'ts_role_color', '#6b7280' ) );
        $role_typo  = $typo_css( 'ts_role', [ 'fontSize' => '12px', 'fontWeight' => '400', 'lineHeight' => '1.3' ] );
        $renderer->add_css( $prefix . ' .jalpi-tc__name{display:block;color:' . $name_color . ';font-style:normal;' . $name_typo . '}' );
        $renderer->add_css( $prefix . ' .jalpi-tc__role{display:block;color:' . $role_color . ';margin-top:2px;' . $role_typo . '}' );

        // ── Responsive breakpoints ───────────────────────────────────────────
        if ( 'grid' === $layout ) {
            if ( $cols >= 3 ) {
                $renderer->add_css( '@media(max-width:768px){' . $prefix . '{grid-template-columns:repeat(2,1fr);}}' );
                $renderer->add_css( '@media(max-width:480px){' . $prefix . '{grid-template-columns:1fr;}}' );
            } elseif ( $cols >= 2 ) {
                $renderer->add_css( '@media(max-width:480px){' . $prefix . '{grid-template-columns:1fr;}}' );
            }
        }

        // ── Build HTML ───────────────────────────────────────────────────────
        $autoplay      = max( 0, intval( $content['autoplay'] ?? 0 ) );
        $autoplay_attr = ( 'carousel' === $layout && $autoplay > 0 ) ? ' data-autoplay="' . $autoplay . '"' : '';
        $wrapper_class = 'jalpi-el jalpi-testimonials jalpi-testimonials--' . esc_attr( $layout ) . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'];

        $cards = '';
        foreach ( $items as $item ) {
            $text    = esc_html( $item['text']      ?? '' );
            $name    = esc_html( $item['name']      ?? '' );
            $role    = esc_html( $item['role']      ?? '' );
            $avatar  = esc_url(  $item['avatarUrl'] ?? '' );
            $rating  = max( 1, min( 5, intval( $item['rating'] ?? 5 ) ) );
            $initial = mb_strtoupper( mb_substr( wp_strip_all_tags( $name ), 0, 1 ) ?: '?' );

            $stars_html = '';
            for ( $si = 1; $si <= 5; $si++ ) {
                $stars_html .= '<span class="jalpi-tc__star' . ( $si <= $rating ? ' is-filled' : '' ) . '" aria-hidden="true">★</span>';
            }

            $avatar_html = $avatar
                ? '<img src="' . $avatar . '" alt="' . esc_attr( $name ) . '" class="jalpi-tc__avatar" loading="lazy">'
                : '<span class="jalpi-tc__avatar-ph" aria-hidden="true">' . esc_html( $initial ) . '</span>';

            $cards .= '<div class="jalpi-tc">'
                    . '<span class="jalpi-tc__qmark" aria-hidden="true">❝</span>'
                    /* translators: %s: star rating number */
                    . '<div class="jalpi-tc__stars" aria-label="' . esc_attr( sprintf( __( '%s out of 5 stars', 'jalpi-page-builder' ), $rating ) ) . '">' . $stars_html . '</div>'
                    . '<p class="jalpi-tc__quote">' . $text . '</p>'
                    . '<footer class="jalpi-tc__footer">'
                    .   $avatar_html
                    .   '<div class="jalpi-tc__author">'
                    .     ( $name ? '<cite class="jalpi-tc__name">' . $name . '</cite>' : '' )
                    .     ( $role ? '<span class="jalpi-tc__role">' . $role . '</span>' : '' )
                    .   '</div>'
                    . '</footer>'
                    . '</div>';
        }

        return '<div class="' . $wrapper_class . '"' . $a['id_attr'] . $autoplay_attr . '>' . $cards . '</div>';
    }
}
