<?php
/**
 * Render Book Gallery [Author Pro] Block
 */

$items_per_page = isset($attributes['itemsPerPage']) ? $attributes['itemsPerPage'] : 12;
$book_page_url = isset($attributes['bookPageUrl']) ? $attributes['bookPageUrl'] : '';
$show_sidebar = isset($attributes['showSidebar']) ? $attributes['showSidebar'] : true;

$is_editor = (defined('REST_REQUEST') && REST_REQUEST) || (isset($_REQUEST['context']) && $_REQUEST['context'] === 'edit');

// Back Link Logic
$back_link = !empty($book_page_url) ? esc_url($book_page_url) : get_post_type_archive_link('book');

// Filter Visibility
$show_search = isset($attributes['showSearch']) ? $attributes['showSearch'] : true;
$show_genre = isset($attributes['showFilterGenre']) ? $attributes['showFilterGenre'] : true;
$show_author = isset($attributes['showFilterAuthor']) ? $attributes['showFilterAuthor'] : true;
$show_series = isset($attributes['showFilterSeries']) ? $attributes['showFilterSeries'] : true;
$show_format = isset($attributes['showFilterFormat']) ? $attributes['showFilterFormat'] : true;
$show_language = isset($attributes['showFilterLanguage']) ? $attributes['showFilterLanguage'] : true;
$show_publisher = isset($attributes['showFilterPublisher']) ? $attributes['showFilterPublisher'] : true;
$show_isbn = isset($attributes['showFilterISBN']) ? $attributes['showFilterISBN'] : true;
$show_price = isset($attributes['showFilterPrice']) ? $attributes['showFilterPrice'] : true;
$show_year = isset($attributes['showFilterYear']) ? $attributes['showFilterYear'] : true;
$show_age = isset($attributes['showFilterAge']) ? $attributes['showFilterAge'] : true;
$show_rating = isset($attributes['showFilterRating']) ? $attributes['showFilterRating'] : true;
$show_sorting = isset($attributes['showSorting']) ? $attributes['showSorting'] : true;
$pagination_type = isset($attributes['paginationType']) ? $attributes['paginationType'] : 'numbers';
$columns = isset($attributes['columns']) ? $attributes['columns'] : 3;

$block_id = isset($attributes['blockId']) ? $attributes['blockId'] : '';
$anchor = isset($attributes['anchor']) ? $attributes['anchor'] : '';
$element_id = !empty($anchor) ? $anchor : $block_id;
if (empty($element_id)) {
    $element_id = 'awt-book-gallery-' . uniqid();
}

// Define SVGs
$icon_star = '<svg class="w-3 h-3 text-yellow-400" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M341.5 45.1C337.4 37.1 329.1 32 320.1 32C311.1 32 302.8 37.1 298.7 45.1L225.1 189.3L65.2 214.7C56.3 216.1 48.9 222.4 46.1 231C43.3 239.6 45.6 249 51.9 255.4L166.3 369.9L141.1 529.8C139.7 538.7 143.4 547.7 150.7 553C158 558.3 167.6 559.1 175.7 555L320.1 481.6L464.4 555C472.4 559.1 482.1 558.3 489.4 553C496.7 547.7 500.4 538.8 499 529.8L473.7 369.9L588.1 255.4C594.5 249 596.7 239.6 593.9 231C591.1 222.4 583.8 216.1 574.8 214.7L415 189.3L341.5 45.1z"/></svg>';
$icon_search = '<svg class="w-4 h-4 text-gray-400 absolute left-4 top-3.5" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M480 272C480 317.9 465.1 360.3 440 394.7L566.6 521.4C579.1 533.9 579.1 554.2 566.6 566.7C554.1 579.2 533.8 579.2 521.3 566.7L394.7 440C360.3 465.1 317.9 480 272 480C157.1 480 64 386.9 64 272C64 157.1 157.1 64 272 64C386.9 64 480 157.1 480 272zM272 416C351.5 416 416 351.5 416 272C416 192.5 351.5 128 272 128C192.5 128 128 192.5 128 272C128 351.5 192.5 416 272 416z"/></svg>';
$icon_chevron_up = '<svg class="w-3 h-3 text-gray-400 transition-transform duration-200" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M297.4 169.4C309.9 156.9 330.2 156.9 342.7 169.4L534.7 361.4C547.2 373.9 547.2 394.2 534.7 406.7C522.2 419.2 501.9 419.2 489.4 406.7L320 237.3L150.6 406.6C138.1 419.1 117.8 419.1 105.3 406.6C92.8 394.1 92.8 373.8 105.3 361.3L297.3 169.3z"/></svg>';
$icon_arrow_left = '<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 448 512" xmlns="http://www.w3.org/2000/svg"><path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.2 288 416 288c17.7 0 32-14.3 32-32s-14.3-32-32-32l-306.7 0L214.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg>';
$icon_arrow_right = '<svg class="w-4 h-4" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M471.1 297.4C483.6 309.9 483.6 330.2 471.1 342.7L279.1 534.7C266.6 547.2 246.3 547.2 233.8 534.7C221.3 522.2 221.3 501.9 233.8 489.4L403.2 320L233.9 150.6C221.4 138.1 221.4 117.8 233.9 105.3C246.4 92.8 266.7 92.8 279.2 105.3L471.2 297.3z"/></svg>';

