/**
 * ============================================================================
 * EONSR AEO AGENT - BULK PROCESSOR SCRIPT
 * 
 * @description Handles Bulk CSV Uploads, Real-time Dashboard, and History Tracking.
 * @version     Pro UI Version
 * @author      Refactored Assistant
 * ============================================================================
 */

jQuery(document).ready(function($) {
    'use strict';

    // ========================================================================
    // [SECTION] GLOBAL STATE & CONFIG
    // ========================================================================

    const EONSR_AEO_LOG_PREFIX = '[EONSR AEO Bulk]';
    
    // Timer handles
    let statusCheckInterval  = null;
    let searchDebounceTimer  = null;

    // Current Session State
    let currentBulkId        = null;
    let currentType          = null; 
    let currentBulkStatus    = null; 

    // History Pagination State
    let historyState = {
        page: 1,
        search: ''
    };

    /**
     * Logger utility for professional debugging
     */
    const logger = {
        info: (msg, data = null) => {
            if (data) console.log(`${EONSR_AEO_LOG_PREFIX} ℹ️ ${msg}`, data);
            else console.log(`${EONSR_AEO_LOG_PREFIX} ℹ️ ${msg}`);
        },
        error: (msg, error = null) => {
            console.error(`${EONSR_AEO_LOG_PREFIX} ❌ ${msg}`, error);
        },
        warn: (msg) => {
            console.warn(`${EONSR_AEO_LOG_PREFIX} ⚠️ ${msg}`);
        }
    };

    // --- Init: Load History on Page Load ---
    logger.info('Initializing Bulk Processor...');
    eonsr_aeo_agent_load_bulk_history();

    // ========================================================================
    // [SECTION] UI RENDERERS (DASHBOARD & LISTS)
    // ========================================================================

    /**
     * Renders the main Dashboard Status UI (Progress bar, Stats, Header).
     * 
     * @param {Object} params - Data object containing bulkId, filename, stats, etc.
     */
    function eonsr_aeo_agent_render_dashboard_ui(params) {
        const $statusDiv = $('#aeo-agent-bulk-status');
        
        const bulkId   = params.bulkUploadId;
        const filename = params.filename || '---';
        const total    = parseInt(params.totalJobs) || 0;
        const isResume = params.isResume || false;
        
        // Stats Calculation (From Step 1 in logic)
        const stats = params.stats || { success: 0, failed: 0, active: total };
        const processedCount = stats.success + stats.failed; 

        // Calculate Percentage
        let percent = total > 0 ? Math.round((processedCount / total) * 100) : 0;
        
        // Determine Status Badge Config
        let statusConfig = { 
            text: 'Đang chờ...', 
            class: 'pending', 
            icon: 'dashicons-clock', 
            color: '#64748b', 
            bg: '#f1f5f9' 
        };

        if (currentBulkStatus === 'processing') {
            statusConfig = { 
                text: 'Đang xử lý...', 
                class: 'processing', 
                icon: 'dashicons-update', 
                color: '#2563eb', 
                bg: '#eff6ff' 
            };
        } else if (currentBulkStatus === 'completed') {
            // Check for partial errors
            if (stats.failed > 0) {
                 statusConfig = { 
                     text: 'Hoàn tất (Có lỗi)', 
                     class: 'warning', 
                     icon: 'dashicons-warning', 
                     color: '#d97706', 
                     bg: '#fffbeb' 
                 };
            } else {
                 statusConfig = { 
                     text: 'Hoàn thành', 
                     class: 'completed', 
                     icon: 'dashicons-yes-alt', 
                     color: '#16a34a', 
                     bg: '#dcfce7' 
                 };
            }
            percent = 100; // Force full bar on completion
        } else if (currentBulkStatus === 'cancelled' || currentBulkStatus === 'failed') {
            statusConfig = { 
                text: 'Đã hủy / Lỗi', 
                class: 'cancelled', 
                icon: 'dashicons-no-alt', 
                color: '#dc2626', 
                bg: '#fee2e2' 
            };
            percent = 100; // Force full bar (red)
        }

        // Render HTML Template
        const html = `
        <div class="aeo-pro-dashboard">
            <!-- Header -->
            <div class="pro-header">
                <div class="pro-file-icon"><span class="dashicons dashicons-media-spreadsheet"></span></div>
                <div class="pro-file-meta">
                    <h3 class="pro-filename" title="${filename}">${filename}</h3>
                    <div class="pro-id-badge">ID: ${bulkId ? bulkId.slice(-8) : '...'}</div>
                </div>
                <!-- Badge Status -->
                <div class="pro-status-badge" style="color:${statusConfig.color}; background:${statusConfig.bg}">
                    <span class="dashicons ${statusConfig.icon}"></span> ${statusConfig.text}
                </div>
            </div>

            <!-- Hero Stats Section -->
            <div class="pro-hero-section">
                <div class="pro-progress-group">
                    <div class="pro-progress-labels">
                        <span class="label">Tiến độ xử lý</span>
                        <span class="percent" style="color:${statusConfig.color}">${percent}%</span>
                    </div>
                    <div class="pro-progress-track">
                        <div class="pro-progress-bar" style="width: ${percent}%; background: ${statusConfig.color}"></div>
                    </div>
                </div>

                <div class="pro-stats-grid">
                    <div class="stat-box">
                        <div class="stat-val">${total}</div>
                        <div class="stat-lbl">Tổng bài</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-val success">${stats.success}</div>
                        <div class="stat-lbl">Thành công</div>
                    </div>
                    <div class="stat-box" style="border-right:none;">
                        <div class="stat-val error">${stats.failed}</div>
                        <div class="stat-lbl">Thất bại / Hủy</div>
                    </div>
                </div>
            </div>

            <!-- Actions Toolbar -->
            <div class="pro-actions-bar">
                <div class="action-left">
                    <button type="button" class="pro-btn-action" id="check-scheduled-status-btn">
                        <span class="dashicons dashicons-update"></span> Kiểm tra ngay
                    </button>
                    <!-- Auto Refresh Button -->
                    <button type="button" class="pro-btn-action toggle-auto" id="auto-refresh-btn" data-active="false">
                        <span class="icon-spin dashicons dashicons-controls-play"></span> 
                        <span class="btn-text">Tự động cập nhật</span>
                    </button>
                </div>
                <div class="action-right">
                    ${isResume 
                        ? `<button class="pro-btn-link" onclick="location.reload()">Quay lại</button>` 
                        : `<button class="pro-btn-primary" onclick="location.reload()">+ Upload Mới</button>`
                    }
                </div>
            </div>
        </div>`;
        
        $statusDiv.html(html);
    }

    /**
     * Renders the detailed list of jobs (cards).
     * @param {Array} jobs 
     */
    function eonsr_aeo_agent_render_scheduled_list(jobs) {
        const $jobsList = $('#aeo-agent-bulk-jobs-list');
        
        if (!jobs || jobs.length === 0) {
            $jobsList.html('<div style="text-align:center; padding:40px; color:#94a3b8;">Chưa có dữ liệu bài viết nào.</div>');
            return;
        }

        let html = '<div class="aeo-pro-list">';

        jobs.forEach(function(job, index) {
            const status = job.status || 'scheduled';
            
            // Icon & Color mapping
            let sMeta = { icon: 'dashicons-clock', class: 'neutral', label: 'Waiting' };
            if(status === 'completed')  sMeta = { icon: 'dashicons-yes', class: 'success', label: 'Done' };
            if(status === 'processing') sMeta = { icon: 'dashicons-update', class: 'processing', label: 'Running' };
            if(status === 'failed')     sMeta = { icon: 'dashicons-warning', class: 'error', label: 'Failed' };
            if(status === 'cancelled')  sMeta = { icon: 'dashicons-no', class: 'error', label: 'Cancelled' };

            // Date Formatting
            let timeStr = '';
            if (job.scheduledTime) {
                timeStr = String(job.scheduledTime).replace('T', ' ').slice(0, 16);
            }

            // Action Button Logic
            const canCancel = (status === 'scheduled' || status === 'pending') && currentBulkStatus !== 'cancelled';
            const actionHtml = canCancel 
                ? `<button class="pro-icon-btn cancel-single-job-btn" data-id="${job.jobId}" title="Hủy bài này"><span class="dashicons dashicons-trash"></span></button>` 
                : `<span class="status-dot ${sMeta.class}"></span>`;

            html += `
            <div class="pro-job-card ${status}" id="job-row-${job.jobId}">
                <div class="job-col-id">#${index + 1}</div>
                <div class="job-col-main">
                    <div class="job-term" title="${job.primary_term}">${job.primary_term}</div>
                    <div class="job-sub">
                        <span class="sub-tag"><span class="dashicons dashicons-admin-users"></span> ${job.audience || 'General'}</span>
                        ${timeStr ? `<span class="sub-tag"><span class="dashicons dashicons-calendar-alt"></span> ${timeStr}</span>` : ''}
                    </div>
                </div>
                <div class="job-col-status">
                    <span class="pro-pill ${sMeta.class}">${sMeta.label}</span>
                </div>
                <div class="job-col-action">
                    ${actionHtml}
                </div>
            </div>`;
        });
        
        html += '</div>';
        $jobsList.html(html);
    }

    // ========================================================================
    // [SECTION] FORM SUBMISSION & UPLOAD
    // ========================================================================

    $('#aeo-agent-bulk-form').on('submit', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $fileInput = $('input[name="bulk_csv_file"]');
        const $submitBtn = $('#aeo-bulk-submit-btn');
        const $statusDiv = $('#aeo-agent-bulk-status');
        
        // 1. Validate Input
        if (!$fileInput[0].files.length) {
            Swal.fire('Lỗi', 'Vui lòng chọn file XLSX', 'warning');
            return;
        }

        const file = $fileInput[0].files[0];
        const fileName = file.name.toLowerCase();

        if (!fileName.endsWith('.xlsx')) {
            Swal.fire({
                icon: 'error',
                title: 'Sai định dạng file',
                text: 'Hệ thống chỉ chấp nhận file có đuôi .xlsx',
            });
            return;
        }
        
        // 2. Prepare UI for Upload
        logger.info(`Starting upload for file: ${fileName}`);
        $submitBtn.prop('disabled', true).html('⏳ Đang tải lên...');
        $statusDiv.html('<div class="notice notice-info"><p>📤 Đang xử lý file CSV...</p></div>');
        
        // 3. Prepare FormData
        const formData = new FormData($form[0]);
        formData.append('action', 'eonsr_aeo_agent_bulk_upload_csv');
        formData.append('nonce', eonsrAeoAgentData.bulkNonce);
        
        eonsr_aeo_agent_stop_auto_refresh_ui();
        
        // 4. Send AJAX
        $.ajax({
            url: eonsrAeoAgentData.ajaxurl, 
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            timeout: 300000, 
            success: function(response) {
                if (response.success) {
                    logger.info('Upload successful', response.data);
                    
                    const type = response.data.type || 'immediate';
                    currentType = type;
                    eonsr_aeo_agent_load_bulk_history(); // Reload history immediately

                    if (type === 'scheduled') {
                        eonsr_aeo_agent_handle_scheduled_success(response.data);
                    } else {
                        eonsr_aeo_agent_handle_immediate_success(response.data);
                    }
                } else {
                    logger.error('Upload failed with message', response.data);
                    eonsr_aeo_agent_handle_error(response.data);
                }
            },
            error: function(xhr, status, error) {
                logger.error('Upload network error', error);
                eonsr_aeo_agent_handle_error({ message: 'Lỗi kết nối: ' + error });
            },
            complete: function() {
                $submitBtn.prop('disabled', false).html('📤 Upload và Bắt đầu');
            }
        });
    });

    // ========================================================================
    // [SECTION] SCHEDULED MODE HANDLERS
    // ========================================================================

    /**
     * Handles success response from Scheduled Upload.
     */
    function eonsr_aeo_agent_handle_scheduled_success(data) {
        const $detailsDiv = $('#aeo-agent-bulk-details');
        currentBulkId = data.bulkUploadId;
        currentBulkStatus = 'scheduled'; 
        
        const total = data.totalJobs || (data.schedule ? data.schedule.length : 0);
        
        // Render Dashboard
        eonsr_aeo_agent_render_dashboard_ui({
            bulkUploadId: currentBulkId,
            filename: data.filename, 
            totalJobs: total,
            isResume: false
        });
        
        // Render List
        if (data.schedule && data.schedule.length > 0) {
            eonsr_aeo_agent_render_scheduled_list(data.schedule);
            $detailsDiv.show();
        } else if (total === 0) {
             $detailsDiv.show();
             $('#aeo-agent-bulk-jobs-list').html('<div class="notice notice-warning"><p>⚠️ File CSV hợp lệ nhưng không tìm thấy dữ liệu.</p></div>');
        }
        
        // Auto-start polling
        $('#auto-refresh-btn').click(); 
        
        // Reset Form
        $('#aeo-agent-bulk-form')[0].reset();
        $('#file-name-display').text('Chưa chọn file').css({'color': '#666', 'font-weight': 'normal'});
        $('#aeo-bulk-submit-btn').prop('disabled', true).addClass('disabled');
    }

    /**
     * Manual Check Status Button
     */
    $(document).on('click', '#check-scheduled-status-btn', function() {
        eonsr_aeo_agent_check_scheduled_status();
    });

    /**
     * Polls the server for current bulk status.
     */
    function eonsr_aeo_agent_check_scheduled_status() {
        if (!currentBulkId) return;
        
        const $btn = $('#check-scheduled-status-btn');
        $btn.prop('disabled', true).text('⏳...');
        
        $.ajax({
            url: eonsrAeoAgentData.ajaxurl,
            type: 'POST',
            data: {
                action: 'eonsr_aeo_agent_check_scheduled_bulk_status',
                nonce: eonsrAeoAgentData.bulkNonce,
                bulkUploadId: currentBulkId
            },
            success: function(response) {
                if (response.success) {
                    eonsr_aeo_agent_display_scheduled_status(response.data);
                } else {
                    if (response.data && response.data.code === 'NOT_FOUND_ON_SERVER') {
                        logger.warn('Bulk ID not found on server');
                        Swal.fire({ icon: 'info', title: 'Dữ liệu không tồn tại', text: response.data.message });
                        eonsr_aeo_agent_stop_auto_refresh_ui();
                        $('#aeo-agent-bulk-details').hide();
                        $('#aeo-agent-bulk-status').empty();
                        currentBulkId = null;
                        eonsr_aeo_agent_load_bulk_history();
                    } else {
                        logger.error('Check status returned error', response);
                    }
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text('📊 Kiểm tra ngay');
            }
        });
    }

    /**
     * Calculates status metrics and updates the UI.
     * Contains crucial status logic.
     */
    function eonsr_aeo_agent_display_scheduled_status(data) {
        const jobs = data.jobs || [];
        
        // 1. Recalculate metrics from job list
        let countTotal   = jobs.length;
        let countSuccess = 0;
        let countFailed  = 0; // Includes failed and cancelled
        let countActive  = 0; // Scheduled + Processing + Pending
        
        jobs.forEach(job => {
            const s = job.status;
            if (s === 'completed') {
                countSuccess++;
            } else if (s === 'failed' || s === 'cancelled') {
                countFailed++;
            } else {
                countActive++;
            }
        });

        // 2. Determine Global Status
        if (countActive === 0 && countTotal > 0) {
            // No active jobs -> Process Finished
            if (countSuccess === countTotal) {
                currentBulkStatus = 'completed';
            } else if (countFailed === countTotal) {
                currentBulkStatus = 'cancelled'; // or 'failed'
            } else {
                currentBulkStatus = 'completed'; // Completed with partial errors
            }
            
            logger.info('Bulk process finished. Stopping auto-refresh.');
            eonsr_aeo_agent_stop_auto_refresh_ui();
        } else if (countActive > 0) {
            currentBulkStatus = 'processing';
        }

        // 3. Re-render Dashboard with new stats
        eonsr_aeo_agent_render_dashboard_ui({
            bulkUploadId: currentBulkId,
            filename: data.filename || 'File Data',
            totalJobs: countTotal,
            stats: { 
                success: countSuccess,
                failed: countFailed,
                active: countActive
            },
            isResume: true 
        });
        
        // 4. Re-render Job List
        eonsr_aeo_agent_render_scheduled_list(jobs);
    }

    // ========================================================================
    // [SECTION] ACTIONS (CANCEL & VIEW)
    // ========================================================================
    
    // Action: Cancel Single Job
    $(document).on('click', '.cancel-single-job-btn', function() {
        const jobId = $(this).data('id');
        const $btn = $(this);

        Swal.fire({
            title: 'Hủy bài viết này?',
            text: "Bài viết này sẽ bị loại khỏi hàng chờ.",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#d63638',
            cancelButtonText: 'Không',
            confirmButtonText: 'Hủy bài'
        }).then((result) => {
            if (result.isConfirmed) {
                $btn.text('...').prop('disabled', true);
                $.ajax({
                    url: eonsrAeoAgentData.ajaxurl,
                    type: 'POST',
                    data: { action: 'eonsr_aeo_agent_cancel_job', nonce: eonsrAeoAgentData.bulkNonce, jobId: jobId },
                    success: function(response) {
                        if (response.success) {
                            $('#job-row-' + jobId).removeClass('scheduled pending').addClass('cancelled')
                                .find('.job-status-badge').html('🚫 Đã hủy');
                            $btn.remove();
                            
                            const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
                            Toast.fire({ icon: 'success', title: 'Đã hủy bài viết' });
                        } else {
                            Swal.fire('Lỗi', response.data.message, 'error');
                            $btn.text('[Hủy bài này]').prop('disabled', false);
                        }
                    }
                });
            }
        });
    });

    // Action: View Detail from History
    $(document).on('click', '.view-bulk-detail-btn', function() {
        const bulkId   = $(this).data('id');
        const filename = $(this).data('filename'); 
        const total    = $(this).data('total');
        const status   = $(this).data('status');
        
        logger.info(`Viewing details for bulk ID: ${bulkId}`);

        currentBulkId     = bulkId;
        currentType       = 'scheduled';
        currentBulkStatus = status;
        
        // Scroll to Dashboard
        const $target = $('#aeo-agent-bulk-status');
        if ($target.length) {
            $('html, body').animate({ scrollTop: $target.offset().top - 50 }, 'fast');
        }
        
        // Show Loading State
        $('#aeo-agent-bulk-status').html('<div class="notice notice-info inline"><p>⏳ Đang tải chi tiết cho file: <strong>' + filename + '</strong>...</p></div>');
        $('#aeo-agent-bulk-jobs-list').html('<p>Đang tải dữ liệu...</p>');
        $('#aeo-agent-bulk-details').show();

        // Init UI
        eonsr_aeo_agent_render_dashboard_ui({
            bulkUploadId: bulkId,
            filename: filename, 
            totalJobs: total,
            isResume: true 
        });

        // Check Status
        eonsr_aeo_agent_check_scheduled_status();
        
        // Auto-refresh logic
        if (status === 'processing') {
            eonsr_aeo_agent_start_auto_refresh_ui();
        } else {
            eonsr_aeo_agent_stop_auto_refresh_ui();
        }
    });

    // Action: Cancel Entire Bulk (Dashboard Button)
    $(document).on('click', '#cancel-bulk-btn', function() {
        if (!currentBulkId) return;

        Swal.fire({
            title: '⚠️ CẢNH BÁO',
            text: "Bạn có chắc muốn hủy toàn bộ tiến trình này không? Hành động này không thể hoàn tác.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d63638',
            confirmButtonText: 'Đồng ý hủy'
        }).then((result) => {
            if (result.isConfirmed) {
                const $btn = $('#cancel-bulk-btn');
                $btn.text('⏳ Đang hủy...').prop('disabled', true);
                
                currentBulkStatus = 'cancelled';
                eonsr_aeo_agent_stop_auto_refresh_ui();
                
                $.ajax({
                    url: eonsrAeoAgentData.ajaxurl,
                    type: 'POST',
                    data: { action: 'eonsr_aeo_agent_cancel_bulk', nonce: eonsrAeoAgentData.bulkNonce, bulkUploadId: currentBulkId },
                    success: function(response) {
                        if (response.success) {
                            $btn.remove();
                            $('#dashboard-status-text').css('color', '#d63638').text('Đã hủy');
                            
                            eonsr_aeo_agent_check_scheduled_status(); 
                            eonsr_aeo_agent_load_bulk_history(); 
                            
                            Swal.fire({ title: 'Đã hủy!', text: 'Tiến trình đã được hủy thành công.', icon: 'success', timer: 2000, showConfirmButton: false });
                        } else {
                            Swal.fire('Lỗi', response.data.message, 'error');
                            $btn.text('🚫 Hủy toàn bộ').prop('disabled', false);
                            currentBulkStatus = 'processing';
                        }
                    }
                });
            }
        });
    });

    // Action: Cancel Bulk from History (Stop Button)
    $(document).on('click', '.cancel-bulk-history-btn', function() {
        const bulkId = $(this).data('id');
        const $btn = $(this);

        Swal.fire({
            title: 'Dừng chạy file này?',
            text: "Các bài viết chưa chạy sẽ bị hủy. Tiến trình đang chạy sẽ dừng lại.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d63638',
            confirmButtonText: 'Dừng ngay',
            cancelButtonText: 'Không'
        }).then((result) => {
            if (result.isConfirmed) {
                $btn.prop('disabled', true);

                $.ajax({
                    url: eonsrAeoAgentData.ajaxurl,
                    type: 'POST',
                    data: { action: 'eonsr_aeo_agent_cancel_bulk', nonce: eonsrAeoAgentData.bulkNonce, bulkUploadId: bulkId },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Thành công', 'Đã dừng tiến trình.', 'success');
                            eonsr_aeo_agent_load_bulk_history(); 
                        } else {
                            Swal.fire('Lỗi', response.data.message, 'error');
                            $btn.prop('disabled', false);
                        }
                    }
                });
            }
        });
    });

    // ========================================================================
    // [SECTION] HISTORY MANAGEMENT
    // ========================================================================

    $('#refresh-history-btn').on('click', function() {
        eonsr_aeo_agent_load_bulk_history();
    });

    // Search Input with Debounce
    $('#history-search-input').on('keyup', function() {
        clearTimeout(searchDebounceTimer);
        const val = $(this).val().trim();
        searchDebounceTimer = setTimeout(function() {
            historyState.search = val;
            historyState.page = 1; 
            eonsr_aeo_agent_load_bulk_history();
        }, 500);
    });

    // Pagination Click
    $(document).on('click', '.aeo-page-btn', function() {
        const page = $(this).data('page');
        if (page) {
            historyState.page = page;
            eonsr_aeo_agent_load_bulk_history();
        }
    });

    /**
     * Loads bulk history data from server.
     */
    function eonsr_aeo_agent_load_bulk_history(callback) {
        const $tbody = $('#aeo-bulk-history-body');
        const $count = $('#history-total-count');
        
        $tbody.css('opacity', '0.5');

        $.ajax({
            url: eonsrAeoAgentData.ajaxurl,
            type: 'POST',
            data: {
                action: 'eonsr_aeo_agent_get_bulk_history',
                nonce: eonsrAeoAgentData.bulkNonce,
                paged: historyState.page,
                search: historyState.search
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    eonsr_aeo_agent_render_history_table(data.logs);
                    eonsr_aeo_agent_render_pagination(data.pagination);
                    $count.text(data.pagination.total_items + ' files');
                } else {
                    $tbody.html('<tr><td colspan="6">Lỗi tải dữ liệu.</td></tr>');
                }
                if (callback) callback();
            },
            complete: function() {
                $tbody.css('opacity', '1');
            }
        });
    }

    /**
     * Renders the History Table.
     */
    function eonsr_aeo_agent_render_history_table(logs) {
        const $tbody = $('#aeo-bulk-history-body');
        $tbody.empty();

        if (!logs || logs.length === 0) {
            $tbody.html('<tr><td colspan="6" style="text-align:center; padding:20px; color:#646970;">Không có dữ liệu lịch sử.</td></tr>');
            return;
        }

        logs.forEach(function(item) {
            let statusClass = '';
            let statusLabel = '';
            let actionButtons = '';
            let displayName = item.filename.replace(/\.[^/.]+$/, ""); // Remove extension

            // 1. Determine Status
            switch(item.status) {
                case 'processing': statusClass = 'processing'; statusLabel = 'Đang chạy'; break;
                case 'completed':  statusClass = 'completed';  statusLabel = 'Hoàn thành'; break;
                case 'cancelled':  
                case 'stopped':    statusClass = 'stopped';    statusLabel = 'Đã dừng'; break;
                case 'failed':     statusClass = 'failed';     statusLabel = 'Thất bại'; break;
                default:           statusClass = 'stopped';    statusLabel = item.status;
            }

            // 2. Determine Actions
            const viewBtn = `<button class="btn-act view view-bulk-detail-btn" 
                                data-id="${item.bulk_id}" 
                                data-filename="${item.filename}" 
                                data-total="${item.total_jobs}" 
                                data-status="${item.status}" 
                                title="Xem chi tiết">
                                <span class="dashicons dashicons-visibility"></span>
                             </button>`;

            if (item.status === 'processing') {
                // If Running -> Show Stop Button
                actionButtons = `
                    ${viewBtn}
                    <button class="btn-act stop cancel-bulk-history-btn" data-id="${item.bulk_id}" title="Dừng tiến trình này ngay lập tức">
                        <span class="dashicons dashicons-no"></span> 
                    </button>
                `;
            } else {
                // If Stopped/Done -> Show Trash Button
                actionButtons = `
                    ${viewBtn}
                    <button class="btn-act trash delete-log-btn" data-id="${item.bulk_id}" title="Xóa lịch sử">
                        <span class="dashicons dashicons-trash"></span>
                    </button>
                `;
            }
            
            // Format Date
            const dateStr = new Date(item.created_at).toLocaleString('vi-VN');

            // 3. Render HTML
            const htmlRow = `
                <tr id="history-row-${item.bulk_id}">
                    <td>${dateStr}</td>
                    <td>
                        <div class="file-name-cell">
                            <span class="dashicons dashicons-media-spreadsheet" style="color:#2271b1; font-size:16px;"></span>
                            ${displayName}
                        </div>
                    </td>
                    <td><span class="bulk-id-code">...${item.bulk_id.slice(-8)}</span></td>
                    <td class="text-center"><strong>${item.total_jobs}</strong></td>
                    <td>
                        <div class="status-badge ${statusClass}">
                            <span class="status-dot"></span> ${statusLabel}
                        </div>
                    </td>
                    <td class="text-right">
                        <div class="action-group">
                            ${actionButtons}
                        </div>
                    </td>
                </tr>
            `;
            $tbody.append(htmlRow);
        });
    }

    /**
     * Renders Pagination Controls.
     */
    function eonsr_aeo_agent_render_pagination(pagination) {
        const $container = $('#aeo-history-pagination');
        $container.empty();

        if (pagination.total_pages <= 1) return; 

        const current = parseInt(pagination.current_page);
        const total = parseInt(pagination.total_pages);
        const start = (current - 1) * pagination.limit + 1;
        const end = Math.min(current * pagination.limit, pagination.total_items);
        
        let html = `<span class="aeo-pagination-info">Hiển thị ${start}-${end} / ${pagination.total_items}</span>`;

        // Prev Button
        html += `<button type="button" class="aeo-page-btn" data-page="${current - 1}" ${current === 1 ? 'disabled' : ''}>«</button>`;

        // Pages
        for (let i = 1; i <= total; i++) {
            if (i === 1 || i === total || (i >= current - 2 && i <= current + 2)) {
                html += `<button type="button" class="aeo-page-btn ${i === current ? 'active' : ''}" data-page="${i}">${i}</button>`;
            } else if (i === current - 3 || i === current + 3) {
                html += `<span style="padding:0 5px; color:#aaa;">...</span>`;
            }
        }

        // Next Button
        html += `<button type="button" class="aeo-page-btn" data-page="${current + 1}" ${current === total ? 'disabled' : ''}>»</button>`;

        $container.html(html);
    }

    // ========================================================================
    // [SECTION] AUTO REFRESH LOGIC
    // ========================================================================

    $(document).on('click', '#auto-refresh-btn', function() {
        const $btn = $(this);
        const isActive = $btn.attr('data-active') === 'true';
        
        if (isActive) {
            eonsr_aeo_agent_stop_auto_refresh_ui(); 
        } else {
            eonsr_aeo_agent_start_auto_refresh_ui();
        }
    });

    function eonsr_aeo_agent_start_auto_refresh_ui() {
        const $btn = $('#auto-refresh-btn');
        // Update UI: "Running" State
        $btn.attr('data-active', 'true').addClass('active');
        $btn.find('.dashicons').removeClass('dashicons-controls-play').addClass('dashicons-update'); 
        $btn.find('.btn-text').text('Đang tự động cập nhật...');
        
        // Logic
        logger.info('Auto-refresh started');
        eonsr_aeo_agent_perform_check(); 
        if (statusCheckInterval) clearInterval(statusCheckInterval);
        statusCheckInterval = setInterval(eonsr_aeo_agent_perform_check, 10000); // Check every 10s
    }

    function eonsr_aeo_agent_stop_auto_refresh_ui() {
        const $btn = $('#auto-refresh-btn');
        // Update UI: "Stopped" State
        $btn.attr('data-active', 'false').removeClass('active');
        $btn.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-controls-play'); 
        $btn.find('.btn-text').text('Tự động cập nhật');
        
        // Logic
        logger.info('Auto-refresh stopped');
        if (statusCheckInterval) {
            clearInterval(statusCheckInterval);
            statusCheckInterval = null;
        }
    }

    function eonsr_aeo_agent_perform_check() {
        if (currentType === 'scheduled') eonsr_aeo_agent_check_scheduled_status();
        else eonsr_aeo_agent_check_immediate_status();
    }

    // ========================================================================
    // [SECTION] LEGACY: IMMEDIATE MODE
    // ========================================================================
    
    function eonsr_aeo_agent_handle_immediate_success(data) {
        const $statusDiv = $('#aeo-agent-bulk-status');
        const $detailsDiv = $('#aeo-agent-bulk-details');
        const summary = data.summary || { total: 0, successful: 0, failed: 0 };
        currentBulkStatus = 'immediate';

        let html = '<div class="notice notice-warning" style="padding: 15px;">';
        html += '<h3>⚠️ Upload thành công (Legacy Mode)</h3>';
        html += `<p><strong>Tổng:</strong> ${summary.total} | <strong>Thành công:</strong> ${summary.successful} | <strong>Thất bại:</strong> ${summary.failed}</p>`;
        html += '<p style="margin-top: 15px;"><button type="button" class="button button-primary" onclick="location.reload()">🔄 Upload lại</button></p></div>';
        
        $statusDiv.html(html);
        $detailsDiv.show();
        if (data.jobIds && data.jobIds.length > 0) eonsr_aeo_agent_check_immediate_status();
    }

    function eonsr_aeo_agent_check_immediate_status() {
        const $btn = $('#check-immediate-status-btn');
        $btn.prop('disabled', true);
        $.ajax({
            url: eonsrAeoAgentData.ajaxurl,
            type: 'POST',
            data: { action: 'eonsr_aeo_agent_check_bulk_status', nonce: eonsrAeoAgentData.bulkStatusNonce },
            success: function(response) { if (response.success) eonsr_aeo_agent_display_immediate_list(response.data); },
            complete: function() { $btn.prop('disabled', false); }
        });
    }

    function eonsr_aeo_agent_display_immediate_list(data) {
        const jobs = data.jobs || [];
        let html = '<h4>Chi tiết:</h4>';
        jobs.forEach((job, i) => {
            let icon = '⏳';
            if(job.status === 'completed') icon = '✅';
            if(job.status === 'failed') icon = '❌';
            html += `<div class="aeo-bulk-job-item ${job.status}"><strong>${i+1}. ${job.params?.primary_term || 'Job'}</strong><span style="float:right">${icon} ${job.status}</span></div>`;
        });
        $('#aeo-agent-bulk-jobs-list').html(html);
    }

    // ========================================================================
    // [SECTION] UTILS & CLEANUP
    // ========================================================================

    function eonsr_aeo_agent_handle_error(data) {
        const message = data.message || 'Lỗi không xác định';
        $('#aeo-agent-bulk-status').html(`<div class="notice notice-error" style="padding:15px"><h3>❌ Lỗi</h3><p>${message}</p><button class="button" onclick="location.reload()">Thử lại</button></div>`);
        $('#aeo-agent-bulk-details').hide();
    }

    $(window).on('beforeunload', function() {
        if (statusCheckInterval) clearInterval(statusCheckInterval);
    });

    // Action: Delete Log
    $(document).on('click', '.delete-log-btn', function() {
        const bulkId = $(this).data('id');
        
        Swal.fire({
            title: 'Xóa nhật ký này?',
            text: "Chỉ xóa khỏi bảng lịch sử.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d63638',
            confirmButtonText: 'Xóa',
            cancelButtonText: 'Hủy'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: eonsrAeoAgentData.ajaxurl,
                    type: 'POST',
                    data: { action: 'eonsr_aeo_agent_delete_bulk_log', nonce: eonsrAeoAgentData.bulkNonce, bulkUploadId: bulkId },
                    success: function() {
                        $('#history-row-' + bulkId).fadeOut(300, function(){ $(this).remove(); });
                    }
                });
            }
        });
    });

    // Action: Clear All History
    $(document).on('click', '#clear-all-history-btn', function() {
        Swal.fire({
            title: '⚠️ Xóa SẠCH lịch sử?',
            text: "Toàn bộ lịch sử upload sẽ bị xóa.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d63638',
            confirmButtonText: 'Xóa tất cả'
        }).then((result) => {
            if (result.isConfirmed) {
                const $btn = $('#clear-all-history-btn');
                $btn.prop('disabled', true);
                
                $.ajax({
                    url: eonsrAeoAgentData.ajaxurl,
                    type: 'POST',
                    data: { action: 'eonsr_aeo_agent_clear_all_history', nonce: eonsrAeoAgentData.bulkNonce },
                    success: function() {
                        Swal.fire('Đã dọn dẹp!', 'Lịch sử đã được xóa sạch.', 'success');
                        eonsr_aeo_agent_load_bulk_history(); 
                    },
                    complete: function() { $btn.prop('disabled', false); }
                });
            }
        });
    });
    
    function updateAudienceInputBulk(select) {
    var input = document.getElementById('audience_real_input_bulk');
    if (select.value === 'custom') {
        input.style.display = 'block';
        input.value = ''; input.focus();
    } else {
        input.style.display = 'none';
        input.value = select.value;
    }
}

