jQuery(document).ready(function($) {
    
/**
 * Smart Convert – Currency & Unit Conversion - AJAX Update Handler
 *
 * Localization & Configuration
 * * Retrieval of localized strings passed from PHP via `wp_localize_script`.
 * A fallback object is defined to ensure the UI remains functional even if
 * the localization object (`window.SmartConvertCurrencyUnitConversionAjax`) fails to load or is undefined.
 *
 * @package           smart-convert-currency-unit-conversion
 * @author            Petr Novák
 * @copyright         2025 Petr Novák
 * @license           GPL-2.0-or-later
 * @licenseURI        https://www.gnu.org/licenses/gpl-2.0.html
 */
     
    const strings = window.SmartConvertCurrencyUnitConversionAjax ? window.SmartConvertCurrencyUnitConversionAjax : {
        preparing: "Preparing...",
        downloading: "Downloading data...",
        processing: "Processing database...",
        success: "Update Complete!",
        error: "Update Failed",
        title: "Updating Data",
        initializing: "Initializing connection...",
        server_error: "Server error:",
        success_rows: "Successfully updated <strong>%d</strong> items."
    };

    /**
     * Currency Symbol Dataset
     * * A comprehensive list of currency symbols used for the particle animation
     * during the update process to provide visual context.
     */
    const allSymbols = [
        '$','£','€','¥','¢','₹','₽','₺','₩','₦','₪','₫','₴','₲','₱','₡','฿','₼','₾','₮',
        '₠','₢','₣','₤','₥','₧','₨','₭','₯','₰','₳','₵','₶','₷','₸','₻','₿','ƒ','៛','֏','؋','﷼'
    ];

    // State management for the particle animation system
    let animationInterval = null;
    let symbolIndex = 0;

    /**
     * Core Update Execution Function
     * * Orchestrates the entire update process: UI overlay generation, animation control,
     * progress bar simulation, and the actual AJAX request to the server.
     * * @param {string} action - The WordPress AJAX action hook to trigger.
     * @param {string} nonce  - Security nonce for request verification.
     */
    function runSmartConvertCurrencyUnitConversionUpdate(action, nonce) {
        // Inject the modal overlay into the DOM
        $('body').append(getOverlayHtml());
        const $overlay = $('#smart-convert-currency-unit-conversion-update-overlay');
        const $bar = $overlay.find('.smart-convert-currency-unit-conversion-progress-fill');
        const $text = $overlay.find('.smart-convert-currency-unit-conversion-progress-text');
        
        // Initialize the visual currency particle system
        startCurrencyFlow();

        /**
         * Progress Bar Simulation
         * * Since the server-side process is synchronous and doesn't stream progress,
         * we simulate a progress bar to provide immediate visual feedback and 
         * prevent the user from thinking the browser has frozen.
         */
        let progress = 0;
        const progressTimer = setInterval(() => {
            // Cap the simulation at 90% until the actual success response is received
            if (progress < 90) {
                // Non-linear progression: starts fast to satisfy immediate click, 
                // then slows down to manage expectations for longer running tasks.
                const increment = (progress > 60) ? 0.2 : (progress > 30 ? 0.5 : 1.5);
                progress += increment;
                
                $bar.css('width', progress + '%');
                
                // Update status text based on simulated progress stages
                if (progress < 30) $text.text(strings.preparing);
                else if (progress < 60) $text.text(strings.downloading);
                else $text.text(strings.processing);
            }
        }, 100);

        // Execute the asynchronous request to the WordPress backend
        $.ajax({
            url: ajaxurl, // 'ajaxurl' is globally defined by WordPress in the admin area
            type: 'POST',
            data: {
                action: action,
                _wpnonce: nonce
            },
            success: function(response) {
                clearInterval(progressTimer);
                
                if (response.success) {
                    // Complete the progress bar visual
                    $bar.css('width', '100%');
                    $text.text(strings.success);
                    $overlay.find('.smart-convert-currency-unit-conversion-progress-bar').addClass('success');
                    
                    // visual feedback: Convert spinner to a pulsing checkmark
                    $overlay.find('.smart-convert-currency-unit-conversion-spinner-icon').text('✅').removeClass('spin').addClass('pulse');
                    
                    // Gracefully stop the animation (allow existing particles to float off)
                    stopCurrencyFlow();

                    // Display result details (e.g., affected row count)
                    const rowCount = response.data.rows || 0;
                    const detailText = strings.success_rows.replace('%d', rowCount);
                    $overlay.find('.smart-convert-currency-unit-conversion-update-details').html(detailText);
                    
                    // Reload the page after a short delay to reflect changes
                    setTimeout(() => {
                        $overlay.fadeOut(500, function() { 
                            location.reload(); 
                        });
                    }, 2000);
                } else {
                    // Handle logical errors returned by the endpoint (success: false)
                    handleError($overlay, $bar, $text, response.data.message);
                    stopCurrencyFlow(true); // Immediate cleanup on error
                }
            },
            error: function(xhr, status, error) {
                // Handle HTTP or Network errors
                clearInterval(progressTimer);
                handleError($overlay, $bar, $text, strings.server_error + " " + error);
                stopCurrencyFlow(true);
            }
        });
    }

    /**
     * Error State Handler
     * * Updates the UI to reflect a failed state, changing colors to red, 
     * displaying the error message, and enabling manual dismissal.
     * * @param {jQuery} $overlay - The modal container.
     * @param {jQuery} $bar     - The progress bar element.
     * @param {jQuery} $text    - The status text element.
     * @param {string} msg      - The specific error message to display.
     */
    function handleError($overlay, $bar, $text, msg) {
        $bar.css('width', '100%').css('background', '#d63638'); // WordPress standard error red
        $text.text(strings.error);
        $overlay.find('.smart-convert-currency-unit-conversion-spinner-icon').text('❌').removeClass('spin');
        $overlay.find('.smart-convert-currency-unit-conversion-update-details').html(`<span style="color:#ff8080">${msg}</span>`);
        
        // Allow user to click anywhere to dismiss the error overlay
        $overlay.on('click', function() { $(this).remove(); });
        
        // Auto-dismiss after 4 seconds if no interaction occurs
        setTimeout(() => { $overlay.fadeOut(function(){ $(this).remove(); }); }, 4000);
    }

    /**
     * Overlay Template Generator
     * * dynamically constructs the HTML structure for the modal overlay.
     * Uses template literals to inject localized strings immediately.
     * * Structure:
     * - Particles container (background animation)
     * - Modal Card (centered content)
     * - Spinner/Icon
     * - Progress Bar
     * - Status Text/Details
     * * @returns {string} HTML string of the overlay.
     */
    function getOverlayHtml() {
        return `
        <div id="smart-convert-currency-unit-conversion-update-overlay">
            <div id="smart-convert-currency-unit-conversion-particles-container"></div>
            <div class="smart-convert-currency-unit-conversion-modal-card">
                <div class="smart-convert-currency-unit-conversion-spinner-icon spin">↻</div>
                <h3>${strings.title}</h3>
                <div class="smart-convert-currency-unit-conversion-progress-container">
                    <div class="smart-convert-currency-unit-conversion-progress-fill"></div>
                </div>
                <div class="smart-convert-currency-unit-conversion-progress-text">${strings.initializing}</div>
                <div class="smart-convert-currency-unit-conversion-update-details"></div>
            </div>
        </div>
        `;
    }

    // --- ANIMATION LOGIC (Currency Flow) ---

    /**
     * Animation Initializer
     * * Prepares the particle system by shuffling symbols and starting the 
     * interval that spawns new particles.
     */
    function startCurrencyFlow() {
        const $container = $('#smart-convert-currency-unit-conversion-particles-container');
        shuffleArray(allSymbols);
        symbolIndex = 0;

        // Spawn a new particle every 80ms for a dense flow effect
        animationInterval = setInterval(() => {
            spawnParticle($container);
        }, 80);
    }

    /**
     * Animation Terminator
     * * Stops the generation of new particles.
     * * @param {boolean} clearInstantly - If true, removes all particles immediately 
     * (used for errors). If false, allows current 
     * particles to finish their CSS animation.
     */
    function stopCurrencyFlow(clearInstantly = false) {
        if (animationInterval) {
            clearInterval(animationInterval);
            animationInterval = null;
        }
        if (clearInstantly) {
            $('#smart-convert-currency-unit-conversion-particles-container').empty();
        }
    }

    /**
     * Particle Generator
     * * Creates a single currency symbol DOM element with randomized CSS properties
     * (position, size, speed, opacity, color) and appends it to the container.
     * * @param {jQuery} $container - The container element for particles.
     */
    function spawnParticle($container) {
        const sym = allSymbols[symbolIndex];
        // Cycle through the symbols array continuously
        symbolIndex = (symbolIndex + 1) % allSymbols.length;

        const $el = $(`<div class="smart-convert-currency-unit-conversion-currency-particle">${sym}</div>`);
        
        // Randomize physics and appearance
        const topPos = Math.random() * 100; // Vertical position (0-100vh)
        const size = 15 + Math.random() * 40; // Font size (15px - 55px)
        const duration = 3000 + Math.random() * 4000; // Animation speed (3s - 7s)
        const opacity = 0.1 + Math.random() * 0.4; // Transparency
        const color = getRandomColor();
        
        $el.css({
            top: topPos + 'vh',
            left: '-50px', // Start off-screen to the left
            fontSize: size + 'px',
            color: color,
            opacity: 0,
            animationDuration: duration + 'ms'
        });

        $container.append($el);

        // Garbage Collection: Remove the element from DOM after animation completes
        setTimeout(() => {
            $el.remove();
        }, duration + 100); 
    }

    /**
     * Color Picker helper
     * * Returns a random color from a curated palette that matches the
     * plugin's light theme and branding.
     */
    function getRandomColor() {
        const colors = [
            '#82C7C4', // Brand Teal (Accent)
            '#FF6B81', // Brand Coral (Primary)
            '#1A2F45', // Brand Dark Blue (Text Main)
            '#50667d', // Muted Blue (Text Light)
            '#A9DFBF', // Soft Green (Success-like)
            '#D7BDE2'  // Soft Purple (Complementary)
        ];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    /**
     * Utility: Fisher-Yates Shuffle
     * * Randomizes the order of the currency symbols array to prevent 
     * repetitive patterns in the animation.
     */
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    // --- EVENT BINDINGS ---
    
    // Bind click event for Rates Update
    $('#smart-convert-currency-unit-conversion-btn-update-rates').on('click', function(e) {
        e.preventDefault();
        // Extracts the specific nonce for this action from the data attribute
        runSmartConvertCurrencyUnitConversionUpdate('smart_convert_currency_unit_conversion_ajax_update_rates', $(this).data('nonce'));
    });

    // Bind click event for Units Update
    // Includes a confirmation dialog due to the potential impact of this action
    $('#smart-convert-currency-unit-conversion-btn-update-units').on('click', function(e) {
        e.preventDefault();
        if(confirm($(this).data('confirm'))) {
            runSmartConvertCurrencyUnitConversionUpdate('smart_convert_currency_unit_conversion_ajax_update_units', $(this).data('nonce'));
        }
    });

});