export const formatCurrency = (val) => {
    const num = Number(val);
    if (val == null || isNaN(num)) return 'R$ 0,00';
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(num);
};

export const parseCurrency = (val) => {
    if (val == null) return 0;
    if (typeof val === 'number') return val;
    let s = String(val).replace('R$', '').trim();
    if (!s) return 0;

    // Detect if it's BR format (comma for decimal) or US/standard (dot for decimal)
    const hasComma = s.includes(',');
    if (hasComma) {
        // BR format: remove dots as thousands separator, replace comma with dot
        s = s.replace(/\./g, '').replace(',', '.');
    } else {
        // US/Standard format: might have multiple dots if misinterpreted?
        // Usually, if it's a string from a standard JSON, it's "68.00"
        // But if it's "22.800" without decimals, parseFloat works fine as 22.8 (which might be wrong if 22800 was intended)
        // However, looking at the user's data, the US format is used for simple floats.
        const dotCount = (s.match(/\./g) || []).length;
        if (dotCount > 1) {
            // Probably BR format but without the comma (e.g. 22.800)
            s = s.replace(/\./g, '');
        }
    }
    
    const num = parseFloat(s);
    return isNaN(num) ? 0 : num;
};

export const parseDateInfo = (dateStr) => {
    if (!dateStr) return { year: 0, month: 0, day: 0 };
    try {
        console.log('[dateUtils] Realizando parse de data bruta:', dateStr);
        // Tenta formato BR: DD/MM/YYYY HH:MM:SS ou DD/MM/YYYY
        if (typeof dateStr === 'string' && /^\d{2}\/\d{2}\/\d{4}/.test(dateStr)) {
            const datePart = dateStr.split(' ')[0];
            const [d, m, y] = datePart.split('/');
            return {
                year: Number(y),
                month: Number(m.replace(/^0+/, '')),
                day: Number(d.replace(/^0+/, ''))
            };
        }
        // Tenta formato ISO (YYYY-MM-DD)
        if (typeof dateStr === 'string' && /^\d{4}-\d{2}-\d{2}/.test(dateStr)) {
            const [y, m, d] = dateStr.split('-');
            return { 
                year: Number(y), 
                month: Number(m.replace(/^0+/, '')), 
                day: Number(d?.substring(0,2).replace(/^0+/, '') || 0) 
            };
        }
        // Tenta objeto Date ou string GMT (ex: Thu, 12 Feb 2026...)
        const dObj = new Date(dateStr);
        if (!isNaN(dObj.getTime())) {
            return { 
                year: dObj.getUTCFullYear(), 
                month: dObj.getUTCMonth() + 1, 
                day: dObj.getUTCDate() 
            };
        }
    } catch (e) {
        console.warn('[dateUtils] Erro ao processar data:', dateStr, e);
    }
    return { year: 0, month: 0, day: 0 };
};