$icon_pen = '<svg class="w-3 h-3 text-gray-400" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M432.5 82.3L382.4 132.4L507.7 257.7L557.8 207.6C579.7 185.7 579.7 150.3 557.8 128.4L511.7 82.3C489.8 60.4 454.4 60.4 432.5 82.3zM343.3 161.2L342.8 161.3L198.7 204.5C178.8 210.5 163 225.7 156.4 245.5L67.8 509.8C64.9 518.5 65.9 528 70.3 535.8L225.7 380.4C224.6 376.4 224.1 372.3 224.1 368C224.1 341.5 245.6 320 272.1 320C298.6 320 320.1 341.5 320.1 368C320.1 394.5 298.6 416 272.1 416C267.8 416 263.6 415.4 259.7 414.4L104.3 569.7C112.1 574.1 121.5 575.1 130.3 572.2L394.6 483.6C414.3 477 429.6 461.2 435.6 441.3L478.8 297.2L478.9 296.7L343.4 161.2z"/></svg>';
$icon_cart = '<svg class="w-3 h-3" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M0 24C0 10.7 10.7 0 24 0H69.5c22 0 41.5 12.8 50.6 32h411c26.3 0 45.5 25 38.6 50.4l-41 152.3c-8.5 31.4-37 53.3-69.5 53.3H170.7l5.4 28.5c2.2 11.3 12.1 19.5 23.6 19.5H488c13.3 0 24 10.7 24 24s-10.7 24-24 24H199.7c-34.6 0-64.3-24.6-70.7-58.5L77.4 54.5c-.7-3.8-4-6.5-7.9-6.5H24C10.7 48 0 37.3 0 24zM128 464a48 48 0 1 1 96 0 48 48 0 1 1 -96 0zm336-48a48 48 0 1 1 0 96 48 48 0 1 1 0-96z"/></svg>';
$icon_sliders = '<svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="M0 416c0 17.7 14.3 32 32 32l54.7 0c12.3 28.3 40.5 48 73.3 48s61-19.7 73.3-48L480 448c17.7 0 32-14.3 32-32s-14.3-32-32-32l-246.7 0c-12.3-28.3-40.5-48-73.3-48s-61 19.7-73.3 48L32 384c-17.7 0-32 14.3-32 32zm192 0a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM384 256a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM512 128c0-17.7-14.3-32-32-32l-54.7 0c-12.3-28.3-40.5-48-73.3-48s-61 19.7-73.3 48L32 96C14.3 96 0 110.3 0 128s14.3 32 32 32l246.7 0c12.3 28.3 40.5 48 73.3 48s61-19.7 73.3-48L480 160c17.7 0 32-14.3 32-32zM160 256a32 32 0 1 0 0-64 32 32 0 1 0 0 64z"/></svg>';
$icon_x_mark = '<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 384 512" xmlns="http://www.w3.org/2000/svg"><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>';

// Context Detection
$current_tax = '';
$current_term_id = '';

$queried_object = get_queried_object();
if ($queried_object instanceof WP_Term) {
    if ($queried_object->taxonomy === 'book-category') {
        $current_tax = 'book-category';
        $current_term_id = $queried_object->term_id;
    } elseif ($queried_object->taxonomy === 'book-author') {
        $current_tax = 'book-author';
        $current_term_id = $queried_object->term_id;
    } elseif ($queried_object->taxonomy === 'book-series') {
        $current_tax = 'book-series';
        $current_term_id = $queried_object->term_id;
    }
}

// Initial Query for SEO
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'book',
    'posts_per_page' => $items_per_page,
    'post_status' => 'publish',
    'paged' => $paged,
);

// Inject Context into Initial Query
if (!empty($current_tax) && !empty($current_term_id)) {
    $args['tax_query'] = array(
        array(
            'taxonomy' => $current_tax,
            'field'    => 'term_id',
            'terms'    => $current_term_id,
        )
    );
}
$book_query = new WP_Query($args);
$total_books = $book_query->found_posts;
$start_result = ($paged - 1) * $items_per_page + 1;
$end_result = min($paged * $items_per_page, $total_books);

$wrapper_attributes = get_block_wrapper_attributes([
    'class' => 'awt-book-gallery bg-white',
    'id'    => $element_id
]);

