/**
 * Progress Bar Animation Controller
 * Controls the wave effect animation on progress bars based on user interactions
 */

(function($) {
    "use strict";

    // Initialize when document is ready
    $(document).ready(function() {
    // Define global objects to track animation state
    window.progressAnimations = {};
    
    // Function to initialize animation control
    function initProgressBarAnimations() {
        // Only animate progress bars that have scan_status='processing'
        // This is controlled by PHP adding the 'animated' class
        $('.progress-bar').each(function() {
            const $bar = $(this);
            // Check if we already have the 'animated' class from PHP
            // If not, make sure the bar doesn't have animation
            if (!$bar.hasClass('animated')) {
                $bar.addClass('no-animation');
            }
        });
        
        // Setup click handlers for verify buttons
        $('.btn-verify').off('click.animation').on('click.animation', function() {
            const csvNameEx = $(this).attr('id').replace('verify_', '');
            const progressBar = $('#progress-bar_' + csvNameEx);
            
            // Enable animation
            progressBar.addClass('animated').removeClass('no-animation');
            window.progressAnimations[csvNameEx] = true;
            
            console.log('Animation enabled for: ' + csvNameEx);
        });
        
        // Setup click handlers for cancel buttons
        $('.task-cancel-btn').off('click.animation').on('click.animation', function() {
            const csvFileNameWithExt = $(this).attr('data-target');
            const csvNameEx = csvFileNameWithExt.replace(/\.[^/.]+$/, '');
            const progressBar = $('#progress-bar_' + csvNameEx);
            
            // Disable animation
            progressBar.removeClass('animated').addClass('no-animation');
            window.progressAnimations[csvNameEx] = false;
            
            console.log('Animation disabled for: ' + csvNameEx);
        });
    }
    
    // Function to update progress bar animation state based on status from server
    function updateProgressBarAnimation(csvNameEx, percent, status) {
        const progressBar = $('#progress-bar_' + csvNameEx);
        if (!progressBar.length) return;
        
        // Only apply animation if the status is 'processing'
        if (status === 'processing' && percent < 100) {
            progressBar.addClass('animated').removeClass('no-animation');
            window.progressAnimations[csvNameEx] = true;
        } else {
            progressBar.removeClass('animated').addClass('no-animation');
            window.progressAnimations[csvNameEx] = false;
        }
    }
    
    // Initialize animations
    initProgressBarAnimations();
    
    // Check for AJAX updates and handle animation accordingly
    $(document).ajaxSuccess(function(event, xhr, settings) {
        if (settings.url && settings.url.includes('verify_per_count.php')) {
            try {
                const response = xhr.responseText;
                if (!response) return;
                
                const data = JSON.parse(response);
                if (data && 'percent' in data) {
                    // Extract CSV name from the URL parameters or data
                    let csvNameEx = '';
                    if (settings.data) {
                        const params = new URLSearchParams(settings.data);
                        const filename = params.get('filename');
                        if (filename) {
                            csvNameEx = filename.replace(/\.[^/.]+$/, '');
                        }
                    }
                    
                    if (csvNameEx) {
                        updateProgressBarAnimation(csvNameEx, data.percent, data.status);
                    }
                }
            } catch (e) {
                console.error('Error processing AJAX response:', e);
            }
        }
    });
    
    // Update animations when DOM changes (for dynamically added progress bars)
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList' && mutation.addedNodes.length) {
                setTimeout(initProgressBarAnimations, 200);
            }
        });
    });
    
    observer.observe(document.body, { childList: true, subtree: true });
    
    // Don't automatically re-enable animations - let the server status control this
    // The animation state should entirely depend on the 'scan_status' from the server
    });

})(jQuery);
