jQuery(document).ready(function($) {
    // Wait for API data to be available
    function waitForApiData() {
        if (typeof pmrcgold_api_data !== 'undefined' && pmrcgold_api_data.rates) {
            initializeWidget();
        } else {
            // If API data not ready, wait a bit and try again
            setTimeout(waitForApiData, 100);
        }
    }

    function initializeWidget() { 
        // Main currency dropdown handler for shortcodes
        $(document).on('change', '.pmrcgold-currency-dropdown', function() {
            var $widget = $(this).closest('.pmrcgold-shortcode-widget-1');
            updateMetalPricesInWidget($widget, $(this).val());
        });

        // Initialize prices on page load for each widget individually
        $('.pmrcgold-currency-dropdown').each(function() {
            var $widget = $(this).closest('.pmrcgold-shortcode-widget-1');
            updateMetalPricesInWidget($widget, $(this).val());
        });

        // Update metal prices within a specific widget only
        function updateMetalPricesInWidget($widget, currency) {
 
            $widget.find('.pmrcgold-metal-badge').each(function() {
                var $badge = $(this);
                var metal = $badge.data('metal');
                var $priceSpan = $badge.find('.metal-price');
                var $changeSpan = $badge.find('.metal-change');

                // Get metal price from API data
                var metalKey = metal.toUpperCase();
                var priceInBase = null;
                
                // Map metal names to API codes
                var metalCodes = {
                    'GOLD': 'XAU',
                    'SILVER': 'XAG', 
                    'PLATINUM': 'XPT',
                    'PALLADIUM': 'XPD'
                };
                
                var apiMetalCode = metalCodes[metalKey] || metalKey;
                
                // The API has USD-based metal prices like "USDXAU": 4697.8859982796
                // This means 1 XAU = 4697.8859982796 USD (which is what we want)
                var usdBasedKey = 'USD' + apiMetalCode;
                if (pmrcgold_api_data.rates && pmrcgold_api_data.rates[usdBasedKey]) {
                    // USDXAU already gives us the price of 1 XAU in USD
                    priceInBase = pmrcgold_api_data.rates[usdBasedKey];
                }
                // Fallback: Direct metal price like "XAU": 129.95
                else if (pmrcgold_api_data.rates && pmrcgold_api_data.rates[apiMetalCode]) {
                    var directRate = pmrcgold_api_data.rates[apiMetalCode];
                    priceInBase = directRate; // Use direct price for 1 metal unit
                }
                // Alternative structure: { "XAU": 1850.50, "XAG": 22.75, ... }
                else if (pmrcgold_api_data[apiMetalCode]) {
                    priceInBase = pmrcgold_api_data[apiMetalCode];
                } else {
                    
                }

                if (priceInBase) {
                    // Convert to selected currency if needed
                    var priceInSelected = priceInBase;
                    
                    if (currency !== pmrcgold_api_data.base && pmrcgold_api_data.rates[currency]) {
                        // For currency conversion: if base is USD and we want INR
                        // and metal price is in USD, we need to multiply by INR rate
                        var currencyRate = pmrcgold_api_data.rates[currency];
                        
                        if (currency === 'INR') {
                            // For INR: 1 USD = 93.472 INR, so metal price in USD * 93.472 = price in INR
                            priceInSelected = priceInBase * currencyRate;
                        } else {
                            // For other currencies, similar logic
                            priceInSelected = priceInBase * currencyRate;
                        }
                    }

                    // Format price with 2 decimal places
                    var formattedPrice = formatPrice(priceInSelected, currency);
        
                    $priceSpan.text(formattedPrice);

                    // Calculate price change (placeholder - would need historical data)
                    var change = calculatePriceChange(metal, currency, priceInSelected);
                    
                    if (change !== null && change !== undefined) {
                        var changeClass = change >= 0 ? 'price-up' : 'price-down';
                        var changeSymbol = change >= 0 ? '↑' : '↓';
                        var formattedChange = Math.abs(change).toFixed(2);
                        
                        // Apply color styling
                        if (change >= 0) {
                            $changeSpan.css('color', '#28a745'); // Green for up
                        } else {
                            $changeSpan.css('color', '#dc3545'); // Red for down
                        }
                        
                        $changeSpan.removeClass('price-up price-down').addClass(changeClass)
                            .text(changeSymbol + ' ' + formattedChange + '%');
                    } else {
                        $changeSpan.text('--').css('color', ''); // Reset color
                    }
                } else {
                    $priceSpan.text('N/A');
                    $changeSpan.text('--');
                }
            });
        }

        // Format price with currency symbol
        function formatPrice(price, currency) {
            var symbols = {
                'USD': '$',
                'EUR': '€',
                'GBP': '£',
                'JPY': '¥',
                'INR': '₹',
                'AUD': 'A$',
                'CAD': 'C$',
                'CHF': 'Fr',
                'CNY': '¥'
            };
            var symbol = symbols[currency] || currency + ' ';
            return symbol + price.toFixed(2);
        }

        // Calculate price change using real historical data
        function calculatePriceChange(metal, currency, currentPrice) {
            // Use real yesterday's data if available
            if (pmrcgold_yesterday_data && pmrcgold_yesterday_data.rates) {
                var metalKey = metal.toUpperCase();
                var metalCodes = {
                    'GOLD': 'XAU',
                    'SILVER': 'XAG', 
                    'PLATINUM': 'XPT',
                    'PALLADIUM': 'XPD'
                };
                var apiMetalCode = metalCodes[metalKey] || metalKey;
                var usdBasedKey = 'USD' + apiMetalCode;
                
                var yesterdayPrice = null;
                
                // Get yesterday's price (same logic as current price)
                if (pmrcgold_yesterday_data.rates[usdBasedKey]) {
                    yesterdayPrice = pmrcgold_yesterday_data.rates[usdBasedKey];
                } else if (pmrcgold_yesterday_data.rates[apiMetalCode]) {
                    var directRate = pmrcgold_yesterday_data.rates[apiMetalCode];
                    yesterdayPrice = directRate;
                }
                
                if (yesterdayPrice && yesterdayPrice > 0) {
                    // Calculate real percentage change
                    var changePercent = ((currentPrice - yesterdayPrice) / yesterdayPrice) * 100;
                    return changePercent;
                }
            }
            
            // Fallback: if no yesterday data, show a small positive change
            return 0; // Show +0% as default (more visible than 0%)
        }

        // Initialize prices on page load
        $('.pmrcgold-currency-dropdown').trigger('change');
    }

    function updateMetalPrices(currency) {
        
        $('.pmrcgold-metal-badge').each(function() {
            var $badge = $(this);
            var metal = $badge.data('metal');
            var $priceSpan = $badge.find('.metal-price');
            var $changeSpan = $badge.find('.metal-change');

            // Get metal price from API data
            var metalKey = metal.toUpperCase();
            var priceInBase = null;
            
            // Map metal names to API codes
            var metalCodes = {
                'GOLD': 'XAU',
                'SILVER': 'XAG', 
                'PLATINUM': 'XPT',
                'PALLADIUM': 'XPD'
            };
            
            var apiMetalCode = metalCodes[metalKey] || metalKey;
            
            // The API has USD-based metal prices like "USDXAU": 4697.8859982796
            // This means 1 XAU = 4697.8859982796 USD (which is what we want)
            var usdBasedKey = 'USD' + apiMetalCode;
            
            if (pmrcgold_api_data.rates && pmrcgold_api_data.rates[usdBasedKey]) {
                // USDXAU already gives us the price of 1 XAU in USD
                priceInBase = pmrcgold_api_data.rates[usdBasedKey];
            }
            // Fallback: Direct metal price like "XAU": 0.0002128617 (price per 1 USD)
            else if (pmrcgold_api_data.rates && pmrcgold_api_data.rates[apiMetalCode]) {
                var directRate = pmrcgold_api_data.rates[apiMetalCode];
                priceInBase = directRate; // Use direct price for 1 metal unit
            }
            // Alternative structure: { "XAU": 1850.50, "XAG": 22.75, ... }
            else if (pmrcgold_api_data[apiMetalCode]) {
                priceInBase = pmrcgold_api_data[apiMetalCode];
            } else {
        
            }

            if (priceInBase) {
                // Convert to selected currency if needed
                var priceInSelected = priceInBase;
                
                if (currency !== pmrcgold_api_data.base && pmrcgold_api_data.rates[currency]) {
                    // For currency conversion: if base is USD and we want INR
                    // and metal price is in USD, we need to multiply by INR rate
                    var currencyRate = pmrcgold_api_data.rates[currency];
                    
                    if (currency === 'INR') {
                        // For INR: 1 USD = 93.472 INR, so metal price in USD * 93.472 = price in INR
                        priceInSelected = priceInBase * currencyRate;
                    } else {
                        // For other currencies, similar logic
                        priceInSelected = priceInBase * currencyRate;
                    }
                }

                // Format price with 2 decimal places
                var formattedPrice = formatPrice(priceInSelected, currency);
                $priceSpan.text(formattedPrice);

                // Calculate price change (placeholder - would need historical data)
                var change = calculatePriceChange(metal, currency, priceInSelected);
             
                if (change !== null && change !== undefined) {
                    var changeClass = change >= 0 ? 'price-up' : 'price-down';
                    var changeSymbol = change >= 0 ? '↑' : '↓';
                    var formattedChange = Math.abs(change).toFixed(2);
                    
                    // Apply color styling
                    if (change >= 0) {
                        $changeSpan.css('color', '#28a745'); // Green for up
                    } else {
                        $changeSpan.css('color', '#dc3545'); // Red for down
                    }
                    
                    $changeSpan.removeClass('price-up price-down').addClass(changeClass)
                        .text(changeSymbol + ' ' + formattedChange + '%');
                } else {
                    $changeSpan.text('--').css('color', ''); // Reset color
                }
            } else {
                $priceSpan.text('N/A');
                $changeSpan.text('--');
            }
        });
    }

    // Format price with currency symbol
    function formatPrice(price, currency) {
        var symbols = {
            'USD': '$',
            'EUR': '€',
            'GBP': '£',
            'JPY': '¥',
            'INR': '₹',
            'AUD': 'A$',
            'CAD': 'C$',
            'CHF': 'Fr',
            'CNY': '¥'
        };
        var symbol = symbols[currency] || currency + ' ';
        return symbol + price.toFixed(2);
    }

    // Calculate price change using real historical data
    function calculatePriceChange(metal, currency, currentPrice) {
        // Use real yesterday's data if available
        if (pmrcgold_yesterday_data && pmrcgold_yesterday_data.rates) {
            var metalKey = metal.toUpperCase();
            var metalCodes = {
                'GOLD': 'XAU',
                'SILVER': 'XAG', 
                'PLATINUM': 'XPT',
                'PALLADIUM': 'XPD'
            };
            var apiMetalCode = metalCodes[metalKey] || metalKey;
            var usdBasedKey = 'USD' + apiMetalCode;
            
            var yesterdayPrice = null;
            
            // Get yesterday's price (same logic as current price)
            if (pmrcgold_yesterday_data.rates[usdBasedKey]) {
                yesterdayPrice = pmrcgold_yesterday_data.rates[usdBasedKey];
            } else if (pmrcgold_yesterday_data.rates[apiMetalCode]) {
                var directRate = pmrcgold_yesterday_data.rates[apiMetalCode];
                yesterdayPrice = 1 / directRate;
            }
            
            if (yesterdayPrice && yesterdayPrice > 0) {
                // Calculate real percentage change
                var changePercent = ((currentPrice - yesterdayPrice) / yesterdayPrice) * 100;
                return changePercent;
            }
        }
        
        // Fallback: if no yesterday data, show a small positive change
        return 0; // Show +0% as default (more visible than 0%)
    }

    // Start waiting for API data
    waitForApiData();
});
