jQuery(document).ready(function ($) {
    if (typeof aurora_lite_load_more === 'undefined') {
        console.warn('aurora_lite_load_more is not defined');
        return;
    }

    let currentPage = parseInt(aurora_lite_load_more.current_page) || 1;
    let loading = false;
    const $loadMoreBtn = $('#load-more-posts');
    const $postDiv = $('.masonry-container, .archive-posts');
    const maxPages = parseInt(aurora_lite_load_more.max_pages) || 1;
    const masonryEnabled = typeof aurora_lite_masonry_config !== 'undefined' && aurora_lite_masonry_config.enabled;

    $loadMoreBtn.on('click', function () {
        if (loading || currentPage >= maxPages) return;

        loading = true;
        currentPage++;

        $.ajax({
            url: aurora_lite_load_more.ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aurora_lite_load_more',
                paged: currentPage,
                security: aurora_lite_load_more.nonce,
                query_vars: aurora_lite_load_more.query_vars
            },
            beforeSend: function () {
                $loadMoreBtn.text('Loading...').prop('disabled', true);
            },
            success: function (response) {
                if (response.success && response.data.content) {
                    const $newItems = $(response.data.content);

                    if (masonryEnabled) {
                        $(document).trigger('aurora:postsAppended', [$newItems]);
                    } else {
                        $postDiv.append($newItems);
                    }

                    if (currentPage >= maxPages) {
                        $loadMoreBtn.remove();
                    } else {
                        $loadMoreBtn.text('Load More Posts').prop('disabled', false);
                    }
                } else {
                    console.error('Error:', response.data.message || 'No content received.');
                    $loadMoreBtn.remove();
                }

                loading = false;
            },
            error: function (xhr) {
                console.error('AJAX Error:', xhr.responseText);
                $loadMoreBtn.text('Load More Posts').prop('disabled', false);
                loading = false;
            }
        });
    });
});