import { format, parseISO, startOfWeek } from 'date-fns';

/**
 * Shared week canonicalization. **American style** — the week starts on
 * **Sunday** (`weekStartsOn: 0`). One source of truth for the dashboard hero,
 * the F.R.A.M.E. weekly entry, and the safety-quiz week, so they never drift.
 */
const WEEK_STARTS_ON = 0; // Sunday

/** The Date at the start (Sunday, local midnight) of the week containing `date`. */
export function getWeekStart(date: Date): Date {
  return startOfWeek(date, { weekStartsOn: WEEK_STARTS_ON });
}

/** The week-start (Sunday) as an ISO `YYYY-MM-DD` string. The canonical key. */
export function toWeekStartIso(date: Date): string {
  return format(getWeekStart(date), 'yyyy-MM-dd');
}

/**
 * Human display for a week-start ISO date, e.g. `2026-06-07` → `June 7, 2026`.
 * Snaps to the week start defensively in case a non-normalized date is passed.
 */
export function formatWeekOf(weekStartIso: string): string {
  return format(getWeekStart(parseISO(weekStartIso)), 'MMMM d, yyyy');
}

/** Whether `weekStartIso` is the current week (in the runtime's local time). */
export function isCurrentWeek(weekStartIso: string, now: Date = new Date()): boolean {
  return weekStartIso === toWeekStartIso(now);
}
