<?php
/**
 * Book Details Block - Server-Side Render
 * * Displays comprehensive book information with a 2-column layout.
 * Replicates the exact logic from single-book.php for consistency.
 * * @package Author_Website_Templates
 * @since 1.0.9
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Extract block attributes
$show_gallery = isset($attributes['showGallery']) ? (bool) $attributes['showGallery'] : true;
$show_meta = isset($attributes['showMeta']) ? (bool) $attributes['showMeta'] : true;
$show_buy_buttons = isset($attributes['showBuyButtons']) ? (bool) $attributes['showBuyButtons'] : true;
$show_description = isset($attributes['showDescription']) ? (bool) $attributes['showDescription'] : true;
$show_price = isset($attributes['showPrice']) ? (bool) $attributes['showPrice'] : true;
$show_formats = isset($attributes['showFormats']) ? (bool) $attributes['showFormats'] : true;

// Design attributes
$section_bg_color = isset($attributes['sectionBgColor']) ? esc_attr($attributes['sectionBgColor']) : '#FFFDF5';
$title_color = isset($attributes['titleColor']) ? esc_attr($attributes['titleColor']) : '#264653';
$accent_color = isset($attributes['accentColor']) ? esc_attr($attributes['accentColor']) : '#EF476F';
$btn_bg_color = isset($attributes['btnBgColor']) ? esc_attr($attributes['btnBgColor']) : '#FFD166';

// Label attributes
$label_back = isset($attributes['labelBack']) ? $attributes['labelBack'] : __('Back to All Books', 'author-website-templates');
$label_latest = isset($attributes['labelLatest']) ? $attributes['labelLatest'] : __('Latest Release!', 'author-website-templates');
$label_illustrated = isset($attributes['labelIllustrated']) ? $attributes['labelIllustrated'] : __('Illustrated by', 'author-website-templates');
$label_order = isset($attributes['labelOrder']) ? $attributes['labelOrder'] : __('Order Your Copy!', 'author-website-templates');
$label_peek = isset($attributes['labelPeek']) ? $attributes['labelPeek'] : __('A Peek Inside!', 'author-website-templates');
$label_about = isset($attributes['labelAbout']) ? $attributes['labelAbout'] : __('About the Book', 'author-website-templates');
$label_details = isset($attributes['labelDetails']) ? $attributes['labelDetails'] : __('Book Details', 'author-website-templates');

// Get current post ID and check context
$book_id = null;

if ( ! empty( $attributes['bookId'] ) ) {
    $book_id = intval( $attributes['bookId'] );
} elseif ( is_singular( 'book' ) ) {
    $book_id = get_the_ID();
}

// Variables init
$book_data = [];

// Show placeholder if no Book ID is found
if ( ! $book_id  && ! ( defined('REST_REQUEST') && REST_REQUEST ) && ! is_admin() ) {
    if ( current_user_can( 'edit_posts' ) ) {
        echo '<div class="awt-placeholder p-4 bg-yellow-50 border border-yellow-200 text-yellow-800 rounded text-center">';
        echo '<strong>' . esc_html__( 'Note:', 'author-website-templates' ) . '</strong> ' . esc_html__( 'Please provide a Book ID in the block settings or utilize this block on a Book single page.', 'author-website-templates' );
        echo '</div>';
    }
    return;
}

$is_book = get_post_type($book_id) === 'book';
$use_placeholder = !$is_book || is_admin() || (defined('REST_REQUEST') && REST_REQUEST);

if (!$use_placeholder) {
    // --- REAL DATA FETCHING (Copied from single-book.php) ---

    // Title & Cover
    $book_data['title'] = get_the_title($book_id);
    $book_data['cover_url'] = get_the_post_thumbnail_url($book_id, 'large');

    // Author/Illustrator Logic
    $author_terms = get_the_terms($book_id, 'book-author');
    $author_name = '';
    if ($author_terms && !is_wp_error($author_terms)) {
        $author_name = $author_terms[0]->name;
    } else {
        $author_name = get_post_meta($book_id, '_rsbs_book_translator', true);
    }
    $book_data['author_name'] = empty($author_name) ? __('Unknown Author', 'author-website-templates') : $author_name;

    // Description
    $description = get_post_meta($book_id, '_rsbs_short_description', true);
    if (empty($description)) {
        $description = get_the_content(null, false, $book_id);
    }
    if (empty($description)) {
        $description = get_the_excerpt($book_id);
    }
    $book_data['description'] = $description;

    // Buy Buttons
    $book_data['primary_btn_text'] = get_post_meta($book_id, '_rsbs_buy_btn_text', true);
    $book_data['primary_btn_link'] = get_post_meta($book_id, '_rsbs_buy_btn_link', true);
    $book_data['additional_stores'] = get_post_meta($book_id, 'rswpbs_also_available_website_list', true);

    // Price
    $book_data['regular_price'] = get_post_meta($book_id, '_rsbs_book_price', true);
    $book_data['sale_price'] = get_post_meta($book_id, '_rsbs_book_sale_price', true);
    
    $currenySign = '$';
    $currenySign = get_option('rswpbs_price_currency', '$');
    if (null === $currenySign) {
        $currenySign = '$';
    }
    // Formats
    $book_data['formats'] = get_post_meta($book_id, 'rswpbs_book_formats', true);

    // Gallery
    $book_data['gallery_images'] = get_post_meta($book_id, 'rswpbs_book_sample_content', true);

    // Book Details List (Exact Logic from single-book.php)
    // Assuming helper functions like rswpbs_get_book_reading_age might not be available in block context context, 
    // we use direct get_post_meta calls with the keys from register-cmb.php.

    $book_info_fields = [
        'availability' => [
            'value' => rswpbs_get_book_availability_status($book_id),
            'label' => rswpbs_static_text_availability(),
            'condition' => function ($value) {
                return !empty($value) && $value !== 'blank';
            }
        ],
        'original_title' => [
            'value' => rswpbs_get_book_original_name($book_id),
            'label' => rswpbs_static_text_original_title(),
            'wrapper' => function ($value) {
                $url = rswpbs_get_book_original_url();
                return $url ? "<a href='" . esc_url($url) . "'>" . esc_html($value) . "</a>" : esc_html($value);
            }
        ],
        'categories' => [
            'value' => rswpbs_get_book_categories($book_id),
            'label' => rswpbs_static_text_categories(),
            'escape' => 'wp_kses_post'
        ],
        'series' => [
            'value' => rswpbs_get_book_series($book_id),
            'label' => rswpbs_static_text_series(),
            'escape' => 'wp_kses_post'
        ],
        'publish_date' => [
            'value' => rswpbs_get_book_publish_date($book_id),
            'label' => rswpbs_static_text_publish_date()
        ],
        'publish_year' => [
            'value' => rswpbs_get_book_publish_year($book_id),
            'label' => rswpbs_static_text_published_year(),
            'condition' => function () {
                return !empty(rswpbs_get_book_publish_date());
            }
        ],
        'publisher' => [
            'value' => esc_html(rswpbs_get_book_publisher_name($book_id)),
            'label' => rswpbs_static_text_publisher_name(),
            'escape' => false
        ],
        'pages' => [
            'value' => rswpbs_get_book_pages($book_id),
            'label' => rswpbs_static_text_total_pages()
        ],
        'isbn' => [
            'value' => rswpbs_get_book_isbn($book_id),
            'label' => rswpbs_static_text_isbn()
        ],
        'isbn_10' => [
            'value' => rswpbs_get_book_isbn_10($book_id),
            'label' => rswpbs_static_text_isbn_10()
        ],
        'isbn_13' => [
            'value' => rswpbs_get_book_isbn_13($book_id),
            'label' => rswpbs_static_text_isbn_13()
        ],
        'asin' => [
            'value' => rswpbs_get_book_asin($book_id),
            'label' => rswpbs_static_text_asin()
        ],
        'format' => [
            'value' => rswpbs_get_book_format($book_id),
            'label' => rswpbs_static_text_format()
        ],
        'country' => [
            'value' => rswpbs_get_book_country($book_id),
            'label' => rswpbs_static_text_country()
        ],
        'language' => [
            'value' => rswpbs_get_book_language($book_id),
            'label' => rswpbs_static_text_language()
        ],
        'translator' => [
            'value' => rswpbs_get_book_translator($book_id),
            'label' => rswpbs_static_text_translator()
        ],
        'file_size' => [
            'value' => rswpbs_get_book_file_size($book_id),
            'label' => rswpbs_static_text_file_size()
        ],
        'dimension' => [
            'value' => rswpbs_get_book_dimension($book_id),
            'label' => rswpbs_static_text_dimension()
        ],
        'weight' => [
            'value' => rswpbs_get_book_weight($book_id),
            'label' => rswpbs_static_text_weight()
        ],
        'file_format' => [
            'value' => rswpbs_get_book_file_format($book_id),
            'label' => rswpbs_static_text_file_format()
        ],
        'simultaneous_device_usage' => [
            'value' => rswpbs_get_simultaneous_device_usage($book_id),
            'label' => rswpbs_static_text_simultaneous_device_usage()
        ],
        'text_to_speech' => [
            'value' => rswpbs_get_book_text_to_speech($book_id),
            'label' => rswpbs_static_text_text_to_speech()
        ],
        'screen_reader' => [
            'value' => rswpbs_get_screen_reader($book_id),
            'label' => rswpbs_static_text_screen_reader()
        ],
        'enhanced_typesetting' => [
            'value' => rswpbs_get_enhanced_typesetting($book_id),
            'label' => rswpbs_static_text_enhanced_typesetting()
        ],
        'x_ray' => [
            'value' => rswpbs_get_x_ray($book_id),
            'label' => rswpbs_static_text_x_ray()
        ],
        'word_wise' => [
            'value' => rswpbs_get_word_wise($book_id),
            'label' => rswpbs_static_text_word_wise()
        ],
        'sticky_notes' => [
            'value' => rswpbs_get_sticky_notes($book_id),
            'label' => rswpbs_static_text_sticky_notes()
        ],
        'print_length' => [
            'value' => rswpbs_get_print_length($book_id),
            'label' => rswpbs_static_text_print_length()
        ],
        'avg_rate' => [
            'value' => rswpbs_get_avg_rate($book_id),
            'label' => rswpbs_static_text_avarage_ratings(),
            'escape' => 'wp_kses_post'
        ],
        'reading_date' => [
            'value' => rswpbs_get_book_reading_date($book_id),
            'label' => rswpbs_static_text_reading_date(),
            'escape' => 'wp_kses_post'
        ]
    ];
    $book_data['details'] = $book_info_fields;

} else {
    // --- PLACEHOLDER DATA (For Editor Preview) ---
    $book_data = [
        'title' => __('The Magical Adventure', 'author-website-templates'),
        'cover_url' => RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/images/book-placeholder.png',
        'author_name' => 'Jane Doe',
        'description' => __('Join our hero on an incredible journey through magical lands. Perfect for young readers!', 'author-website-templates'),
        'primary_btn_text' => 'Buy Now',
        'primary_btn_link' => '#',
        'additional_stores' => [
            ['website_name' => 'Amazon', 'book_url' => '#'],
            ['website_name' => 'Barnes & Noble', 'book_url' => '#']
        ],
        'regular_price' => '$19.99',
        'sale_price' => '$14.99',
        'formats' => [
            ['format_name' => 'Hardcover', 'format_price' => '$19.99'],
            ['format_name' => 'Kindle', 'format_price' => '$9.99']
        ],
        'gallery_images' => [
            ['upload_image' => RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/images/book-placeholder.png'],
            ['upload_image' => RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/images/book-placeholder.png']
        ],
        'details' => [
            'availability' => [
                'value' => 'In Stock',
                'label' => 'Availability:',
            ],
            'categories' => [
                'value' => 'Fantasy, Adventure',
                'label' => 'Categories:',
                'escape' => 'wp_kses_post'
            ],
            'series' => [
                'value' => 'Magic World Series',
                'label' => 'Series:',
                'escape' => 'wp_kses_post'
            ],
            'publish_date' => [
                'value' => '2024-01-12',
                'label' => 'Publish Date:'
            ],
            'publish_year' => [
                'value' => '2024',
                'label' => 'Published Year:'
            ],
            'publisher' => [
                'value' => "<a href='#'>Example Press</a>",
                'label' => 'Publisher:',
                'escape' => false
            ],
            'pages' => [
                'value' => '32',
                'label' => 'Total Pages:'
            ],
            'isbn' => [
                'value' => '978-1234567890',
                'label' => 'ISBN:'
            ],
            'asin' => [
                'value' => 'B0TESTASIN',
                'label' => 'ASIN:'
            ],
            'format' => [
                'value' => 'Hardcover',
                'label' => 'Format:'
            ],
            'country' => [
                'value' => 'USA',
                'label' => 'Country:'
            ],
            'language' => [
                'value' => 'English',
                'label' => 'Language:'
            ],
            'translator' => [
                'value' => 'N/A',
                'label' => 'Translator:'
            ],
        ]

    ];
}

// Fallback for missing cover
// Fallback for missing cover
if (empty($book_data['cover_url'])) {
    $book_data['cover_url'] = RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/images/book-placeholder.png';
}

// Back Link URL
$books_archive_url = get_post_type_archive_link('book');

// CSS Variables for Container
$css_variables = [
    '--awt-section-bg' => $section_bg_color,
    '--awt-title-color' => $title_color,
    '--awt-accent-color' => $accent_color,
    '--awt-btn-bg' => $btn_bg_color,
];
$style_attr = '';
foreach ($css_variables as $var => $value) {
    if (!empty($value)) {
        $style_attr .= "{$var}: {$value}; ";
    }
}
?>

<div class="awt-book-details-container" style="<?php echo esc_attr($style_attr); ?>">
    
    <?php if (isset($attributes['detailsStyle']) && $attributes['detailsStyle'] === 'elegant'): ?>
    
        <!-- ELEGANT STYLE -->
        <section class="py-16 md:py-24 border-b border-gray-100" style="background-color: var(--awt-section-bg);">
            <div class="awt-container container mx-auto px-6 max-w-6xl">
                <?php if (!$use_placeholder && $books_archive_url): ?>
                    <a href="<?php echo esc_url($books_archive_url); ?>" 
                       class="text-slate-500 hover:text-slate-900 font-medium text-sm mb-8 inline-flex items-center transition-colors"
                       style="color: var(--awt-accent-color);">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                        <?php echo esc_html($label_back); ?>
                    </a>
                <?php endif; ?>

                <div class="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-start">
                    
                    <!-- LEFT COL: Cover & Gallery -->
                    <div class="lg:col-span-5 space-y-8">
                        <div class="relative group">
                            <img src="<?php echo esc_url($book_data['cover_url']); ?>" 
                                 alt="<?php echo esc_attr(sprintf(__('Book cover for %s', 'author-website-templates'), $book_data['title'])); ?>" 
                                 class="rounded shadow-xl w-full mx-auto hover:shadow-2xl transition-all duration-300">
                        </div>

                        <?php if ($show_gallery && !empty($book_data['gallery_images'])): 
                            // Check for valid images
                             $valid_images = [];
                             if(is_array($book_data['gallery_images'])){
                                foreach($book_data['gallery_images'] as $img){
                                     if(is_array($img) && !empty($img['upload_image'])) $valid_images[] = $img['upload_image'];
                                     elseif(is_string($img) && !empty($img)) $valid_images[] = $img;
                                }
                             }
                        ?>
                            <?php if (!empty($valid_images)): ?>
                            <div>
                                <h4 class="text-sm font-bold text-slate-800 uppercase tracking-widest mb-4 border-b border-gray-200 pb-2" style="color: var(--awt-title-color);">
                                    <?php echo esc_html($label_peek); ?>
                                </h4>
                                <div class="grid grid-cols-3 gap-4">
                                    <?php foreach ($valid_images as $img_url): ?>
                                        <img src="<?php echo esc_url($img_url); ?>" alt="Interior art" class="rounded shadow-sm hover:opacity-80 transition-opacity cursor-pointer">
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>

                    <!-- RIGHT COL: Details -->
                    <div class="lg:col-span-7 space-y-10">
                        <div>
                            <span class="inline-block py-1 px-3 bg-slate-800 text-white text-xs font-bold uppercase tracking-wider rounded mb-4" style="background-color: var(--awt-title-color);">
                                <?php echo esc_html($label_latest); ?>
                            </span>
                            <h1 class="text-4xl md:text-5xl font-serif font-bold text-slate-800 mb-4 leading-tight" style="color: var(--awt-title-color);">
                                <?php echo esc_html($book_data['title']); ?>
                            </h1>
                            <p class="text-xl text-slate-500 font-light">
                                <?php echo esc_html($label_illustrated); ?> <span class="font-bold text-slate-800" style="color: var(--awt-title-color);"><?php echo esc_html($book_data['author_name']); ?></span>
                            </p>
                            
                            <?php if ($show_price && (!empty($book_data['regular_price']) || !empty($book_data['sale_price']))):
                                $book_data['regular_price'] = str_replace('$', '', $book_data['regular_price']);
                                $book_data['sale_price'] = str_replace('$', '', $book_data['sale_price']);
                                ?>
                                <div class="mt-4 text-lg font-bold">
                                    <?php if (!empty($book_data['sale_price'])): ?>
                                        <span class="line-through text-slate-400 mr-2"><?php echo esc_html($currenySign . $book_data['regular_price']); ?></span>
                                        <span class="text-2xl text-slate-900" style="color: var(--awt-accent-color);"><?php echo esc_html($currenySign . $book_data['sale_price']); ?></span>
                                    <?php else: ?>
                                        <span class="text-2xl text-slate-900" style="color: var(--awt-accent-color);"><?php echo esc_html($currenySign . $book_data['regular_price']); ?></span>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <?php if ($show_buy_buttons): ?>
                        <div class="bg-white p-8 rounded border border-gray-200 shadow-sm">
                            <h3 class="text-lg font-bold text-slate-800 mb-6 text-center uppercase tracking-wide" style="color: var(--awt-title-color);">
                                <?php echo esc_html($label_order); ?>
                            </h3>
                            <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                                <?php if (!empty($book_data['primary_btn_link'])): ?>
                                    <a href="<?php echo esc_url($book_data['primary_btn_link']); ?>" 
                                       class="px-6 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-transparent text-sm uppercase tracking-wider text-center bg-slate-900 text-white hover:bg-slate-800 shadow-sm hover:shadow-md"
                                       style="background-color: var(--awt-btn-bg); color: var(--awt-title-color);">
                                        <?php echo esc_html(!empty($book_data['primary_btn_text']) ? $book_data['primary_btn_text'] : __('Buy Now', 'author-website-templates')); ?>
                                    </a>
                                <?php endif; ?>
                                
                                <?php if (!empty($book_data['additional_stores']) && is_array($book_data['additional_stores'])): ?>
                                    <?php foreach ($book_data['additional_stores'] as $store):
                                        $store_name = isset($store['website_name']) ? $store['website_name'] : '';
                                        $store_url = isset($store['book_url']) ? $store['book_url'] : '';
                                        if (empty($store_name) || empty($store_url)) continue;
                                    ?>
                                        <a href="<?php echo esc_url($store_url); ?>" 
                                           class="px-6 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-gray-200 text-sm uppercase tracking-wider text-center bg-white text-slate-800 hover:border-slate-800 hover:bg-gray-50"
                                           target="_blank">
                                            <?php echo esc_html($store_name); ?>
                                        </a>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ($show_description && !empty($book_data['description'])): ?>
                        <div>
                            <h3 class="text-2xl font-serif font-bold text-slate-800 mb-4" style="color: var(--awt-title-color);">
                                <?php echo esc_html($label_about); ?>
                            </h3>
                            <div class="text-lg text-slate-500 leading-relaxed space-y-4 font-light">
                                <?php echo wpautop(wp_kses_post($book_data['description'])); ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ($show_meta && !empty($book_data['details'])): ?>
                        <div>
                            <h3 class="text-2xl font-serif font-bold text-slate-800 mb-4" style="color: var(--awt-title-color);">
                                <?php echo esc_html($label_details); ?>
                            </h3>
                            <ul class="grid grid-cols-1 sm:grid-cols-2 gap-y-3 gap-x-8 text-slate-700 bg-white p-6 rounded border border-gray-100 text-sm">
                                <?php foreach ($book_data['details'] as $key => $field): 
                                    $value = $field['value'] ?? '';
                                    if(empty($value)) continue;
                                    if(isset($field['condition']) && is_callable($field['condition']) && !$field['condition']($value)) continue;
                                    if(isset($field['wrapper']) && is_callable($field['wrapper'])) $value = $field['wrapper']($value);
                                    
                                    // Basic escape check
                                    if(!isset($field['escape']) || $field['escape'] === 'esc_html') $value = esc_html($value);
                                    elseif($field['escape'] === 'wp_kses_post') $value = wp_kses_post($value);
                                ?>
                                <li class="flex justify-between border-b border-gray-50 pb-2">
                                    <span class="font-bold text-slate-500"><?php echo esc_html($field['label']); ?></span>
                                    <span><?php echo $value; ?></span>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>
                        
                    </div>
                </div>
            </div>
        </section>

    <?php else: ?>
    
        <!-- FUN (DEFAULT) STYLE -->
        <section class="awt-book-details py-16 md:py-24" style="background-color: var(--awt-section-bg);">
            <div class="awt-container container mx-auto px-6 max-w-6xl">
                <?php if (!$use_placeholder && $books_archive_url): ?>
                    <a href="<?php echo esc_url($books_archive_url); ?>" class="font-bold hover:opacity-80 mb-8 inline-block"
                        style="color: var(--awt-accent-color);">
                        ← <?php echo esc_html($label_back); ?>
                    </a>
                <?php endif; ?>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-start">

                    <div class="space-y-6">
                        <img src="<?php echo esc_url($book_data['cover_url']); ?>"
                            alt="<?php echo esc_attr(sprintf(__('Book cover for %s', 'author-website-templates'), $book_data['title'])); ?>"
                            class="rounded-lg shadow-2xl w-full max-w-lg mx-auto transform -rotate-2 transition-all duration-300 hover:rotate-2">

                        <?php if ($show_gallery && !empty($book_data['gallery_images']) && is_array($book_data['gallery_images'])):
                            // Verify if any image actually exists
                            $has_images = false;
                            foreach ($book_data['gallery_images'] as $item) {
                                if ((is_array($item) && !empty($item['upload_image'])) || (is_string($item) && !empty($item))) {
                                    $has_images = true;
                                    break;
                                }
                            }
                            ?>
                            <?php if ($has_images): ?>
                                <div>
                                    <h4 class="text-2xl font-black pt-4 mb-4" style="color: var(--awt-title-color);">
                                        <?php echo esc_html($label_peek); ?>
                                    </h4>
                                    <div class="grid grid-cols-3 gap-4">
                                        <?php foreach ($book_data['gallery_images'] as $index => $image_data):
                                            $img_url = '';
                                            if (is_array($image_data) && isset($image_data['upload_image'])) {
                                                $img_url = $image_data['upload_image'];
                                            } elseif (is_string($image_data)) {
                                                $img_url = $image_data;
                                            }
                                            if (empty($img_url))
                                                continue;
                                            ?>
                                            <img src="<?php echo esc_url($img_url); ?>"
                                                alt="<?php esc_attr_e('Interior preview', 'author-website-templates'); ?>"
                                                class="rounded-md shadow-md transition-all hover:scale-105 hover:shadow-lg">
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php if ($show_formats && !empty($book_data['formats']) && is_array($book_data['formats'])): ?>
                            <div class="pt-4">
                                <div class="grid grid-cols-2 gap-3">
                                    <?php foreach ($book_data['formats'] as $format):
                                        $format_name = isset($format['name']) ? $format['name'] : '';
                                        $format_price = isset($format['price']) ? $format['price'] : '';
                                        $format_link = isset($format['link']) ? $format['link'] : '';
                                        if (empty($format_name))
                                            continue;
                                        ?>

                                        <a href="<?php echo esc_url($format_link); ?>" class="block no-underline" target="_blank"
                                            rel="noopener">
                                            <div class="text-center p-3 rounded-lg border-2 transition-all hover:shadow-md bg-white"
                                                style="border-color: var(--awt-btn-bg);">

                                                <div class="font-black text-sm uppercase" style="color: var(--awt-title-color);">
                                                    <?php echo esc_html($format_name); ?>
                                                </div>

                                                <?php if (!empty($format_price)): ?>
                                                    <div class="text-lg font-bold mt-1" style="color: var(--awt-accent-color);">
                                                        <?php echo esc_html($format_price); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </a>

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

                    </div>

                    <div class="space-y-8">
                        <div>
                            <span class="block font-bold uppercase tracking-wider" style="color: var(--awt-accent-color);">
                                <?php echo esc_html($label_latest); ?>
                            </span>
                            <h1 class="text-4xl md:text-6xl font-black my-2 leading-tight"
                                style="color: var(--awt-title-color);">
                                <?php echo esc_html($book_data['title']); ?>
                            </h1>
                            <p class="text-2xl font-bold" style="color: var(--awt-title-color); opacity: 0.8;">
                                <?php echo esc_html(sprintf('%s %s', $label_illustrated, $book_data['author_name'])); ?>
                            </p>

                            <?php if ($show_price && (!empty($book_data['regular_price']) || !empty($book_data['sale_price']))): ?>
                                <div class="mt-4 text-lg font-bold">
                                    <?php if (!empty($book_data['sale_price'])): ?>
                                        <span class="line-through"
                                            style="color: var(--awt-title-color); opacity: 0.5; margin-right: 0.5rem;">
                                            <?php echo esc_html($currenySign . $book_data['regular_price']); ?>
                                        </span>
                                        <span class="text-2xl" style="color: var(--awt-accent-color);">
                                            <?php echo esc_html($currenySign . $book_data['sale_price']); ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-2xl" style="color: var(--awt-accent-color);">
                                            <?php echo esc_html($currenySign . $book_data['regular_price']); ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <?php if ($show_buy_buttons && (!empty($book_data['primary_btn_link']) || !empty($book_data['additional_stores']))): ?>
                            <div class="bg-white p-6 rounded-xl shadow-lg"
                                style="border: 2px solid calc(var(--awt-btn-bg) * 1);"> 
                                <!-- Note: Calc hack or RGBA needed for opacity, stuck with solid for vars unless using HEX->RGB. Keeping simple for now or using inline styles for border if desired, but user asked for vars. 
                                     The original was: style="border: 2px solid <?php echo $btn_bg_color; ?>30;" which is HEX opacity. 
                                     For CSS vars, we'll lose the opacity unless we convert. Let's stick to the color var for now. -->
                                <h3 class="text-3xl font-black mb-6 text-center" style="color: var(--awt-title-color);">
                                    <?php echo esc_html($label_order); ?>
                                </h3>

                                <div class="flex flex-wrap gap-4 justify-center">
                                    <?php if (!empty($book_data['primary_btn_link'])): ?>
                                        <a href="<?php echo esc_url($book_data['primary_btn_link']); ?>"
                                            class="px-8 py-3 rounded-full font-black text-lg transition-all hover:scale-105 shadow-lg"
                                            style="background-color: var(--awt-btn-bg); color: #000;" target="_blank">
                                            <?php echo esc_html(!empty($book_data['primary_btn_text']) ? $book_data['primary_btn_text'] : __('Buy Now', 'author-website-templates')); ?>
                                        </a>
                                    <?php endif; ?>

                                    <?php if (!empty($book_data['additional_stores']) && is_array($book_data['additional_stores'])): ?>
                                        <?php foreach ($book_data['additional_stores'] as $store):
                                            $store_name = isset($store['website_name']) ? $store['website_name'] : '';
                                            $store_url = isset($store['book_url']) ? $store['book_url'] : '';
                                            if (empty($store_name) || empty($store_url))
                                                continue;
                                            ?>
                                            <a href="<?php echo esc_url($store_url); ?>"
                                                class="px-8 py-3 rounded-full font-black text-lg transition-all hover:scale-105 bg-white shadow-lg"
                                                style="color: var(--awt-title-color);" target="_blank">
                                                <?php echo esc_html($store_name); ?>
                                            </a>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($show_description && !empty($book_data['description'])): ?>
                            <div>
                                <h3 class="text-3xl font-black mb-4" style="color: var(--awt-title-color);">
                                    <?php echo esc_html($label_about); ?>
                                </h3>
                                <div class="text-lg leading-relaxed space-y-4"
                                    style="color: var(--awt-title-color); opacity: 0.8;">
                                    <?php echo wpautop(wp_kses_post($book_data['description'])); ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($show_meta && !empty($book_data['details'])): ?>
                            <div>
                                <h3 class="text-3xl font-black mb-4" style="color: var(--awt-title-color);">
                                    <?php echo esc_html($label_details); ?>
                                </h3>
                                <ul class="list-none space-y-2 bg-white p-6 rounded-lg shadow-sm"
                                    style="color: var(--awt-title-color); opacity: 0.8;">

                                    <?php foreach ($book_data['details'] as $key => $field):

                                        // Skip if value empty
                                        $value = $field['value'] ?? '';
                                        if (empty($value))
                                            continue;

                                        // Check condition (if exists)
                                        if (isset($field['condition']) && is_callable($field['condition'])) {
                                            if (!$field['condition']($value))
                                                continue;
                                        }

                                        // Apply wrapper (if exists)
                                        if (isset($field['wrapper']) && is_callable($field['wrapper'])) {
                                            $value = $field['wrapper']($value);
                                        }

                                        // Escape handling
                                        if (isset($field['escape'])) {
                                            if ($field['escape'] === 'esc_html') {
                                                $value = esc_html($value);
                                            } elseif ($field['escape'] === 'wp_kses_post') {
                                                $value = wp_kses_post($value);
                                            } elseif ($field['escape'] === false) {
                                                // skip escape
                                            }
                                        } else {
                                            // default escape
                                            $value = esc_html($value);
                                        }

                                        ?>
                                        <li>
                                            <strong
                                                style="color: var(--awt-title-color);"><?php echo esc_html($field['label']); ?></strong>
                                            <span><?php echo $value; ?></span>
                                        </li>

                                    <?php endforeach; ?>

                                </ul>

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