jQuery(document).ready(function($){
    let currentPostType = null;
    let currentPage = 1;
    let currentSearch = '';
    let selectedPosts = new Set();

    function updateSelectedCount(){
        $('#posttopdf-selected-count').text('Posts Selected: ' + selectedPosts.size);
    }

    function showLoader(container) {
        container.html('<p style="font-weight:bold;">Loading...</p>');
    }

    function loadPosts(){
        if(!currentPostType) return;
        const container = $('#posttopdf-post-list-container');
        showLoader(container);

        $.ajax({
            url: posttopdf_ajax.url,
            method: 'POST',
            data: {
                action: 'posttopdf_load_posts',
                nonce: posttopdf_ajax.nonce,
                post_type: currentPostType,
                page: currentPage,
                search: currentSearch
            },
            success: function(response){
                console.log(response); // Debug
                if(!response.success){
                    alert('Error loading posts');
                    container.html('');
                    return;
                }
                const data = response.data;
                let html = '';

                if(data.posts.length === 0){
                    html = '<p>No posts found.</p>';
                } else {
                    data.posts.forEach(post => {
                        const checked = selectedPosts.has(post.ID) ? 'checked' : '';
                        html += `<label><input type="checkbox" class="posttopdf-post-checkbox" data-post-id="${post.ID}" ${checked}> ${post.title}</label><br>`;
                    });
                }

                html += '<div id="posttopdf-pagination" style="margin-top:10px;">';
                if(currentPage > 1){
                    html += '<button type="button" id="posttopdf-prev-page" class="button">Previous Page</button> ';
                }
                if(currentPage < data.max_num_pages){
                    html += '<button type="button" id="posttopdf-next-page" class="button">Next Page</button> ';
                }
                html += '<button type="button" id="posttopdf-select-all" class="button" style="margin-left:10px;">Select All</button>';
                html += '</div>';

                container.html(html);
                updateSelectedCount();
            },
            error: function(){
                alert('Error loading posts');
                $('#posttopdf-post-list-container').html('');
            }
        });
    }

    // Tab click
    $('#posttopdf-tabs').on('click', '.posttopdf-tab-btn', function(){
        currentPostType = $(this).data('post-type');
        currentPage = 1;
        currentSearch = '';
        selectedPosts.clear();
        $('#posttopdf-search').val('');
        loadPosts();
    });

    // Search input
    $('#posttopdf-search').on('input', function(){
        currentSearch = $(this).val();
        currentPage = 1;
        loadPosts();
    });

    // Pagination prev/next
    $('#posttopdf-post-list-container').on('click', '#posttopdf-prev-page', function(){
        if(currentPage > 1){ currentPage--; loadPosts(); }
    });
    $('#posttopdf-post-list-container').on('click', '#posttopdf-next-page', function(){
        currentPage++; loadPosts();
    });

    // Checkbox toggle
    $('#posttopdf-post-list-container').on('change', '.posttopdf-post-checkbox', function(){
        const postId = parseInt($(this).data('post-id'));
        if($(this).is(':checked')) selectedPosts.add(postId);
        else selectedPosts.delete(postId);
        updateSelectedCount();
    });

    // Reset all
    $('#posttopdf-reset-btn').on('click', function(){
        selectedPosts.clear();
        $('#posttopdf-post-list-container .posttopdf-post-checkbox').prop('checked', false);
        updateSelectedCount();
    });

    // Select all visible posts
    $('#posttopdf-post-list-container').on('click', '#posttopdf-select-all', function(){
        $('#posttopdf-post-list-container .posttopdf-post-checkbox').each(function(){
            const postId = parseInt($(this).data('post-id'));
            if(!selectedPosts.has(postId)){
                selectedPosts.add(postId);
                $(this).prop('checked', true);
            }
        });
        updateSelectedCount();
    });

    // Preview PDF button
    $('#posttopdf-preview-btn').on('click', function(){
        if(selectedPosts.size === 0){
            alert('Please select some posts first.');
            return;
        }
        let ids = Array.from(selectedPosts).join(',');
        let url = posttopdf_ajax.preview_url + encodeURIComponent(ids) + '&preview_nonce=' + posttopdf_ajax.preview_nonce;

        $('#posttopdf-preview-frame').hide();
        $('#posttopdf-preview-modal').fadeIn();
        $('#posttopdf-preview-frame').attr('src', '');

        if($('#posttopdf-preview-modal .loading-text').length === 0){
            $('#posttopdf-preview-modal').append('<p class="loading-text" style="font-weight:bold;">Loading PDF Preview...</p>');
        }

        $('#posttopdf-preview-frame').attr('src', url);
        $('#posttopdf-preview-frame').off('load').on('load', function(){
            $('.loading-text').remove();
            $(this).fadeIn();
        });
    });

    // Close preview
    $('#posttopdf-preview-close').on('click', function(){
        $('#posttopdf-preview-modal').fadeOut();
        $('#posttopdf-preview-frame').attr('src', '');
        $('.loading-text').remove();
    });

    // Generate PDF (download)
    $('#posttopdf-generate-btn').on('click', function(){
        if(selectedPosts.size === 0){
            alert('Please select some posts first.');
            return;
        }
        let ids = Array.from(selectedPosts);
        let form = $('<form method="post" action="' + posttopdf_ajax.url + '"></form>');
        form.append('<input type="hidden" name="action" value="posttopdf_generate_pdf">');
        form.append('<input type="hidden" name="nonce" value="' + posttopdf_ajax.nonce + '">');
        ids.forEach(id => {
            form.append('<input type="hidden" name="ids[]" value="' + id + '">');
        });
        $('body').append(form);
        form.submit();
        form.remove();
    });

    // Auto-select first tab on load
    $('#posttopdf-tabs .posttopdf-tab-btn:first').trigger('click');
});
