/**
 * Oney Widget Loader
 * 
 * Dynamically loads the Oney widget based on environment configuration.
 * This script is loaded in the head and waits for the configuration to be available.
 * 
 * @version 1.0.0
 * @author Oney
 * @since 1.0.0
 */
(function() {
    'use strict';
    
    var widgetConfig = null;
    var scriptLoaded = false;
    var callbacks = [];
    var isProduction = false;
    
    /**
     * Wait for widget configuration
     * 
     * @version 1.0.0
     */
    function waitForConfig() {
        var configElement = document.getElementById('oney-threebyfour-widget-config');
        if (configElement) {
            widgetConfig = {
                url: configElement.getAttribute('data-widget-url'),
                loaded: false
            };
            
            // Determine if production environment based on URL
            isProduction = widgetConfig.url.indexOf('assets.oney.io') !== -1;
            
            if (!isProduction) {
                console.log('[INFO] [JS] Oney widget config loaded:', widgetConfig.url);
            }
            
            loadWidgetScript();
        } else {
            setTimeout(waitForConfig, 50);
        }
    }
    
    /**
     * Load widget script dynamically
     * 
     * @version 1.0.0
     */
    function loadWidgetScript() {
        if (scriptLoaded || !widgetConfig) return;
        
        var script = document.createElement('script');
        script.src = widgetConfig.url;
        script.type = 'text/javascript';
        script.async = true;
        
        script.onload = function() {
            scriptLoaded = true;
            widgetConfig.loaded = true;
            
            if (!isProduction) {
                console.log('[INFO] [JS] Oney widget script loaded successfully');
            }
            
            // Hide loader if it exists
            hideLoader();
            
            // Execute all pending callbacks
            callbacks.forEach(function(callback) {
                if (typeof callback === 'function') {
                    callback();
                }
            });
            callbacks = [];
        };
        
        script.onerror = function() {
            console.error('[ERROR] [JS] Failed to load Oney widget from: ', widgetConfig.url);
            hideLoader();
        };
        
        document.head.appendChild(script);
    }
    
    /**
     * Show loader
     * 
     * @version 1.0.0
     */
    function showLoader() {
        var loader = document.getElementById('oney-threebyfour-widget-loader');
        if (loader) {
            loader.style.display = 'block';
        }
        
        // Show checkout container loader
        showCheckoutLoader();
    }
    
    /**
     * Hide loader
     * 
     * @version 1.0.0
     */
    function hideLoader() {
        var loader = document.getElementById('oney-threebyfour-widget-loader');
        if (loader) {
            loader.style.display = 'none';
        }
        
        // Hide checkout container loader
        hideCheckoutLoader();
    }
    
    /**
     * Show checkout container loader
     * 
     * @version 1.0.0
     */
    function showCheckoutLoader() {
        var containers = document.querySelectorAll('.oney-threebyfour-checkout-container');
        containers.forEach(function(container) {
            // Find the widget container (the one with getSimulationContainerId)
            var widgetContainer = container.querySelector('[data-bind*="getSimulationContainerId"]');
            if (widgetContainer) {
                var existingLoader = widgetContainer.querySelector('.oney-widget-loading');
                if (!existingLoader) {
                    var loader = document.createElement('div');
                    loader.className = 'oney-widget-loading';
                    
                    // Get translated text using Magento's i18n system
                    var loaderText = 'Chargement du widget Oney...'; // Default French text
                    if (typeof window.translate === 'function') {
                        loaderText = window.translate('Loading Oney widget...');
                    } else if (typeof $t === 'function') {
                        loaderText = $t('Loading Oney widget...');
                    }
                    
                    loader.innerHTML = '<div class="oney-loader-content"><div class="oney-loader-spinner"></div><div class="oney-loader-text">' + 
                        loaderText + 
                        '</div></div>';
                        widgetContainer.appendChild(loader);
                }
            }
        });
    }
    
    /**
     * Hide checkout container loader
     * 
     * @version 1.0.0
     */
    function hideCheckoutLoader() {
        var loaders = document.querySelectorAll('.oney-widget-loading');
        loaders.forEach(function(loader) {
            loader.remove();
        });
    }
    
    /**
     * Load Oney Widget
     * 
     * Global function to load Oney widget with callback.
     * This function is called from various templates to initialize the Oney widget.
     * 
     * @param {Function} callback Callback function to execute after widget loads
     * @version 1.0.0
     */
    window.loadOneyWidget = function(callback) {
        // Always show loader when function is called
        showLoader();
        
        if (typeof oneyMerchantApp !== 'undefined') {
            // Widget already loaded
            setTimeout(function() {
                hideLoader();
                if (callback) callback();
            }, 500); // Small delay to show loader briefly
        } else if (widgetConfig && widgetConfig.loaded) {
            // Widget script loaded but not yet initialized
            var checkWidget = setInterval(function() {
                if (typeof oneyMerchantApp !== 'undefined') {
                    clearInterval(checkWidget);
                    hideLoader();
                    if (callback) callback();
                }
            }, 100);
            
            // Timeout after 10 seconds
            setTimeout(function() {
                clearInterval(checkWidget);
                hideLoader();
                console.error('[ERROR] [JS] Oney widget failed to initialize within timeout period');
            }, 10000);
        } else {
            // Add callback to queue
            if (callback) callbacks.push(callback);
        }
    };
    
    /**
     * Show Oney loader (global function)
     * 
     * @version 1.0.0
     */
    window.showOneyLoader = function() {
        showCheckoutLoader();
    };
    
    /**
     * Hide Oney loader (global function)
     * 
     * @version 1.0.0
     */
    window.hideOneyLoader = function() {
        hideCheckoutLoader();
    };
    
    // Start loading process
    waitForConfig();
})();
