<?php
/**
 * Render Review Block with Dynamic Load More & Multi-Book Support
 */

$posts_to_show = isset($attributes['postsToShow']) ? intval($attributes['postsToShow']) : 3;
$selected_book_ids_str = isset($attributes['selectedBookId']) ? $attributes['selectedBookId'] : '';
$heading = isset($attributes['heading']) ? $attributes['heading'] : 'Happy Readers!';
$show_curve = isset($attributes['showCurve']) ? $attributes['showCurve'] : true;
$curve_color = isset($attributes['curveColor']) ? $attributes['curveColor'] : '#FFFDF5';
$curve_color = isset($attributes['curveColor']) ? $attributes['curveColor'] : '#FFFDF5';
$enable_load_more = isset($attributes['enableLoadMore']) ? $attributes['enableLoadMore'] : false;
$review_style = isset($attributes['reviewStyle']) ? $attributes['reviewStyle'] : 'fun';

$is_fun = $review_style === 'fun';
$is_elegant = $review_style === 'elegant';

// Styles
$section_bg_color = isset($attributes['sectionBgColor']) ? $attributes['sectionBgColor'] : '';
$text_color = isset($attributes['textColor']) ? $attributes['textColor'] : '';
$card_bg_color = isset($attributes['cardBgColor']) ? $attributes['cardBgColor'] : '';
$star_color = isset($attributes['starColor']) ? $attributes['starColor'] : '';

// Conditional Classes & Styles
// Conditional Classes & Styles
$section_wrapper_class = !empty($section_bg_color) ? '' : ($is_elegant ? 'bg-gray-50' : 'bg-blue-sky/10');
$section_style = !empty($section_bg_color) ? 'style="background-color:' . esc_attr($section_bg_color) . ';"' : '';

$default_heading_class = $is_elegant
    ? 'text-3xl md:text-5xl font-serif font-bold text-brand-dark'
    : 'text-center md:text-center text-3xl md:text-5xl font-black leading-10 text-navy';
$text_class = !empty($text_color) ? '' : ($is_elegant ? 'text-brand-dark' : 'text-navy');
$text_style = !empty($text_color) ? 'style="color:' . esc_attr($text_color) . ';"' : '';

$card_class = !empty($card_bg_color) ? '' : ($is_elegant ? 'bg-white rounded shadow-sm hover:shadow-md transition-all duration-300' : 'bg-white rounded-xl shadow-lg');
$card_style = !empty($card_bg_color) ? 'style="background-color:' . esc_attr($card_bg_color) . ';"' : '';

$star_class = !empty($star_color) ? '' : ($is_elegant ? 'text-slate-900 text-lg tracking-widest' : 'text-yellow-sun text-4xl');
$star_style = !empty($star_color) ? 'style="color:' . esc_attr($star_color) . ';"' : '';

$review_text_class = $is_elegant
    ? 'text-brand-gray italic mb-6 leading-relaxed'
    : 'text-lg italic mb-6 leading-relaxed text-navy opacity-80';

// Meta Styles
$meta_container_class = $is_elegant ? 'flex items-center gap-4 border-t border-gray-100 pt-4' : 'flex items-center gap-4';
$author_name_class = $is_elegant ? 'font-bold text-slate-800 font-serif' : 'font-black';
$author_role_class = $is_elegant ? 'text-xs text-gray-500 uppercase' : 'text-sm opacity-60';
$star_style = !empty($star_color) ? 'style="color:' . esc_attr($star_color) . ';"' : '';


// Query Arguments
$args = [
    'post_type' => 'book_reviews',
    'posts_per_page' => $posts_to_show,
    'post_status' => 'publish',
    'orderby' => 'date',
    'order' => 'DESC',
];

// Handle Multiple Book IDs (Comma Separated)
if (!empty($selected_book_ids_str)) {
    // Convert "1, 2, 3" to array [1, 2, 3]
    $book_ids_array = array_map('intval', array_map('trim', explode(',', $selected_book_ids_str)));

    // Use Meta Query with 'IN' comparison
    $args['meta_query'] = [
        [
            'key' => '_rswpbs_reviewed_book',
            'value' => $book_ids_array,
            'compare' => 'IN',
        ],
    ];
} elseif (is_singular('book')) {
    // Auto-fetch for current book if we are on a Single Book page
    $args['meta_query'] = [
        [
            'key' => '_rswpbs_reviewed_book',
            'value' => get_the_ID(),
            'compare' => '=',
        ],
    ];
}

$reviews_query = new WP_Query($args);

$block_id = uniqid('reviews-');
?>