jQuery(document).ready(function($) {
    // File Upload Handler
    $('#bulk_csv_file_input').on('change', function() {
        if (this.files.length > 0) {
            $('#aeo-bulk-submit-btn').prop('disabled', false).removeClass('disabled');
            $('#file-name-display').text(this.files[0].name).css({'color': '#2271b1', 'font-weight': 'bold'});
        } else {
            $('#aeo-bulk-submit-btn').prop('disabled', true).addClass('disabled');
            $('#file-name-display').text('Chưa chọn file').css({'color': '#666', 'font-weight': 'normal'});
        }
    });

    // Translation Logic
    $('#aeo_bulk_auto_translate').change(function() {
        if (this.checked) {
            $('#aeo_bulk_translation_options').slideDown(200);
            syncBulkLanguage();
        } else {
            $('#aeo_bulk_translation_options').slideUp(200);
            $('#aeo_bulk_lang_list input').prop('checked', false);
        }
    });

    function syncBulkLanguage() {
        var sourceLang = $('#bulk_source_language').val();
        $('#aeo_bulk_lang_list input[type="checkbox"]').each(function() {
            var $cb = $(this);
            var $label = $cb.closest('label');
            if ($cb.val() === sourceLang) {
                $cb.prop('checked', false).prop('disabled', true);
                $label.css({opacity: 0.5, cursor: 'not-allowed'}).attr('title', 'Đây là ngôn ngữ gốc');
            } else {
                $cb.prop('disabled', false);
                $label.css({opacity: 1, cursor: 'pointer'}).removeAttr('title');
            }
        });
    }

    $('#bulk_source_language').change(syncBulkLanguage);

    // Custom Logo Logic (only if allowed)
    var bulkData = (typeof eonsrAeoBulkData !== 'undefined') ? eonsrAeoBulkData : {};
    var allowLogo = bulkData.allowLogo === '1';
    var setupNonce = bulkData.setupNonce || '';

    if (allowLogo) {
        $('#use_custom_logo').on('change', function() {
            if ($(this).is(':checked')) {
                $('#aeo-logo-upload-area').slideDown(200);
            } else {
                $('#aeo-logo-upload-area').slideUp(200);
            }
        });

        $('#btn-upload-logo').on('click', function(e) { e.preventDefault(); $('#aeo-logo-file').click(); });

        $('#aeo-logo-file').on('change', function() {
            var file_data = $(this).prop('files')[0];
            if (!file_data) return;
            if (file_data.type !== 'image/png') {
                Swal.fire({ icon: 'error', title: 'Định dạng sai', text: 'Vui lòng chỉ upload file PNG.', confirmButtonColor: '#2271b1' });
                $(this).val(''); return;
            }
            var form_data = new FormData();
            form_data.append('custom_logo', file_data);
            form_data.append('action', 'eonsr_aeo_agent_upload_logo');
            form_data.append('nonce', setupNonce);
            $('#aeo-logo-preview').html('<span class="dashicons dashicons-update" style="animation:spin 1s infinite linear; color:#2271b1"></span>');

            $.ajax({
                url: ajaxurl, type: 'POST', data: form_data, contentType: false, processData: false,
                success: function(response) {
                    if (response.success) {
                        $('#aeo-logo-preview').html('<img src="' + response.data.url + '" style="max-width:100%; max-height:100%;">');
                        $('#btn-remove-logo').show();
                        const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, timerProgressBar: true });
                        Toast.fire({ icon: 'success', title: 'Đã tải logo lên' });
                    } else {
                        Swal.fire({ icon: 'error', title: 'Lỗi', text: response.data.message });
                        $('#aeo-logo-preview').html('<span class="dashicons dashicons-warning" style="color:red"></span>');
                    }
                }
            });
        });

        $('#btn-remove-logo').on('click', function() {
            Swal.fire({
                title: 'Xóa Logo tùy chỉnh?',
                html: '<div style="text-align:left;font-size:14px;line-height:1.5;color:#555"><p style="margin-top:0">Bạn chắc chắn muốn xóa logo hiện tại?</p><ul style="list-style:none;padding:0;margin:0"><li style="margin-bottom:6px;color:#d63638;display:flex;align-items:center;gap:8px"><span>❌</span><span>Ảnh Logo tùy chỉnh sẽ bị gỡ bỏ.</span></li><li style="color:#00a32a;display:flex;align-items:center;gap:8px"><span>♻️</span><span>Hệ thống sẽ quay về sử dụng Logo mặc định.</span></li></ul></div>',
                icon: 'warning', iconColor: '#f59e0b', showCancelButton: true,
                confirmButtonColor: '#d63638', cancelButtonColor: '#6b7280',
                confirmButtonText: 'Đồng ý, xóa ngay', cancelButtonText: 'Huỷ bỏ',
                reverseButtons: true, focusCancel: true
            }).then(function(result) {
                if (result.isConfirmed) {
                    Swal.fire({ title: 'Đang xử lý...', allowOutsideClick: false, showConfirmButton: false, didOpen: function() { Swal.showLoading(); } });
                    $.post(ajaxurl, { action: 'eonsr_aeo_agent_remove_logo', nonce: setupNonce }, function(res) {
                        if (res.success) {
                            $('#aeo-logo-preview').html('<span class="dashicons dashicons-format-image" style="color:#ccc"></span>');
                            $('#btn-remove-logo').hide(); $('#aeo-logo-file').val('');
                            Swal.fire({ icon: 'success', title: 'Đã xóa!', text: 'Logo đã quay về mặc định.', confirmButtonColor: '#2271b1', timer: 1500 });
                        }
                    });
                }
            });
        });
    }
});

});