// Helper to get Unique Meta Values (for filters)
if (!function_exists('awt_get_meta_options')) {
    function awt_get_meta_options($key) {
        global $wpdb;
        $results = $wpdb->get_col($wpdb->prepare("
            SELECT DISTINCT meta_value FROM $wpdb->postmeta 
            WHERE meta_key = %s AND meta_value != ''
        ", $key));
        return $results ? $results : [];
    }
}


// Helper to Render Multi-Select Dropdown
if (!function_exists('awt_render_dropdown_filter')) {
    function awt_render_dropdown_filter($label, $name, $options, $placeholder = 'Search...', $icon_chevron = '') {
        $key = uniqid();
        // Normalize options to [['value' =>, 'label' =>, 'count' => (optional)]]
        $normalized_options = [];
        
        if (!empty($options)) {
             // Check if it's an array of objects (Terms) or array of arrays
             $first = reset($options);
             if (is_array($first) && isset($first['value']) && isset($first['label'])) {
                 // Already in correct format (e.g. Genre custom array from previous step)
                 $normalized_options = $options;
             } elseif (is_object($first) && isset($first->term_id)) {
                 // WP Terms Object
                 foreach ($options as $term) {
                      $normalized_options[] = [
                          'value' => $term->term_id,
                          'label' => $term->name,
                          'count' => $term->count
                      ];
                 }
             } elseif (!is_array($first) && !is_object($first)) {
                 // Simple Key-Value Pair (e.g. Price, Rating, Meta Unique Values)
                 // Note: awt_get_meta_options returns simple array of strings [val1, val2]
                 // But manual arrays are [key => label].
                 // If keys are indices (0,1,2), it's a simple list. If keys are string/meaningful, it's key=>label.
                 
                 // Check if associative
                 $is_assoc = array_keys($options) !== range(0, count($options) - 1);
                 
                 foreach ($options as $k => $v) {
                     if ($is_assoc) {
                         // Key => Label (Price: '0-10' => 'Under $10')
                         $normalized_options[] = ['value' => $k, 'label' => $v];
                     } else {
                         // Value only (Meta: 'Hardcover', 'Paperback')
                         $normalized_options[] = ['value' => $v, 'label' => $v];
                     }
                 }
             }
        }
        ?>
        <div class="awt-custom-dropdown relative mb-4 group" id="dropdown-<?php echo esc_attr($key); ?>">
            <label class="block text-xs font-bold text-primary uppercase tracking-widest mb-2"><?php echo esc_html($label); ?></label>

            <button type="button" class="awt-dropdown-trigger w-full bg-white border border-gray-200 rounded px-3 py-2 text-sm text-left flex justify-between items-center hover:border-accent transition group-focus-within:border-accent">
                <span class="truncate text-secondary select-label font-medium">Select <?php echo esc_html($label); ?></span>
                <span class="transform transition-transform duration-200 dropdown-icon origin-center">
                    <?php echo $icon_chevron; ?>
                </span>
            </button>

            <div class="awt-dropdown-content hidden absolute top-full left-0 w-full bg-white border border-gray-200 shadow-xl rounded-b-lg z-50 mt-1 max-h-60 overflow-y-auto p-2">
                <input type="text" class="awt-dropdown-search w-full text-xs border border-gray-200 rounded px-2 py-2 mb-2 focus:outline-none focus:border-accent" placeholder="<?php echo esc_attr($placeholder); ?>">

                <div class="space-y-0.5 awt-dropdown-list">
                    <?php if (empty($normalized_options)): ?>
                        <div class="p-2 text-xs text-gray-400 italic">No options available</div>
                    <?php else: ?>
                        <?php foreach ($normalized_options as $opt) : ?>
                        <label class="flex items-center gap-2 cursor-pointer hover:bg-gray-50 p-1.5 rounded group transition w-full">
                            <input type="checkbox" name="<?php echo esc_attr($name); ?>[]" value="<?php echo esc_attr($opt['value']); ?>" data-label="<?php echo esc_attr($opt['label']); ?>" class="rounded border-gray-300 text-accent focus:ring-accent w-4 h-4">
                            <span class="text-xs text-secondary group-hover:text-accent transition font-medium">
                                <?php echo esc_html($opt['label']); ?>
                                <?php if (isset($opt['count']) && $opt['count'] !== ''): ?>
                                    <span class="text-gray-400 font-normal ml-1">(<?php echo esc_html($opt['count']); ?>)</span>
                                <?php endif; ?>
                            </span>
                        </label>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    }
}

$formats = awt_get_meta_options('_rsbs_book_format'); 
$languages = awt_get_meta_options('_rsbs_book_language'); 
$years = awt_get_meta_options('_rsbs_book_publish_year'); 
$ages = awt_get_meta_options('_rsbs_book_reading_age');
$publishers = awt_get_meta_options('_rsbs_book_publisher_name'); // New
?>

<section <?php echo $wrapper_attributes; ?>>
    <!-- Hidden inputs for JS -->
    <input type="hidden" id="awt-ajax-url" value="<?php echo admin_url('admin-ajax.php'); ?>">
    <input type="hidden" class="awt-items-per-page" value="<?php echo esc_attr($items_per_page); ?>">
    <input type="hidden" id="awt-current-tax" value="<?php echo esc_attr($current_tax); ?>">
    <input type="hidden" id="awt-current-term" value="<?php echo esc_attr($current_term_id); ?>">
    <input type="hidden" class="awt-pagination-type" value="<?php echo esc_attr($pagination_type); ?>">

    <div class="py-12">
        <div class="awt-container">
            <div class="grid grid-cols-12 md:grid-cols-12 gap-8 md:gap-12 items-start">

                <?php if ($show_sidebar) : ?>
                <!-- Mobile Filter Toggle -->
                <?php if (!$is_editor) : ?>
                <div class="block md:hidden w-full mb-6">
                    <button id="awt-mobile-filter-toggle" class="w-full flex items-center justify-center bg-white border border-gray-200 text-primary font-bold py-3 px-4 rounded-lg shadow-sm hover:border-accent hover:text-accent transition">
                        <?php echo $icon_sliders; ?>
                        <?php _e('Filters', 'author-website-templates'); ?>
                    </button>
                    <!-- Backdrop -->
                    <div id="awt-filter-backdrop" class="fixed inset-0 bg-black/50 z-40 hidden transition-opacity duration-300"></div>
                </div>
                <?php endif; ?>

                <?php
                $aside_classes = $is_editor 
                    ? 'awt-book-filters w-full md:space-y-0 md:col-span-3 space-y-8 static z-auto bg-transparent translate-x-0 overflow-visible p-0 h-auto shadow-none'
                    : 'awt-book-filters w-full md:space-y-0 md:col-span-3 space-y-8 fixed inset-0 z-50 bg-white transform -translate-x-full transition-transform duration-300 md:static md:z-auto md:bg-transparent md:translate-x-0 overflow-y-auto md:overflow-visible p-6 md:p-0 h-full md:h-auto shadow-2xl md:shadow-none';
                ?>
                <aside class="<?php echo esc_attr($aside_classes); ?>">
                    
                    <!-- Mobile Header with Close -->
                    <?php if (!$is_editor) : ?>
                    <div class="flex items-center justify-between mb-6 md:hidden">
                        <h2 class="text-xl font-bold text-primary font-serif"><?php _e('Filters', 'author-website-templates'); ?></h2>
                        <button id="awt-mobile-filter-close" class="text-gray-400 hover:text-accent p-2">
                             <?php echo $icon_x_mark; ?>
                        </button>
                    </div>
                    <?php endif; ?>

                    <!-- Search -->
                     <?php if($show_search): ?>
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
                        <h3 class="font-bold text-primary text-sm uppercase tracking-wider mb-4"><?php _e('Search', 'author-website-templates'); ?></h3>
                        <div class="relative">
                            <input type="text" class="awt-filter-search w-full pl-10 pr-4 py-3 bg-paper border border-gray-200 rounded-lg focus:outline-none focus:border-accent text-sm transition" placeholder="<?php _e('Title, keyword...', 'author-website-templates'); ?>">
                            <?php echo $icon_search; ?>
                        </div>
                    </div>
                     <?php endif; ?>

                    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">

                        <!-- Genre Filter -->
                        <?php if($show_genre): ?>
                        <div class="mb-8">
                            <?php 
                            if ($current_tax === 'book-category' && !empty($current_term_id)) {
                                // Locked View
                                $current_term = get_term($current_term_id);
                                if ($current_term) {
                                    ?>
                                    <h3 class="font-bold text-primary text-sm uppercase tracking-wider mb-4"><?php _e('Genres', 'author-website-templates'); ?></h3>
                                    <label class="flex items-center gap-3 cursor-not-allowed opacity-75">
                                        <input type="checkbox" checked disabled class="w-4 h-4 text-accent border-gray-300 rounded">
                                        <span class="text-sm text-secondary font-bold"><?php echo esc_html($current_term->name); ?></span>
                                    </label>
                                    <a href="<?php echo $back_link; ?>" class="text-xs font-bold text-accent hover:underline mt-2 inline-flex items-center gap-1">
                                        <?php echo $icon_arrow_left; ?> <?php _e('Back to All Books', 'author-website-templates'); ?>
                                    </a>
                                    <?php
                                }
                            } else {
                                // Dropdown View
                                $genres = get_terms(['taxonomy' => 'book-category', 'hide_empty' => true]);
                                awt_render_dropdown_filter(__('Genres', 'author-website-templates'), 'genre', $genres, 'Search genres...', $icon_chevron_up);
                            }
                            ?>
                        </div>
                        <?php endif; ?>

                        <!-- Authors Filter -->
                        <?php if($show_author): ?>
                        <div class="mb-8">
                            <?php 
                            if ($current_tax === 'book-author' && !empty($current_term_id)) {
                                $current_term = get_term($current_term_id);
                                if ($current_term) {
                                    ?>
                                    <h3 class="font-bold text-primary text-sm uppercase tracking-wider mb-4"><?php _e('Authors', 'author-website-templates'); ?></h3>
                                    <label class="flex items-center gap-3 cursor-not-allowed opacity-75">
                                        <input type="checkbox" checked disabled class="w-4 h-4 text-accent border-gray-300 rounded">
                                        <span class="text-sm text-secondary font-bold"><?php echo esc_html($current_term->name); ?></span>
                                    </label>
                                    <a href="<?php echo $back_link; ?>" class="text-xs font-bold text-accent hover:underline mt-2 inline-flex items-center gap-1">
                                        <?php echo $icon_arrow_left; ?> <?php _e('Back to All Books', 'author-website-templates'); ?>
                                    </a>
                                    <?php
                                }
                            } else {
                                $authors = get_terms(['taxonomy' => 'book-author', 'hide_empty' => true]);
                                awt_render_dropdown_filter(__('Authors', 'author-website-templates'), 'author', $authors, 'Search authors...', $icon_chevron_up);
                            }
                            ?>
                        </div>
                        <?php endif; ?>

                        <!-- Series Filter -->
                        <?php if($show_series): ?>
                        <div class="mb-8">
                            <?php 
                            if ($current_tax === 'book-series' && !empty($current_term_id)) {
                                $current_term = get_term($current_term_id);
                                if ($current_term) {
                                    ?>
                                    <h3 class="font-bold text-primary text-sm uppercase tracking-wider mb-4"><?php _e('Series', 'author-website-templates'); ?></h3>
                                    <label class="flex items-center gap-3 cursor-not-allowed opacity-75">
                                        <input type="checkbox" checked disabled class="w-4 h-4 text-accent border-gray-300 rounded">
                                        <span class="text-sm text-secondary font-bold"><?php echo esc_html($current_term->name); ?></span>
                                    </label>
                                    <a href="<?php echo $back_link; ?>" class="text-xs font-bold text-accent hover:underline mt-2 inline-flex items-center gap-1">
                                        <?php echo $icon_arrow_left; ?> <?php _e('Back to All Books', 'author-website-templates'); ?>
                                    </a>
                                    <?php
                                }
                            } else {
                                $series = get_terms(['taxonomy' => 'book-series', 'hide_empty' => true]);
                                awt_render_dropdown_filter(__('Series', 'author-website-templates'), 'series', $series, 'Search series...', $icon_chevron_up);
                            } 
                            ?>
                        </div>
                        <?php endif; ?>

                         <!-- Format Filter (Meta) -->
                         <?php if($show_format && !empty($formats)): ?>
                         <div class="mb-8">
                             <?php awt_render_dropdown_filter(__('Format', 'author-website-templates'), 'format', $formats, 'Search format...', $icon_chevron_up); ?>
                        </div>
                        <?php endif; ?>

                        <!-- Language Filter (Meta) -->
                        <?php if($show_language && !empty($languages)): ?>
                         <div class="mb-8">
                            <?php awt_render_dropdown_filter(__('Language', 'author-website-templates'), 'language', $languages, 'Search language...', $icon_chevron_up); ?>
                        </div>
                        <?php endif; ?>

                        <!-- Publisher Filter (Meta) -->
                        <?php if($show_publisher && !empty($publishers)): ?>
                         <div class="mb-8">
                            <?php
                            awt_render_dropdown_filter(__('Publisher', 'author-website-templates'), 'publisher', $publishers, 'Search publishers...', $icon_chevron_up);
                            ?>
                        </div>
                        <?php endif; ?>

                        <!-- ISBN Filter (Meta Input) -->
                         <?php if($show_isbn): ?>
                         <div class="mb-8">
                            <h3 class="font-bold text-primary text-sm uppercase tracking-wider mb-4 flex justify-between cursor-pointer awt-accordion-trigger">
                                <?php _e('ISBN', 'author-website-templates'); ?> <?php echo $icon_chevron_up; ?>
                            </h3>
                            <div class="space-y-3 awt-accordion-content">
                                <div class="relative">
                                    <input type="text" class="awt-filter-isbn w-full pl-10 pr-4 py-2 bg-paper border border-gray-200 rounded-lg focus:outline-none focus:border-accent text-sm transition" placeholder="<?php _e('ISBN-10 or ISBN-13', 'author-website-templates'); ?>">
                                     <?php echo $icon_search; ?>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                         <!-- Price Filter (Range Logic) -->
                         <?php if($show_price): ?>
                         <div class="mb-8">
                            <?php 
                            $price_ranges = [
                                '0-10' => 'Under $10',
                                '10-20' => '$10 - $20',
                                '20-30' => '$20 - $30',
                                '30-50' => '$30 - $50',
                                '50+' => '$50+'
                            ];
                            awt_render_dropdown_filter(__('Price', 'author-website-templates'), 'price', $price_ranges, 'Search prices...', $icon_chevron_up);
                            ?>
                        </div>
                        <?php endif; ?>

                        <!-- Year Filter (Meta) -->
                        <?php if($show_year && !empty($years)): ?>
                         <div class="mb-8">
                            <?php 
                            // Sort years desc
                            rsort($years);
                            awt_render_dropdown_filter(__('Publish Year', 'author-website-templates'), 'year', $years, 'Search years...', $icon_chevron_up);
                            ?>
                        </div>
                        <?php endif; ?>

                         <!-- Age Filter (Meta) -->
                        <?php if($show_age && !empty($ages)): ?>
                         <div class="mb-8">
                            <?php 
                            awt_render_dropdown_filter(__('Reading Age', 'author-website-templates'), 'age', $ages, 'Search reading age...', $icon_chevron_up); 
                            ?>
                        </div>
                        <?php endif; ?>
                        
                         <!-- Rating Filter (Meta Logic) -->
                        <?php if($show_rating): ?>
                         <div class="mb-8">
                            <?php 
                            $rating_options = [
                                '5' => '5 Stars',
                                '4' => '4 Stars & Up',
                                '3' => '3 Stars & Up'
                            ];
                            awt_render_dropdown_filter(__('Rating', 'author-website-templates'), 'rating', $rating_options, 'Search ratings...', $icon_chevron_up);
                            ?>
                        </div>
                        <?php endif; ?>

                        <button class="awt-apply-filters w-full py-3 bg-primary text-white text-xs font-bold uppercase rounded hover:bg-slate-800 transition shadow-lg shadow-blue-900/10">
                            <?php _e('Apply Filters', 'author-website-templates'); ?>
                        </button>
                        <button class="awt-reset-filters w-full py-3 mt-2 text-gray-400 text-xs font-bold uppercase hover:text-accent transition text-white">
                            <?php _e('Reset All', 'author-website-templates'); ?>
                        </button>

                    </div>
                </aside>
                <?php endif; ?>

                <div class="<?php echo $show_sidebar ? 'md:col-span-9' : 'md:col-span-12'; ?>">

                    <!-- Top Bar -->
                    <div class="flex flex-col sm:flex-row justify-between items-center mb-8 bg-white p-4 rounded-lg shadow-sm border border-gray-100">
                        <p class="text-sm text-secondary font-medium mb-3 sm:mb-0 awt-files-result-count">
                            Showing <span class="font-bold text-primary"><?php echo $start_result; ?> - <?php echo $end_result; ?></span> of <span class="font-bold text-primary"><?php echo $total_books; ?></span> Results
                        </p>
                        <?php if($show_sorting): ?>
                        <div class="flex items-center gap-3">
                            <span class="text-xs font-bold text-gray-400 uppercase"><?php _e('Sort By:', 'author-website-templates'); ?></span>
                            <select class="awt-sort-books bg-paper border border-gray-200 text-primary text-sm rounded px-3 py-2 focus:outline-none focus:border-accent cursor-pointer transition">
                                <option value="date_desc"><?php _e('Newest Arrivals', 'author-website-templates'); ?></option>
                                <option value="price_asc"><?php _e('Price: Low to High', 'author-website-templates'); ?></option>
                                <option value="price_desc"><?php _e('Price: High to Low', 'author-website-templates'); ?></option>
                                <option value="rating_desc"><?php _e('Top Rated', 'author-website-templates'); ?></option>
                            </select>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Book Grid -->
                    <div class="awt-book-grid-container grid gap-8" style="grid-template-columns: repeat(<?php echo intval($columns); ?>, minmax(0, 1fr));">
                        <?php 
                        if ($book_query->have_posts()) :
                            while ($book_query->have_posts()) : $book_query->the_post();
                                $book_id = get_the_ID();
                                
                                // --- 1. Get Initial Prices from Meta ---
                                $raw_price = get_post_meta($book_id, '_rsbs_book_price', true);
                                $raw_sale_price = get_post_meta($book_id, '_rsbs_book_sale_price', true);

                                // Clean data to ensure they are numbers
                                $regular_price = (float) preg_replace('/[^0-9.]/', '', $raw_price);
                                $sale_price = (float) preg_replace('/[^0-9.]/', '', $raw_sale_price);

                                // --- 2. Linked Product Override (Your Logic) ---
                                if(function_exists('rswpbs_get_linked_product')){
                                    $linked_product = rswpbs_get_linked_product();
                                    if ($linked_product) {
                                        $regular_price = $linked_product->get_regular_price();
                                        $sale_price = $linked_product->get_sale_price();
                                    }
                                }

                                // --- 3. Calculate Logic ---
                                // Check if there is a valid sale
                                $has_sale = !empty($sale_price) && $sale_price < $regular_price && $sale_price > 0;
                                
                                // Determine Price to show
                                $display_price = $has_sale ? $sale_price : $regular_price;
                                
                                // Calculate Savings Percentage
                                $savings_pct = 0;
                                if ($has_sale && $regular_price > 0) {
                                    $savings_pct = round((($regular_price - $sale_price) / $regular_price) * 100);
                                }

                                // Other Data
                                $rating = get_post_meta($book_id, '_rsbs_average_book_rating', true);
                                if (!is_numeric($rating)) $rating = 0;
                                
                                $author_terms = get_the_terms($book_id, 'book-author');
                                $author_name = $author_terms ? $author_terms[0]->name : 'Unknown Author';
                                $cat_terms = get_the_terms($book_id, 'book-category');
                                $cat_name = $cat_terms ? $cat_terms[0]->name : '';
                                
                                $img_url = get_the_post_thumbnail_url($book_id, 'large');
                                $short_desc = get_post_meta($book_id, '_rswpbs_short_description', true);
                                $permalink = get_permalink();
                                $buy_links = get_post_meta($book_id, 'rswpbs_also_available_website_list', true);
                                $buy_btn_text = get_post_meta($book_id, '_rsbs_buy_btn_text', true);
                                $buy_btn_link = get_post_meta($book_id, '_rsbs_buy_btn_link', true);
                                $format_val = get_post_meta($book_id, '_rsbs_book_format', true);
                        ?>
                        <div class="group bg-white rounded-xl shadow-sm hover:shadow-xl hover:-translate-y-1 transition duration-300 overflow-hidden border border-gray-100 flex flex-col">
                            <div class="relative p-6 bg-[#f1f5f9] flex justify-center items-center h-64 overflow-hidden">
                                <?php if($format_val): ?>
                                <span class="absolute top-4 left-4 bg-accent text-white text-[10px] font-bold px-2 py-1 rounded uppercase z-10"><?php echo esc_html($format_val); ?></span>
                                <?php endif; ?>
                                
                                <?php if($img_url): ?>
                                <img src="<?php echo esc_url($img_url); ?>" class="h-48 shadow-lg rounded transform group-hover:scale-105 transition duration-500">
                                <?php else: ?>
                                <div class="h-48 w-32 bg-gray-200 shadow-lg rounded flex items-center justify-center text-gray-400 text-xs">No Image</div>
                                <?php endif; ?>
                            </div>

                            <div class="p-5 flex-1 flex flex-col">
                                
                                <div class="mb-3 flex justify-between items-start">
                                    <span class="text-[10px] font-bold text-accent uppercase tracking-widest px-1 py-0.5 rounded mt-1">
                                        <?php echo esc_html($cat_name); ?>
                                    </span>

                                    <div class="flex flex-col items-end">
                                        <?php if ($has_sale) : ?>
                                            <span class="text-[10px] font-bold text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded mb-1">
                                                Save <?php echo $savings_pct; ?>%
                                            </span>
                                            <div class="flex items-center gap-1.5 leading-none">
                                                <span class="text-xs text-gray-400 line-through decoration-gray-400">
                                                    $<?php echo number_format($regular_price, 2); ?>
                                                </span>
                                                <span class="text-sm font-bold text-primary">
                                                    $<?php echo number_format($sale_price, 2); ?>
                                                </span>
                                            </div>
                                        <?php else : ?>
                                            <span class="text-sm font-bold text-primary mt-1">
                                                <?php echo $display_price > 0 ? '$' . number_format($display_price, 2) : 'Free'; ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <h3 class="text-xl font-serif font-bold text-primary mb-1 group-hover:text-accent transition">
                                    <a href="<?php echo esc_url($permalink); ?>"><?php the_title(); ?></a>
                                </h3>

                                <div class="flex items-center mb-2">
                                    <div class="flex text-yellow-400 text-xs gap-0.5">
                                        <?php for($i=1; $i<=5; $i++) {
                                            echo $i <= $rating ? $icon_star : str_replace('text-yellow-400', 'text-gray-300', $icon_star);
                                        } ?>
                                    </div>
                                    <span class="text-[10px] text-gray-400 font-medium ml-1.5">(<?php echo esc_html($rating); ?>)</span>
                                </div>

                                <div class="flex items-center gap-2 mb-3">
                                    <?php echo $icon_pen; ?>
                                    <span class="text-xs font-bold text-secondary"><?php echo esc_html($author_name); ?></span>
                                </div>

                                <p class="text-xs text-secondary mb-4 line-clamp-3 leading-relaxed"><?php echo esc_html(wp_trim_words($short_desc, 20)); ?></p>

                                <div class="mt-auto space-y-3">
                                    <div class="flex flex-wrap gap-2">
                                        <?php
                                        echo '<a target="_blank" href="'.esc_url($buy_btn_link).'"
                                            class="flex-1 min-w-[110px] flex items-center justify-center gap-1 py-2
                                                bg-gray-50 border border-gray-200 rounded text-xs font-bold text-primary
                                                hover:bg-white hover:border-[#FF9900] hover:text-[#FF9900] transition">'
                                            . esc_html($buy_btn_text) .
                                        '</a>';

                                        if (!empty($buy_links)) {
                                            foreach (array_slice($buy_links, 0, 4) as $link) {
                                                echo '<a target="_blank" href="'.esc_url($link['book_url']).'"
                                                    class="flex-1 min-w-[110px] flex items-center justify-center gap-1 py-2
                                                        bg-gray-50 border border-gray-200 rounded text-xs font-bold text-primary
                                                        hover:bg-white hover:border-[#FF9900] hover:text-[#FF9900] transition">'
                                                    . esc_html($link['website_name']) .
                                                '</a>';
                                            }
                                        }
                                        ?>
                                    </div>

                                    <div class="flex items-center gap-2 w-full">
                                        
                                        <?php 
                                        // 1. Shortcode Check & Output
                                        if ( shortcode_exists('rswpbs_book_loop_btn') ) {
                                            echo do_shortcode( '[rswpbs_book_loop_btn]' );
                                        } 
                                        ?>

                                        <a href="<?php echo esc_url($permalink); ?>" class="flex-1 block py-2.5 border border-primary text-primary text-center text-xs font-bold uppercase rounded hover:bg-primary hover:text-white transition">
                                            <?php _e('View Details', 'author-website-templates'); ?>
                                        </a>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <?php endwhile; wp_reset_postdata(); ?>
                        <?php else: ?>
                            <p class="col-span-3 text-center text-gray-500 py-12"><?php _e('No books found matching your criteria.', 'author-website-templates'); ?></p>
                        <?php endif; ?>
                    </div>

                    <!-- Pagination -->
                    <!-- Note: Implementation simplified for View.js update -->
                    <div class="awt-pagination mt-16 flex justify-center gap-2">
                        <?php 
                        $total_pages = $book_query->max_num_pages;

                        if ($pagination_type === 'load_more') {
                             if ($total_pages > 1) {
                                echo '<div class="text-center w-full">'; // Centering container
                                echo '<button id="awt-load-more-btn" data-page="1" class="px-8 py-3 bg-white border border-gray-200 text-primary font-bold uppercase text-xs rounded shadow-sm hover:border-accent hover:text-accent transition">';
                                _e('Load More Books', 'author-website-templates');
                                echo '</button>';
                                echo '</div>';
                             }
                        } else {
                            // Numbers
                            if ($total_pages > 1) {
                                $current = max(1, get_query_var('paged'));
                                
                                // Prev
                                if ($current > 1) {
                                    echo '<button data-page="'.($current-1).'" class="awt-page-link w-10 h-10 flex items-center justify-center rounded bg-white border border-gray-200 text-secondary hover:border-accent hover:text-accent transition font-bold text-sm">'.$icon_arrow_left.'</button>';
                                }

                                // Pages (Simplified range)
                                for ($i = 1; $i <= $total_pages; $i++) {
                                    if ($i == $current) {
                                        echo '<button class="w-10 h-10 flex items-center justify-center rounded bg-primary text-white font-bold text-sm">'.$i.'</button>';
                                    } else {
                                        echo '<button data-page="'.$i.'" class="awt-page-link w-10 h-10 flex items-center justify-center rounded bg-white border border-gray-200 text-secondary hover:border-accent hover:text-accent transition font-bold text-sm">'.$i.'</button>';
                                    }
                                }

                                // Next
                                if ($current < $total_pages) {
                                    echo '<button data-page="'.($current+1).'" class="awt-page-link w-10 h-10 flex items-center justify-center rounded bg-white border border-gray-200 hover:border-accent hover:text-white text-primary hover:bg-primary transition font-bold text-sm">'.$icon_arrow_right.'</button>';
                                }
                            }
                        }
                        ?>
                    </div>

                </div>
            </div>
        </div>
    </div>
</section>
