jQuery(document).ready(function($) {
    
    // Tab Navigation
    $('.ccspllms_nav_link').on('click', function(e) {
        e.preventDefault();
        
        var tab = $(this).data('tab');
        
        // Remove active classes
        $('.ccspllms_nav_link').removeClass('active');
        $('.ccspllms_tab_content').removeClass('active');
        
        // Add active classes
        $(this).addClass('active');
        $('#ccspllms_' + tab).addClass('active');
    });
    
    // Regenerate File
    $('#ccspllms_regenerate_btn').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.html();
        
        $btn.html('<i class="fas fa-spinner fa-spin"></i> Generating...').prop('disabled', true);
        
        $.ajax({
            url: ccspllms_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'ccspllms_regenerate',
                nonce: ccspllms_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    showNotification(response.data.message, 'success');
                    updateStats(response.data);
                } else {
                    showNotification('Error: ' + response.data, 'error');
                }
            },
            error: function() {
                showNotification('Network error occurred', 'error');
            },
            complete: function() {
                $btn.html(originalText).prop('disabled', false);
            }
        });
    });
    
    // Toggle Post Inclusion
    $('.ccspllms_post_toggle').on('change', function() {
        var $toggle = $(this);
        var postId = $toggle.data('post-id');
        var excluded = $toggle.is(':checked') ? 0 : 1;
        
        $.ajax({
            url: ccspllms_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'ccspllms_toggle_post',
                nonce: ccspllms_ajax.nonce,
                post_id: postId,
                excluded: excluded
            },
            success: function(response) {
                if (response.success) {
                    showNotification('Post updated successfully', 'success');
                } else {
                    showNotification('Error updating post', 'error');
                    $toggle.prop('checked', !$toggle.is(':checked'));
                }
            }
        });
    });
    
    // Bulk Actions
    $('#ccspllms_bulk_apply').on('click', function() {
        var action = $('#ccspllms_bulk_action').val();
        var selectedPosts = [];
        
        $('.ccspllms_post_checkbox:checked').each(function() {
            selectedPosts.push($(this).val());
        });
        
        if (selectedPosts.length === 0) {
            showNotification('Please select posts first', 'warning');
            return;
        }
        
        $.ajax({
            url: ccspllms_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'ccspllms_bulk_action',
                nonce: ccspllms_ajax.nonce,
                action_type: action,
                post_ids: selectedPosts
            },
            success: function(response) {
                if (response.success) {
                    showNotification('Bulk action completed', 'success');
                    location.reload();
                } else {
                    showNotification('Error performing bulk action', 'error');
                }
            }
        });
    });



// Open modal on edit button click
    $('.edit-custom-content').on('click', function(e) {
        e.preventDefault();
        var postId = $(this).data('post-id');
        var row = $(this).closest('tr');
        var preview = row.find('.custom-content-preview').attr('title') || '';
        $('#custom_content_textarea').val(preview);
        $('#custom_content_modal').data('post-id', postId).fadeIn(200);
    });

    // Close modal
    $('.ccspllms_modal_close, #cancel_custom_content').on('click', function() {
        $('#custom_content_modal').fadeOut(200);
        $('#custom_content_textarea').val('');
    });

    // Save custom content (AJAX)
    $('#save_custom_content').on('click', function() {
        var postId = $('#custom_content_modal').data('post-id');
        var content = $('#custom_content_textarea').val();
        $.post(ajaxurl, {
            action: 'ccspllms_save_custom_content',
            post_id: postId,
            custom_content: content,
            _wpnonce: ccspllms_ajax.nonce
        }, function(response) {
            if (response.success) {
                location.reload(); // Reload to update table
            } else {
                alert('Error saving custom content');
            }
        });
    });

    // Optional: Close modal when clicking outside modal content
    $('#custom_content_modal').on('click', function(e) {
        if ($(e.target).is('#custom_content_modal')) {
            $(this).fadeOut(200);
            $('#custom_content_textarea').val('');
        }
    });


       // Edit" button in your Content Management admin page End
    // Download File
    $('#ccspllms_download_btn').on('click', function() {
        window.location.href = '/llms.txt';
        showNotification('File download started', 'success');
    });
    
    // Settings Form
    // $('#ccspllms_settings_form').on('submit', function(e) {
    //     e.preventDefault();
        
    //     var formData = $(this).serialize();
        
    //     $.ajax({
    //         url: ccspllms_ajax.ajax_url,
    //         type: 'POST',
    //         data: formData + '&action=ccspllms_save_settings&nonce=' + ccspllms_ajax.nonce,
    //         success: function(response) {
    //             if (response.success) {
    //                 showNotification('Settings saved successfully', 'success');
    //             } else {
    //                 showNotification('Error saving settings', 'error');
    //             }
    //         }
    //     });
    // });
    

