﻿        function CurrencyConverter() {
            const [rates, setRates] = useState({
                USD: 1,
                EUR: 0.92,
                GBP: 0.79,
                INR: 83.12,
                JPY: 149.50,
                AUD: 1.52,
                CAD: 1.36,
                CHF: 0.88,
                CNY: 7.24
            });

            const [activeCurrencies, setActiveCurrencies] = useState(['USD', 'EUR', 'GBP', 'INR', 'JPY', 'AUD']);
            const [values, setValues] = useState({});
            const [loading, setLoading] = useState(false);
            const [lastUpdated, setLastUpdated] = useState(null);
            const [showAddCurrency, setShowAddCurrency] = useState(false);

            const allCurrencies = {
                USD: { name: 'US Dollar', symbol: '$' },
                EUR: { name: 'Euro', symbol: '€' },
                GBP: { name: 'British Pound', symbol: '£' },
                INR: { name: 'Indian Rupee', symbol: '₹' },
                JPY: { name: 'Japanese Yen', symbol: '¥' },
                AUD: { name: 'Australian Dollar', symbol: '$' },
                CAD: { name: 'Canadian Dollar', symbol: '$' },
                CHF: { name: 'Swiss Franc', symbol: 'Fr' },
                CNY: { name: 'Chinese Yuan', symbol: '¥' },
                KRW: { name: 'South Korean Won', symbol: '₩' },
                SGD: { name: 'Singapore Dollar', symbol: '$' },
                HKD: { name: 'Hong Kong Dollar', symbol: '$' },
                NZD: { name: 'New Zealand Dollar', symbol: '$' },
                SEK: { name: 'Swedish Krona', symbol: 'kr' },
                NOK: { name: 'Norwegian Krone', symbol: 'kr' },
                MXN: { name: 'Mexican Peso', symbol: '$' },
                BRL: { name: 'Brazilian Real', symbol: 'R$' },
                ZAR: { name: 'South African Rand', symbol: 'R' },
                RUB: { name: 'Russian Ruble', symbol: '₽' },
                TRY: { name: 'Turkish Lira', symbol: '₺' }
            };

            const fetchLiveRates = async () => {
                setLoading(true);
                try {
                    // Using exchangerate-api.com free API
                    const response = await fetch('https://api.exchangerate-api.com/v4/latest/USD');
                    const data = await response.json();

                    if (data && data.rates) {
                        setRates(data.rates);
                        setLastUpdated(new Date().toLocaleString());
                        alert('✅ Exchange rates updated successfully!');
                    }
                } catch (error) {
                    alert('❌ Failed to fetch live rates. Please check your internet connection.');
                } finally {
                    setLoading(false);
                }
            };

            const convertCurrency = (fromCurrency, value) => {
                if (!value || value === '') {
                    setValues({});
                    return;
                }

                const amount = parseFloat(value);
                const newValues = { [fromCurrency]: value };

                activeCurrencies.forEach(currency => {
                    if (currency !== fromCurrency) {
                        // Convert from source currency to USD, then to target currency
                        const usdAmount = amount / rates[fromCurrency];
                        const convertedAmount = usdAmount * rates[currency];
                        newValues[currency] = convertedAmount.toFixed(2);
                    }
                });

                setValues(newValues);
            };

            const addCurrency = (currency) => {
                if (!activeCurrencies.includes(currency)) {
                    setActiveCurrencies([...activeCurrencies, currency]);
                    setShowAddCurrency(false);
                }
            };

            const removeCurrency = (currency) => {
                if (activeCurrencies.length > 2) {
                    setActiveCurrencies(activeCurrencies.filter(c => c !== currency));
                    const newValues = { ...values };
                    delete newValues[currency];
                    setValues(newValues);
                } else {
                    alert('You must have at least 2 currencies!');
                }
            };

            const availableCurrencies = Object.keys(allCurrencies).filter(c => !activeCurrencies.includes(c));

            return (
                <div className="card">
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                        <h3 style={{ margin: 0 }}>💱 Currency Converter</h3>
                        <button
                            className="btn btn-primary"
                            onClick={fetchLiveRates}
                            disabled={loading}
                            style={{ fontSize: '13px', padding: '6px 12px' }}
                        >
                            {loading ? '⏳ Updating...' : '🔄 Get Live Rates'}
                        </button>
                    </div>

                    {lastUpdated && (
                        <div style={{ fontSize: '12px', color: 'var(--success)', marginBottom: '12px' }}>
                            ✅ Last updated: {lastUpdated}
                        </div>
                    )}

                    <p style={{ color: 'var(--text-secondary)', fontSize: '14px', marginBottom: '16px' }}>
                        Enter amount in any currency for real-time conversion
                    </p>

                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px', marginBottom: '16px' }}>
                        {activeCurrencies.map(currency => (
                            <div key={currency} className="form-group" style={{ marginBottom: '0', position: 'relative' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <label className="form-label">
                                        {allCurrencies[currency]?.name || currency} ({currency} {allCurrencies[currency]?.symbol || ''})
                                    </label>
                                    {activeCurrencies.length > 2 && (
                                        <button
                                            onClick={() => removeCurrency(currency)}
                                            style={{
                                                background: 'none',
                                                border: 'none',
                                                color: 'var(--danger)',
                                                cursor: 'pointer',
                                                fontSize: '18px',
                                                padding: '0',
                                                lineHeight: '1'
                                            }}
                                            title="Remove currency"
                                        >
                                            ×
                                        </button>
                                    )}
                                </div>
                                <input
                                    type="number"
                                    className="form-input"
                                    value={values[currency] || ''}
                                    onChange={(e) => convertCurrency(currency, e.target.value)}
                                    placeholder="0.00"
                                />
                            </div>
                        ))}
                    </div>

                    {availableCurrencies.length > 0 && (
                        <div style={{ marginTop: '16px' }}>
                            {!showAddCurrency ? (
                                <button
                                    className="btn btn-secondary"
                                    onClick={() => setShowAddCurrency(true)}
                                    style={{ fontSize: '13px', width: '100%' }}
                                >
                                    + Add Currency
                                </button>
                            ) : (
                                <div style={{ background: 'var(--bg-tertiary)', padding: '12px', borderRadius: '8px' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                                        <strong style={{ fontSize: '14px' }}>Select Currency to Add:</strong>
                                        <button
                                            onClick={() => setShowAddCurrency(false)}
                                            style={{
                                                background: 'none',
                                                border: 'none',
                                                color: 'var(--text-secondary)',
                                                cursor: 'pointer',
                                                fontSize: '20px',
                                                padding: '0',
                                                lineHeight: '1'
                                            }}
                                        >
                                            ×
                                        </button>
                                    </div>
                                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '8px', maxHeight: '200px', overflowY: 'auto' }}>
                                        {availableCurrencies.map(currency => (
                                            <button
                                                key={currency}
                                                className="btn btn-secondary"
                                                onClick={() => addCurrency(currency)}
                                                style={{ fontSize: '12px', padding: '8px', textAlign: 'left' }}
                                            >
                                                {currency} - {allCurrencies[currency]?.name || currency}
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    <div style={{ marginTop: '12px', fontSize: '12px', color: 'var(--text-secondary)', fontStyle: 'italic' }}>
                        {lastUpdated ?
                            'Using live exchange rates. Click "Get Live Rates" to refresh.' :
                            'Using approximate rates. Click "Get Live Rates" for current market rates.'
                        }
                    </div>
                </div>
            );
        }

// Export to global registry
window.CurrencyConverter = CurrencyConverter;