<section id="reviews" class="py-24 relative overflow-hidden <?php echo esc_attr($section_wrapper_class); ?>" <?php echo $section_style; ?>>

    <?php if ($show_curve && $is_fun): ?>
        <div class="absolute top-0 left-0 w-full">
            <svg viewBox="0 0 1440 100" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
                <path d="M0 0H1440V100C1192.5 50.503 919.5 25.503 720 25.503C520.5 25.503 247.5 50.503 0 100V0Z"
                    fill="<?php echo esc_attr($curve_color); ?>" />
            </svg>
        </div>
    <?php endif; ?>

    <div
        class="awt-container container mx-auto px-6 relative z-10 <?php echo ($show_curve && $is_fun) ? 'mt-12' : ''; ?>">
        <?php if ($heading): ?>
            <h2 class="mb-12 text-center md:text-center <?php echo !empty($text_color) ? '' : esc_attr($default_heading_class); ?> <?php echo esc_attr($text_class); ?>"
                <?php echo $text_style; ?>>
                <?php echo esc_html($heading); ?>
            </h2>
        <?php endif; ?>

        <?php if ($reviews_query->have_posts()): ?>
            <div id="awt-reviews-grid-<?php echo esc_attr($block_id); ?>"
                class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                <?php
                $index = 0;
                while ($reviews_query->have_posts()):
                    $reviews_query->the_post();
                    $rating = get_post_meta(get_the_ID(), '_rswpbs_rating', true);
                    $reviewer_name = get_post_meta(get_the_ID(), '_rswpbs_reviewer_name', true);

                    // Rotation & Avatar Logic
                    $rotation_class = '';
                    if ($is_fun) {
                        $rotation_class = 'hover:rotate-0 transition-all duration-300 shadow-lg';
                        if ($index % 3 == 0)
                            $rotation_class .= ' transform rotate-1';
                        elseif ($index % 3 == 1)
                            $rotation_class .= ' transform -rotate-1';
                        else
                            $rotation_class .= ' transform rotate-2';
                    }

                    $initial = !empty($reviewer_name) ? strtoupper(substr($reviewer_name, 0, 1)) : 'R';
                    $avatar_colors = ['bg-coral-pop/20 text-coral-pop', 'bg-blue-sky/20 text-blue-sky', 'bg-yellow-sun/20 text-navy'];
                    $avatar_color_class = $avatar_colors[$index % 3];

                    $content = get_the_content();
                    $unique_content_id = 'review-content-' . get_the_ID();
                    $word_count = str_word_count(strip_tags($content));
                    ?>
                    <div class="p-8 <?php echo esc_attr($card_class . ' ' . $rotation_class); ?>" <?php echo $card_style; ?>>
                        <div class="mb-4 <?php echo esc_attr($star_class); ?>" <?php echo $star_style; ?>>
                            <?php for ($i = 1; $i <= 5; $i++)
                                echo $i <= $rating ? '★' : '☆'; ?>
                        </div>
                        <div class="awt-review-content <?php echo esc_attr($review_text_class); ?> <?php echo esc_attr($text_class); ?>"
                            <?php echo $text_style; ?>>
                            "<?php echo wp_trim_words($content, 25, '...'); ?>"
                            <?php if ($word_count > 25): ?>
                                <button
                                    class="awt-read-more-btn text-sm font-bold underline ml-2 cursor-pointer py-1 px-3 focus:outline-none"
                                    data-content-id="<?php echo esc_attr($unique_content_id); ?>">Read More</button>
                                <template
                                    id="<?php echo esc_attr($unique_content_id); ?>"><?php echo wp_kses_post($content); ?></template>
                            <?php endif; ?>
                        </div>
                        <div class="<?php echo esc_attr($meta_container_class); ?>">
                            <?php if ($is_fun): ?>
                                <div
                                    class="w-12 h-12 rounded-full flex items-center justify-center font-black text-xl <?php echo esc_attr($avatar_color_class); ?>">
                                    <?php echo esc_html($initial); ?>
                                </div>
                            <?php endif; ?>
                            <div>
                                <h5 class="<?php echo esc_attr($author_name_class); ?> <?php echo esc_attr($text_class); ?>"
                                    <?php echo $text_style; ?>>
                                    <?php echo esc_html($reviewer_name); ?>
                                </h5>
                                <span class="<?php echo esc_attr($author_role_class); ?> <?php echo esc_attr($text_class); ?>"
                                    <?php echo $text_style; ?>>Verified Reader</span>
                            </div>
                        </div>
                    </div>
                    <?php
                    $index++;
                endwhile;
                wp_reset_postdata();
                ?>
            </div>



        <?php else: ?>
            <div class="text-center p-8 border-2 border-dashed border-gray-300 rounded-lg bg-white/50">
                <p class="text-gray-500 text-lg">No reviews found. Add some Book Reviews in the dashboard!</p>
            </div>
        <?php endif; ?>

    </div>

    <div id="awt-review-modal"
        class="fixed inset-0 z-50 flex items-center justify-center hidden opacity-0 transition-opacity duration-300"
        role="dialog">
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" id="awt-modal-backdrop"></div>
        <div class="relative bg-white rounded-2xl p-8 max-w-lg w-full mx-4 shadow-2xl transform scale-95 transition-transform duration-300"
            id="awt-modal-content">
            <button id="awt-modal-close" class="absolute top-4 right-4 text-white hover:text-navy transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
            <div class="text-4xl text-yellow-sun mb-4">★★★★★</div>
            <div id="awt-modal-text"
                class="text-lg text-navy italic leading-relaxed opacity-80 max-h-[60vh] overflow-y-auto pr-2"></div>
        </div>
    </div>
</section>