<?php
/**
 * Template: product/reviews.php
 *
 * Renders the review list for a product — rating summary bar + paginated reviews.
 *
 * Available variables:
 *   $product_id   int     tc_products.id
 *   $reviews      array   Approved review rows from ReviewManager::get_reviews()
 *   $total        int     Total approved review count
 *   $total_pages  int
 *   $current_page int
 *   $stats        array   { avg_rating: float, total_count: int, distribution: array<int,int> }
 *   $sort         string  Current sort mode
 *
 * Override: copy to your-theme/titancart/product/reviews.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$product_id   = (int) ( $product_id   ?? 0 );
$reviews      = $reviews      ?? [];
$total        = (int) ( $total        ?? 0 );
$total_pages  = (int) ( $total_pages  ?? 1 );
$current_page = (int) ( $current_page ?? 1 );
$stats        = $stats        ?? [ 'avg_rating' => 0, 'total_count' => 0, 'distribution' => [] ];
$sort         = $sort         ?? 'newest';

$avg_rating  = (float) ( $stats['avg_rating']  ?? 0 );
$total_count = (int)   ( $stats['total_count'] ?? 0 );
$dist        = $stats['distribution'] ?? [];

// Helper: render star SVGs (filled/empty) for a given rating.
function titancart_render_stars( float $rating, string $size = '16' ): string {
    $out = '<span class="tc-stars" aria-hidden="true">';
    for ( $i = 1; $i <= 5; $i++ ) {
        $fill = $i <= $rating ? '#D9A441' : '#E1E5EA';
        $out .= sprintf(
            '<svg width="%s" height="%s" viewBox="0 0 16 16" fill="%s" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 1l1.8 3.6L14 5.3 11 8.1l.7 3.9L8 10.1l-3.7 1.9.7-3.9L2 5.3l4.2-.7z"/>
            </svg>',
            esc_attr( $size ),
            esc_attr( $size ),
            esc_attr( $fill )
        );
    }
    $out .= '</span>';
    return $out;
}

// WP.org R2 item 6: allowlist matching exactly what titancart_render_stars() builds —
// passed to wp_kses() at both echo sites below (kses_post strips SVG, hence scoped).
$tc_stars_kses_allowed = [
    'span' => [ 'class' => true, 'aria-hidden' => true ],
    'svg'  => [ 'width' => true, 'height' => true, 'viewbox' => true, 'fill' => true, 'xmlns' => true ],
    'path' => [ 'd' => true ],
];
?>

<section class="tc-reviews" id="tc-reviews" data-product-id="<?php echo esc_attr( $product_id ); ?>">

    <h2 class="tc-reviews__heading">
        <?php
        if ( $total_count ) {
            printf(
                /* translators: 1: total count */
                esc_html__( 'Customer Reviews (%d)', 'titancart-lite' ),
                (int) $total_count
            );
        } else {
            esc_html_e( 'Customer Reviews', 'titancart-lite' );
        }
        ?>
    </h2>

    <?php if ( $total_count ) : ?>

        <!-- ── Rating Summary ─────────────────────────────────────────────── -->
        <div class="tc-reviews__summary">

            <div class="tc-reviews__summary-score">
                <span class="tc-reviews__avg" aria-label="<?php echo esc_attr( $avg_rating ); ?> <?php esc_attr_e( 'out of 5', 'titancart-lite' ); ?>">
                    <?php echo esc_html( number_format( $avg_rating, 1 ) ); ?>
                </span>
                <?php echo wp_kses( titancart_render_stars( $avg_rating, '20' ), $tc_stars_kses_allowed ); ?>
                <span class="tc-reviews__count tc-muted">
                    <?php
                    printf(
                        /* translators: %d: review count */
                        esc_html( _n( '%d review', '%d reviews', $total_count, 'titancart-lite' ) ),
                        (int) $total_count
                    );
                    ?>
                </span>
            </div>

            <div class="tc-reviews__summary-bars">
                <?php foreach ( [ 5, 4, 3, 2, 1 ] as $star ) :
                    $count   = (int) ( $dist[ $star ] ?? 0 );
                    $percent = $total_count ? round( ( $count / $total_count ) * 100 ) : 0;
                ?>
                    <div class="tc-reviews__bar-row">
                        <span class="tc-reviews__bar-label">
                            <?php
                            printf(
                                /* translators: %d: star count */
                                esc_html__( '%d star', 'titancart-lite' ),
                                (int) $star
                            );
                            ?>
                        </span>
                        <div class="tc-reviews__bar-track" role="presentation">
                            <div class="tc-reviews__bar-fill" style="width: <?php echo esc_attr( $percent ); ?>%;"></div>
                        </div>
                        <span class="tc-reviews__bar-count tc-muted"><?php echo esc_html( $count ); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>

        </div><!-- .tc-reviews__summary -->

        <!-- ── Sort Controls ──────────────────────────────────────────────── -->
        <div class="tc-reviews__toolbar">
            <label for="tc-review-sort" class="tc-label tc-label--inline">
                <?php esc_html_e( 'Sort by:', 'titancart-lite' ); ?>
            </label>
            <select id="tc-review-sort"
                    class="tc-select tc-select--sm js-tc-review-sort"
                    data-product-id="<?php echo esc_attr( $product_id ); ?>">
                <?php
                $sort_options = [
                    'newest'  => __( 'Newest first',    'titancart-lite' ),
                    'oldest'  => __( 'Oldest first',    'titancart-lite' ),
                    'highest' => __( 'Highest rated',   'titancart-lite' ),
                    'lowest'  => __( 'Lowest rated',    'titancart-lite' ),
                    'helpful' => __( 'Most helpful',    'titancart-lite' ),
                ];
                foreach ( $sort_options as $val => $label ) :
                ?>
                    <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $sort, $val ); ?>>
                        <?php echo esc_html( $label ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- ── Review List ────────────────────────────────────────────────── -->
        <div class="tc-reviews__list" id="tc-reviews-list">
            <?php foreach ( $reviews as $review ) :
                $verified = ! empty( $review['verified_purchase'] );
            ?>
                <article class="tc-review" data-review-id="<?php echo esc_attr( $review['id'] ); ?>">

                    <header class="tc-review__header">
                        <div class="tc-review__meta">
                            <?php echo wp_kses( titancart_render_stars( (int) $review['rating'] ), $tc_stars_kses_allowed ); ?>
                            <strong class="tc-review__author">
                                <?php echo esc_html( $review['author_name'] ); ?>
                            </strong>
                            <?php if ( $verified ) : ?>
                                <span class="tc-review__badge tc-badge tc-badge--success">
                                    <?php esc_html_e( '✓ Verified Purchase', 'titancart-lite' ); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                        <time class="tc-review__date tc-muted"
                              datetime="<?php echo esc_attr( $review['created_at'] ); ?>">
                            <?php echo esc_html( titancart_format_date( $review['created_at'] ) ); ?>
                        </time>
                    </header>

                    <?php if ( ! empty( $review['title'] ) ) : ?>
                        <h3 class="tc-review__title"><?php echo esc_html( $review['title'] ); ?></h3>
                    <?php endif; ?>

                    <div class="tc-review__body">
                        <?php echo wp_kses_post( wpautop( $review['body'] ) ); ?>
                    </div>

                    <!-- Helpful vote -->
                    <footer class="tc-review__footer">
                        <span class="tc-review__helpful-label tc-muted">
                            <?php esc_html_e( 'Was this review helpful?', 'titancart-lite' ); ?>
                        </span>
                        <button class="tc-btn tc-btn--ghost tc-btn--xs js-tc-vote"
                                data-review-id="<?php echo esc_attr( $review['id'] ); ?>"
                                data-vote="1"
                                aria-label="<?php esc_attr_e( 'Mark as helpful', 'titancart-lite' ); ?>">
                            👍 <span class="tc-vote-count"><?php echo esc_html( $review['helpful'] ); ?></span>
                        </button>
                        <button class="tc-btn tc-btn--ghost tc-btn--xs js-tc-vote"
                                data-review-id="<?php echo esc_attr( $review['id'] ); ?>"
                                data-vote="0"
                                aria-label="<?php esc_attr_e( 'Mark as not helpful', 'titancart-lite' ); ?>">
                            👎 <span class="tc-vote-count"><?php echo esc_html( $review['not_helpful'] ); ?></span>
                        </button>
                    </footer>

                </article>
            <?php endforeach; ?>
        </div><!-- #tc-reviews-list -->

        <!-- ── Pagination ─────────────────────────────────────────────────── -->
        <?php if ( $total_pages > 1 ) : ?>
            <nav class="tc-reviews__pagination tc-pagination" aria-label="<?php esc_attr_e( 'Review pages', 'titancart-lite' ); ?>">
                <?php for ( $p = 1; $p <= $total_pages; $p++ ) :
                    $is_current = ( $p === $current_page );
                    $page_url   = add_query_arg( 'reviews_page', $p );
                ?>
                    <a href="<?php echo esc_url( $page_url ); ?>#tc-reviews"
                       class="tc-pagination__btn<?php echo $is_current ? ' tc-pagination__btn--active' : ''; ?>"
                       aria-current="<?php echo $is_current ? 'page' : 'false'; ?>">
                        <?php echo esc_html( $p ); ?>
                    </a>
                <?php endfor; ?>
            </nav>
        <?php endif; ?>

    <?php else : ?>

        <p class="tc-reviews__empty tc-muted">
            <?php esc_html_e( 'No reviews yet. Be the first to write one!', 'titancart-lite' ); ?>
        </p>

    <?php endif; ?>

</section><!-- .tc-reviews -->
