// Initialize config based on the existence of ecreAdmin or ecreFrontend
let config = {};

if (window.ecreAdmin) {
    config = Object.assign({}, window.ecreAdmin);
} else if (window.ecreFrontend) {
    config = Object.assign({}, window.ecreFrontend);
}

export const displayProPopup = () => {
    WPPOOL.Popup('echo_rewards').show();
}

export function translate(key) {
    return config.strings && config.strings[key] ? config.strings[key] : key;
}

/**
 * Format a price using WooCommerce currency settings.
 *
 * Mirrors the PHP ecre_format_price() function, respecting:
 * - Currency symbol
 * - Currency position (left, right, left_space, right_space)
 * - Thousand separator
 * - Decimal separator
 * - Number of decimals
 *
 * @param {number|string} price - The numeric price to format.
 * @param {boolean} includeSymbol - Whether to include the currency symbol (default: true).
 * @returns {string} The formatted price string.
 */
export function formatPrice(price, includeSymbol = true) {
    const cs = config.currency_settings || {};
    const symbol = cs.symbol || config.currency || '$';
    const position = cs.position || 'left';
    const thousandSep = cs.thousand_separator !== undefined ? cs.thousand_separator : ',';
    const decimalSep = cs.decimal_separator !== undefined ? cs.decimal_separator : '.';
    const decimals = cs.decimals !== undefined ? parseInt(cs.decimals, 10) : 2;

    // Format the number with separators and decimals.
    const num = parseFloat(price) || 0;
    const fixed = num.toFixed(decimals);
    const [intPart, decPart] = fixed.split('.');

    // Add thousand separator.
    const withThousands = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep);
    const formattedPrice = decimals > 0 ? withThousands + decimalSep + decPart : withThousands;

    if (!includeSymbol) {
        return formattedPrice;
    }

    // Position the currency symbol.
    switch (position) {
        case 'left':
            return symbol + formattedPrice;
        case 'right':
            return formattedPrice + symbol;
        case 'left_space':
            return symbol + ' ' + formattedPrice;
        case 'right_space':
            return formattedPrice + ' ' + symbol;
        default:
            return symbol + formattedPrice;
    }
}
