jQuery(function($) {
    const { __ } = (window.wp && window.wp.i18n) ? window.wp.i18n : { __: (s) => s };
    'use strict';
    
    // Función para formatear precios según la configuración de WooCommerce
    function formatPrice(amount) {
        if (typeof window.ckfylt25Currency === 'undefined') {
            return '$' + amount.toFixed(2); // Fallback
        }
        
        const currency = window.ckfylt25Currency;
        let formattedAmount = amount.toFixed(currency.decimals);
        
        // Agregar separadores de miles
        if (currency.thousand_separator) {
            formattedAmount = formattedAmount.replace(/\B(?=(\d{3})+(?!\d))/g, currency.thousand_separator);
        }
        
        // Reemplazar separador decimal
        if (currency.decimal_separator !== '.') {
            formattedAmount = formattedAmount.replace('.', currency.decimal_separator);
        }
        
        // Decodificar símbolo de moneda si está codificado como entidad HTML
        let symbol = currency.symbol;
        if (symbol.includes('&#036;')) {
            symbol = symbol.replace(/&#036;/g, '$');
        }
        
        // Posicionar símbolo de moneda
        switch (currency.position) {
            case 'left':
                return symbol + formattedAmount;
            case 'right':
                return formattedAmount + symbol;
            case 'left_space':
                return symbol + ' ' + formattedAmount;
            case 'right_space':
                return formattedAmount + ' ' + symbol;
            default:
                return symbol + formattedAmount;
        }
    }
    
    function calculate_totals() {
        let subtotal = 0;
        let shipping = 0;
        let shippingText = __('Select shipping method', 'checkoutify-lite');
        
        // Sumar productos
        $('#order_products_list .ckfylt25-order-product').each(function() {
            const price = parseFloat($(this).data('price'));
            const qty = parseInt($(this).data('qty'));
            subtotal += price * qty;
        });
        
        // Obtener método de envío seleccionado
        const $selectedShipping = $('#shipping_methods_list input[type="radio"]:checked');
        if ($selectedShipping.length) {
            const $label = $selectedShipping.closest('li').find('label .shipping-price');
            if ($label.length) {
                // Extraer número del precio (ej: Q12.00)
                const priceText = $label.text().replace(/[^\d.,]/g, '').replace(',', '.');
                shipping = parseFloat(priceText) || 0;
                shippingText = shipping > 0 ? formatPrice(shipping) : __('Free', 'checkoutify-lite');
            } else {
                shippingText = __('Free', 'checkoutify-lite');
            }
        }
        
        // Actualizar DOM
        $('#subtotal_amount').text(formatPrice(subtotal));
        $('#shipping_amount').text(shippingText);
        $('#total_amount').text(shippingText === __('Select shipping method', 'checkoutify-lite') ? __('Select shipping method', 'checkoutify-lite') : formatPrice(subtotal + shipping));
    }
    
    // Al cambiar método de envío
    $(document).on('change', '#shipping_methods_list input[type="radio"]', function() {
        calculate_totals();
    });
    
    // Inicializar al cargar
    $(document).ready(function() {
        calculate_totals();
        
        // Si hay solo un método de envío, ya está seleccionado, así que calcular
        const totalMethods = $('#shipping_methods_list input[type="radio"]').length;
        const selectedMethods = $('#shipping_methods_list input[type="radio"]:checked').length;
        
        console.log('Total shipping methods:', totalMethods, 'Selected methods:', selectedMethods);
        
        if (totalMethods === 1 && selectedMethods === 1) {
            console.log('Auto-selected single shipping method');
            calculate_totals();
        } else if (totalMethods > 1 && selectedMethods === 0) {
            console.log('Multiple methods available, none selected');
        }
    });
});
