import { useMemo } from "react"; import { useTranslation } from "react-i18next"; export interface CompareReferenceMonthPickerProps { year: number; month: number; onChange: (year: number, month: number) => void; /** Number of recent months to show in the dropdown. Default: 24. */ monthCount?: number; /** "today" override for tests. */ today?: Date; } interface Option { value: string; // "YYYY-MM" year: number; month: number; label: string; } function formatMonth(year: number, month: number, language: string): string { const date = new Date(year, month - 1, 1); return new Intl.DateTimeFormat(language === "fr" ? "fr-CA" : "en-CA", { month: "long", year: "numeric", }).format(date); } export default function CompareReferenceMonthPicker({ year, month, onChange, monthCount = 24, today = new Date(), }: CompareReferenceMonthPickerProps) { const { t, i18n } = useTranslation(); const options = useMemo(() => { const list: Option[] = []; let y = today.getFullYear(); let m = today.getMonth() + 1; for (let i = 0; i < monthCount; i++) { list.push({ value: `${y}-${String(m).padStart(2, "0")}`, year: y, month: m, label: formatMonth(y, m, i18n.language), }); m -= 1; if (m === 0) { m = 12; y -= 1; } } return list; }, [today, monthCount, i18n.language]); const currentValue = `${year}-${String(month).padStart(2, "0")}`; const isKnown = options.some((o) => o.value === currentValue); const displayOptions = isKnown ? options : [ { value: currentValue, year, month, label: formatMonth(year, month, i18n.language), }, ...options, ]; return ( ); }