import type { YearlyFinancials } from '@/types/growth-score';

export type YearRange = {
    start: number;
    end: number;
    label: string;
};

export function formatMoney(value: number, currency = 'USD'): string {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency,
        maximumFractionDigits: 0,
    }).format(value);
}

export function formatCompactMoney(value: number, currency = 'USD'): string {
    return new Intl.NumberFormat(undefined, {
        style: 'currency',
        currency,
        notation: 'compact',
        maximumFractionDigits: 1,
    }).format(value);
}

export function formatPercent(value: number | null): string {
    if (value === null) {
        return '—';
    }

    const formatted = new Intl.NumberFormat('en-US', {
        maximumFractionDigits: 1,
        signDisplay: 'exceptZero',
    }).format(value);

    return `${formatted}%`;
}

export function formatScore(value: number | null): string {
    if (value === null) {
        return '—';
    }

    return `${new Intl.NumberFormat('en-US', {
        maximumFractionDigits: 1,
    }).format(value)} / 100`;
}

export function yearRangesFrom(years: YearlyFinancials[]): YearRange[] {
    if (years.length === 0) {
        return [];
    }

    const sorted = years.map((item) => item.year).sort((a, b) => a - b);
    const end = sorted[sorted.length - 1]!;

    return sorted.map((start) => {
        const count = end - start + 1;

        return {
            start,
            end,
            label: `${start}–${end} (${count} Year${count === 1 ? '' : 's'})`,
        };
    });
}

export function defaultYearRange(years: YearlyFinancials[]): YearRange | null {
    return yearRangesFrom(years)[0] ?? null;
}

export function yearsInRange(
    years: YearlyFinancials[],
    range: YearRange | null,
): YearlyFinancials[] {
    if (range === null) {
        return years;
    }

    return years.filter(
        (item) => item.year >= range.start && item.year <= range.end,
    );
}
