/**
 * JavaScript para carregar mais posts do blog via AJAX
 * 
 * @package Upgram
 * @since 1.27.0
 */

(function($) {
    'use strict';
    
    $(document).ready(function() {
        const $loadMoreBtn = $('#upgram-load-more-posts');
        const $loading = $('.upgram-blog-listing-loading');
        const $grid = $('#upgram-blog-posts-grid');
        
        if (!$loadMoreBtn.length) {
            return;
        }
        
        let currentPage = parseInt($loadMoreBtn.data('page')) || 2;
        let isLoading = false;
        
        $loadMoreBtn.on('click', function(e) {
            e.preventDefault();
            
            if (isLoading) {
                return;
            }
            
            isLoading = true;
            $loadMoreBtn.prop('disabled', true);
            $loading.show();
            
            $.ajax({
                url: upgramBlog.ajax_url,
                type: 'POST',
                data: {
                    action: 'upgram_load_more_blog_posts',
                    nonce: upgramBlog.nonce,
                    page: currentPage
                },
                success: function(response) {
                    if (response.success && response.data.html) {
                        // Adicionar novos posts ao grid
                        $grid.append(response.data.html);
                        
                        // Atualizar página atual
                        currentPage = response.data.next_page || currentPage + 1;
                        
                        // Verificar se há mais posts
                        if (!response.data.has_more) {
                            $loadMoreBtn.fadeOut();
                            $loading.hide();
                        } else {
                            $loadMoreBtn.prop('disabled', false);
                            $loading.hide();
                        }
                    } else {
                        // Não há mais posts
                        $loadMoreBtn.fadeOut();
                        $loading.hide();
                    }
                },
                error: function() {
                    alert('Erro ao carregar mais artigos. Tente novamente.');
                    $loadMoreBtn.prop('disabled', false);
                    $loading.hide();
                },
                complete: function() {
                    isLoading = false;
                }
            });
        });
    });
})(jQuery);



