/**
 * AJAX Load More Books Handler
 * 
 * Handles the "Load More" button click for Book List blocks.
 * Sends AJAX request, appends new books to the container, and manages button state.
 * 
 * @package Author_Website_Templates
 * @since 1.0.9
 */

(function ($) {
    'use strict';

    $(document).ready(function () {
        // Handle Load More button click
        $('.awt-load-more-btn').on('click', function (e) {
            e.preventDefault();

            const $button = $(this);
            const $container = $($button.data('container'));

            // Get current state
            const queryData = $container.data('query');
            const currentPage = parseInt($container.data('current-page')) || 1;
            const maxPages = parseInt($container.data('max-pages')) || 1;

            // Check if there are more pages
            if (currentPage >= maxPages) {
                $button.hide();
                return;
            }

            // Disable button and show loading state
            $button.prop('disabled', true);
            const originalText = $button.text();
            $button.text('Loading...');

            // Send AJAX request
            $.ajax({
                url: awtLoadMore.ajaxurl,
                type: 'POST',
                data: {
                    action: 'awt_load_more_books',
                    nonce: awtLoadMore.nonce,
                    query_data: JSON.stringify(queryData),
                    current_page: currentPage
                },
                success: function (response) {
                    if (response.success && response.html) {
                        // Append new books to container
                        $container.append(response.html);

                        // Update current page
                        const newPage = currentPage + 1;
                        $container.data('current-page', newPage);
                        $container.attr('data-current-page', newPage);

                        // Hide button if no more pages
                        if (newPage >= response.max_pages) {
                            $button.hide();
                        } else {
                            // Re-enable button
                            $button.prop('disabled', false);
                            $button.text(originalText);
                        }
                    } else {
                        console.error('Load More failed:', response);
                        $button.prop('disabled', false);
                        $button.text('Error - Try Again');
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', error);
                    $button.prop('disabled', false);
                    $button.text('Error - Try Again');
                }
            });
        });
    });

})(jQuery);
