(function($) {
    'use strict';
    
    let currentPaymentMethod = '';

    function initializePaymentMethods() {
        // Deseleccionar todos los métodos de pago al inicio
        $('input[name="payment_method"]').prop('checked', false);
        $('.payment_box').hide();
        
        console.log('💰 Métodos de pago inicializados - ninguno seleccionado');
    }

    function switchCurrencyByPaymentMethod() {
        const selectedMethod = $('input[name="payment_method"]:checked').val();
        
        if (!selectedMethod) {
            console.log('No hay método de pago seleccionado');
            return;
        }
        
        if (selectedMethod === currentPaymentMethod) {
            return;
        }
        
        currentPaymentMethod = selectedMethod;
        
        console.log('🔄 Solicitando cambio de moneda para:', selectedMethod);
        
        $.ajax({
            type: 'POST',
            url: currency_woocs_data.ajax_url,
            data: {
                action: 'switch_currency_by_payment_woocs',
                payment_method: selectedMethod,
                nonce: currency_woocs_data.nonce
            },
            success: function(response) {
                if (response.success) {
                    console.log('✅ Cambio exitoso:', response.data);
                    
                    // Forzar actualización completa del checkout
                    setTimeout(function() {
                        $('body').trigger('update_checkout');
                    }, 300);
                } else {
                    console.log('❌ Error en respuesta:', response);
                }
            },
            error: function(xhr, status, error) {
                console.log('❌ Error AJAX:', error);
            }
        });
    }

    // Inicializar cuando el documento esté listo
    $(document).ready(function() {
        console.log('💰 Currency by Payment Method WOOCS inicializado');
        
        // Inicializar métodos de pago (ninguno seleccionado)
        setTimeout(initializePaymentMethods, 1000);
        
        // Detectar cambio en método de pago
        $(document).on('click', 'input[name="payment_method"]', function() {
            console.log('📝 Método de pago clickeado:', $(this).val());
            setTimeout(switchCurrencyByPaymentMethod, 100);
        });

        // También detectar cambios por otros medios
        $(document).on('change', 'input[name="payment_method"]', function() {
            setTimeout(switchCurrencyByPaymentMethod, 100);
        });
    });
    
    // Manejar actualizaciones del checkout
    $(document.body).on('updated_checkout', function() {
        console.log('🔄 Checkout actualizado');
        
        const currentMethod = $('input[name="payment_method"]:checked').val();
        if (currentMethod && currentMethod !== currentPaymentMethod) {
            currentPaymentMethod = currentMethod;
        }
    });

    // Debug helper
    window.currencyDebugWOOCS = function() {
        console.log('=== 🔧 DEBUG WOOCS CURRENCY PLUGIN ===');
        console.log('Método actual:', currentPaymentMethod);
        console.log('Métodos VES:', currency_woocs_data.ves_methods);
        console.log('Es método VES:', currency_woocs_data.ves_methods.includes(currentPaymentMethod));
        console.log('==============================');
    };

})(jQuery);