// Deleting in cron page
    // Select all checkboxes (event delegation)
    $(document).on('change', '#ccspllms-select-all', function() {
        var checked = $(this).prop('checked');
        $('#ccspllms-history-table .ccspllms-row-checkbox').prop('checked', checked);
    });

    // Bulk delete (event delegation)
    $(document).on('click', '#ccspllms-delete-selected', function(e) {
        e.preventDefault();
        var ids = $('#ccspllms-history-table .ccspllms-row-checkbox:checked').map(function() {
            return $(this).val();
        }).get();
        if (ids.length === 0) {
            alert('Please select at least one entry to delete.');
            return;
        }
        if (!confirm('Are you sure you want to delete the selected entries?')) return;
        $.post(ccspllms_ajax.ajax_url, {
            action: 'ccspllms_delete_history',
            ids: ids,
            ccspllms_delete_history: ccspllms_ajax.nonce
        }, function(response) {
            if (response.success) {
                ids.forEach(function(id) {
                    $('#ccspllms-history-table tr[data-row-id="' + id + '"]').remove();
                });
             showNotification('Selected rows deleted successfully', 'success');    
            } else {
                showNotification('Delete failed', 'error');
            }
        });
    });

    // Single delete (event delegation)
    $(document).on('click', '.ccspllms-delete-single', function(e) {
        e.preventDefault();
        var id = $(this).data('row-id');
        if (!confirm('Are you sure you want to delete this entry?')) return;
        $.post(ccspllms_ajax.ajax_url, {
            action: 'ccspllms_delete_history',
            ids: [id],
            ccspllms_delete_history: ccspllms_ajax.nonce
        }, function(response) {
            if (response.success) {
                $('#ccspllms-history-table tr[data-row-id="' + id + '"]').remove();
            showNotification('Row deleted successfully', 'success');  
            } else {
                showNotification('Delete failed', 'error');
            }
        });
    });


    $(document).on('change', '.bot_status_toggle', function() {
        var $checkbox = $(this);
        var botName = $checkbox.data('bot'); // ✅ correct way
        var status = $checkbox.is(':checked') ? 1 : 0; // ✅ checkbox status
        
        $.post(ccspllms_ajax.ajax_url, {
            action: 'ccspllms_update_bot_status',
            bot_name: botName,
            status: status,
            ccspllms_update_bot_nonce: ccspllms_ajax.nonce
        }, function(response) {
            if (response.success) {
                showNotification('Bot status updated', 'success');
            } else {
                showNotification('Failed to update bot status', 'error');
            }
        });
    });

    $('#ccspllms_export_csv').on('click', function(e) {
        e.preventDefault();
        window.location.href = ccspllms_ajax.ajax_url + '?action=ccspllms_export_analytics&format=csv&ccspllms_export_nonce=' + ccspllms_ajax.nonce;
        
    });
    $('#ccspllms_export_json').on('click', function(e) {
        e.preventDefault();
        window.location.href = ccspllms_ajax.ajax_url + '?action=ccspllms_export_analytics&format=json&ccspllms_export_nonce=' + ccspllms_ajax.nonce;
        
    });



    // Analytics Chart (placeholder for Chart.js integration)
    if ($('#ccspllms_analytics_chart').length) {
        loadAnalyticsChart();
    }
    
    // Utility Functions
    function showNotification(message, type) {
        var alertClass = 'ccspllms_alert ';
        switch(type) {
            case 'success':
                alertClass += 'success';
                break;
            case 'error':
                alertClass += 'error';
                break;
            case 'warning':
                alertClass += 'warning';
                break;
            default:
                alertClass += 'info';
        }
        
        var notification = $('<div class="' + alertClass + '">' + message + '</div>');
        $('.ccspllms_content').prepend(notification);
        
        setTimeout(function() {
            notification.fadeOut(function() {
                $(this).remove();
            });
        }, 3000);
    }
    
    function updateStats(data) {
        if (data.timestamp) {
            $('.ccspllms_last_generated').text(data.timestamp);
        }
        if (data.file_size) {
            $('.ccspllms_file_size').text(data.file_size);
        }
    }
    
    

function loadAnalyticsChart() {
    if (typeof window.ccspllmsAnalyticsData === 'undefined') {
        return;
    }
    var stats = window.ccspllmsAnalyticsData;
    var labels = stats.map(function(item) { return item.date; });
    var data = stats.map(function(item) { return item.visit_count; });

    var ctx = document.getElementById('ccspllms_analytics_chart').getContext('2d');
    if (window.ccspllmsChartInstance) {
        window.ccspllmsChartInstance.destroy();
    }
    window.ccspllmsChartInstance = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Bot Visits',
                data: data,
                borderColor: 'rgba(102,126,234,1)',
                backgroundColor: 'rgba(118,75,162,0.15)',
                pointBackgroundColor: 'rgba(102,126,234,1)',
                pointBorderColor: '#fff',
                pointRadius: 5,
                pointHoverRadius: 7,
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: true,
                    labels: {
                        color: '#764ba2',
                        font: { size: 16, weight: 'bold' }
                    }
                },
                title: {
                    display: true,
                    text: 'Bot Visits (Last 30 Days)',
                    color: '#667eea',
                    font: { size: 18, weight: 'bold' }
                },
                tooltip: {
                    backgroundColor: '#667eea',
                    titleColor: '#fff',
                    bodyColor: '#fff'
                }
            },
            scales: {
                x: {
                    title: { display: true, text: 'Date', color: '#764ba2', font: { size: 14 } },
                    ticks: { color: '#667eea' }
                },
                y: {
                    title: { display: true, text: 'Visits', color: '#764ba2', font: { size: 14 } },
                    beginAtZero: true,
                    ticks: { color: '#667eea' }
                }
            }
        }
    });
}


    
    // Auto-refresh analytics every 30 seconds
    if ($('.ccspllms_analytics_page').length) {
        setInterval(function() {
            loadAnalyticsChart();
        }, 30000);
    }
});