/**
 * Universal Currency Converter
 * Automatically converts all prices on the page based on selected currency
 * SAFE VERSION - Won't block page loading
 */

(function() {
    'use strict';

    // Exchange rates (base: EUR)
    const exchangeRates = {
        'eur': 1.0,
        'usd': 1.10,
        'gbp': 0.87,
        'cad': 1.48
    };

    // Currency symbols
    const currencySymbols = {
        'eur': '€',
        'usd': '$',
        'gbp': '£',
        'cad': 'C$'
    };

    // Store original prices
    const priceData = new Map();
    let isConverting = false;

    /**
     * Format price with currency symbol
     */
    function formatPrice(amount, currency) {
        try {
            const symbol = currencySymbols[currency] || '€';
            return symbol + amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        } catch (e) {
            console.error('Format price error:', e);
            return '€' + amount.toFixed(2);
        }
    }

    /**
     * Get currency code from symbol
     */
    function getCurrencyFromSymbol(symbol) {
        const map = {
            '$': 'usd',
            '€': 'eur',
            '£': 'gbp',
            'C$': 'cad'
        };
        return map[symbol] || 'eur';
    }

    /**
     * Extract price and currency from text
     */
    function parsePrice(text) {
        if (!text || typeof text !== 'string') return null;
        
        try {
            // Try C$ first (two characters)
            let match = text.match(/C\$\s*([\d,]+\.?\d*)/);
            if (match) {
                return {
                    value: parseFloat(match[1].replace(/,/g, '')),
                    currency: 'cad',
                    symbol: 'C$',
                    fullMatch: match[0]
                };
            }
            
            // Try single character symbols
            match = text.match(/([$€£])\s*([\d,]+\.?\d*)/);
            if (match) {
                return {
                    value: parseFloat(match[2].replace(/,/g, '')),
                    currency: getCurrencyFromSymbol(match[1]),
                    symbol: match[1],
                    fullMatch: match[0]
                };
            }
        } catch (e) {
            console.error('Parse price error:', e);
        }
        
        return null;
    }

    /**
     * Convert all prices on the page (SAFE VERSION)
     */
    function convertAllPrices(targetCurrency) {
        if (isConverting) return; // Prevent concurrent conversions
        if (!targetCurrency || !exchangeRates[targetCurrency]) {
            console.error('Invalid currency:', targetCurrency);
            return;
        }

        try {
            isConverting = true;
            const targetRate = exchangeRates[targetCurrency] || 1.0;
            const targetSymbol = currencySymbols[targetCurrency] || '€';

            // Only process elements that haven't been processed
            const priceElements = document.querySelectorAll('p, span, div, td, h3, h4, h5');
            let convertedCount = 0;

            priceElements.forEach(element => {
                // Skip if already processed or has children with prices
                if (element.dataset.priceConverted === 'true' || 
                    element.querySelector('[data-price-converted="true"]')) {
                    return;
                }

                // Skip script and style elements
                if (element.tagName === 'SCRIPT' || element.tagName === 'STYLE') {
                    return;
                }

                const text = element.textContent || '';
                if (!text.trim()) return;

                const priceInfo = parsePrice(text);
                
                if (priceInfo && priceInfo.value > 0 && priceInfo.value < 1000000) {
                    // Store original if not stored
                    const elementId = element.tagName + '-' + (element.id || Math.random());
                    if (!priceData.has(elementId)) {
                        priceData.set(elementId, {
                            element: element,
                            originalText: text,
                            basePrice: priceInfo.value / (exchangeRates[priceInfo.currency] || 1.0),
                            baseCurrency: priceInfo.currency
                        });
                    }

                    const stored = priceData.get(elementId);
                    const convertedPrice = stored.basePrice * targetRate;
                    const formattedPrice = formatPrice(convertedPrice, targetCurrency);
                    
                    // Replace price in text
                    const newText = text.replace(priceInfo.fullMatch, formattedPrice);
                    if (newText !== text) {
                        element.textContent = newText;
                        element.dataset.priceConverted = 'true';
                        convertedCount++;
                    }
                }
            });

            // Handle data-price attributes
            document.querySelectorAll('[data-price]').forEach(element => {
                try {
                    const basePrice = parseFloat(element.dataset.price);
                    if (!isNaN(basePrice)) {
                        const baseCurrency = element.dataset.baseCurrency || 'eur';
                        const storedBasePrice = basePrice / (exchangeRates[baseCurrency] || 1.0);
                        const convertedPrice = storedBasePrice * targetRate;
                        element.textContent = formatPrice(convertedPrice, targetCurrency);
                    }
                } catch (e) {
                    console.error('Data-price conversion error:', e);
                }
            });

            console.log('✅ Currency conversion complete:', targetCurrency.toUpperCase(), '(' + convertedCount + ' prices)');
        } catch (e) {
            console.error('Currency conversion error:', e);
        } finally {
            isConverting = false;
        }
    }

    /**
     * Initialize currency converter
     */
    function initCurrencyConverter() {
        try {
            // Get selected currency from cookie or default to EUR
            const currencyCookie = getCookie('selected_currency');
            const selectedCurrency = currencyCookie || 'eur';
            
            // Wait for DOM to be fully ready
            function doConversion() {
                if (document.body && document.body.children.length > 0) {
                    convertAllPrices(selectedCurrency);
                } else {
                    setTimeout(doConversion, 100);
                }
            }

            // Convert prices on page load (with delay to ensure DOM is ready)
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', () => {
                    setTimeout(doConversion, 1000);
                });
            } else {
                setTimeout(doConversion, 1000);
            }

            // Listen for currency changes from dropdown
            setTimeout(() => {
                const currencySelect = document.getElementById('currencySelect');
                if (currencySelect && !currencySelect.dataset.listenerAdded) {
                    currencySelect.dataset.listenerAdded = 'true';
                    currencySelect.addEventListener('change', function() {
                        const newCurrency = this.value;
                        setCookie('selected_currency', newCurrency, 365);
                        convertAllPrices(newCurrency);
                    });
                }
            }, 500);

        } catch (e) {
            console.error('Currency converter init error:', e);
        }
    }

    /**
     * Cookie helpers
     */
    function setCookie(name, value, days) {
        try {
            const expires = new Date();
            expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
            document.cookie = name + '=' + value + ';expires=' + expires.toUTCString() + ';path=/';
        } catch (e) {
            console.error('Set cookie error:', e);
        }
    }

    function getCookie(name) {
        try {
            const nameEQ = name + '=';
            const ca = document.cookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
            }
        } catch (e) {
            console.error('Get cookie error:', e);
        }
        return null;
    }

    // Initialize safely
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initCurrencyConverter);
    } else {
        setTimeout(initCurrencyConverter, 100);
    }

    // Export for manual use
    window.currencyConverter = {
        convert: convertAllPrices,
        rates: exchangeRates,
        symbols: currencySymbols
    };
})();
