/**
 * Currency formatting utility for MBetter betting system
 */

class CurrencyFormatter {
    constructor() {
        this.settings = {
            symbol: 'USh',
            position: 'before'
        };
        this.loaded = false;
        this.loadPromise = null;
    }

    /**
     * Load currency settings from the API
     * @returns {Promise} Promise that resolves when settings are loaded
     */
    async loadSettings() {
        if (this.loadPromise) {
            return this.loadPromise;
        }

        this.loadPromise = fetch('/api/currency-settings')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.settings) {
                    this.settings = {
                        symbol: data.settings.symbol || 'USh',
                        position: data.settings.position || 'before'
                    };
                    this.loaded = true;
                    console.log('Currency settings loaded:', this.settings);
                } else {
                    console.warn('Failed to load currency settings, using defaults');
                    this.loaded = true;
                }
            })
            .catch(error => {
                console.warn('Error loading currency settings, using defaults:', error);
                this.loaded = true;
            });

        return this.loadPromise;
    }

    /**
     * Format an amount with the configured currency symbol and position
     * @param {number|string} amount The amount to format
     * @param {number} decimals Number of decimal places (default: 2)
     * @returns {string} Formatted currency string
     */
    format(amount, decimals = 2) {
        if (!this.loaded) {
            console.warn('Currency settings not loaded, using default format');
            return `USh ${parseFloat(amount || 0).toFixed(decimals)}`;
        }

        const numericAmount = parseFloat(amount || 0).toFixed(decimals);
        
        if (this.settings.position === 'after') {
            return `${numericAmount} ${this.settings.symbol}`;
        } else {
            return `${this.settings.symbol} ${numericAmount}`;
        }
    }

    /**
     * Format an amount synchronously (only if settings are already loaded)
     * @param {number|string} amount The amount to format
     * @param {number} decimals Number of decimal places (default: 2)
     * @returns {string} Formatted currency string
     */
    formatSync(amount, decimals = 2) {
        return this.format(amount, decimals);
    }

    /**
     * Get the current currency symbol
     * @returns {string} Currency symbol
     */
    getSymbol() {
        return this.settings.symbol;
    }

    /**
     * Get the current currency position
     * @returns {string} Position ('before' or 'after')
     */
    getPosition() {
        return this.settings.position;
    }

    /**
     * Check if currency settings are loaded
     * @returns {boolean} True if loaded
     */
    isLoaded() {
        return this.loaded;
    }
}

// Create global instance
window.CurrencyFormatter = new CurrencyFormatter();

// Auto-load settings when the script is included
document.addEventListener('DOMContentLoaded', function() {
    window.CurrencyFormatter.loadSettings().then(() => {
        // Dispatch custom event when currency settings are loaded
        const event = new CustomEvent('currencySettingsLoaded', {
            detail: {
                symbol: window.CurrencyFormatter.getSymbol(),
                position: window.CurrencyFormatter.getPosition()
            }
        });
        document.dispatchEvent(event);
    });
});

/**
 * Helper function for backward compatibility
 * @param {number|string} amount The amount to format
 * @param {number} decimals Number of decimal places (default: 2)
 * @returns {string} Formatted currency string
 */
function formatCurrency(amount, decimals = 2) {
    return window.CurrencyFormatter.formatSync(amount, decimals);
}