export function formateaMoneda(valor, digits = 2, locale = 'es-ES', currency = 'EUR') {
    try {
        return new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits: digits, useGrouping: true }).format(valor);
    } catch {
        return valor;
    }
}


export function formateaNumero({
    valor,
    digits = 2,
    style = 'decimal',
    locale = 'es-ES',
    currency = 'EUR'
}) {
    const n = Number(valor);
    if (!Number.isFinite(n)) return valor;

    const opts = {
        useGrouping: true,
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
    };

    if (style === 'currency') {
        opts.style = 'currency';
        opts.currency = currency;
    }

    return new Intl.NumberFormat(locale, opts).format(n);
}


export function isNumber(value) {

    if(typeof value === 'string') {
        if(value.trim() === '') return false;
    }
    return !isNaN(Number(value));
}

// Aplana un objeto a "prefijo.clave" (sin arrays)
export function dotify(obj, prefix = '') {
    const out = {};
    const walk = (o, path) => {
        Object.entries(o).forEach(([k, v]) => {
            const key = path ? `${path}.${k}` : k;
            if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
                walk(v, key);
            } else {
                out[key] = v;
            }
        });
    };
    walk(obj, prefix);
    return out;
}

// Convierte {a:1, b:2} en {"summary[a]":1, "summary[b]":2}
export function bracketPrefix(obj, prefix) {
    const out = {};
    Object.entries(obj).forEach(([k, v]) => {
        out[`${prefix}[${k}]`] = v;
    });
    return out;
}