const DAY_LABELS = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"] as const;

export type WeekDay = {
  date: string;
  label: string;
  dayNum: number;
  isToday: boolean;
};

const VISIBLE_DAYS = 7;

/**
 * Jours affichés dans le calendrier.
 * - offset 0 : 7 jours à partir d’aujourd’hui (jours passés masqués)
 * - offset ≠ 0 : semaine complète lun–dim décalée
 */
export function getWeekDays(anchor: Date, weekOffset = 0): WeekDay[] {
  const todayIso = formatDateIso(new Date());

  if (weekOffset === 0) {
    const today = parseIsoDate(todayIso);
    const days: WeekDay[] = [];
    const d = new Date(today);
    while (days.length < VISIBLE_DAYS) {
      days.push(makeWeekDay(d, todayIso));
      d.setDate(d.getDate() + 1);
    }
    return days;
  }

  const weekStart = startOfWeekMonday(anchor);
  weekStart.setDate(weekStart.getDate() + weekOffset * 7);
  const days: WeekDay[] = [];
  for (let i = 0; i < VISIBLE_DAYS; i++) {
    const d = new Date(weekStart);
    d.setDate(weekStart.getDate() + i);
    days.push(makeWeekDay(d, todayIso));
  }
  return days;
}

export function formatDateIso(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

export function formatWeekRangeLabel(days: WeekDay[]): string {
  if (days.length === 0) return "";
  const first = parseIsoDate(days[0].date);
  const last = parseIsoDate(days[days.length - 1].date);
  const opts: Intl.DateTimeFormatOptions = { day: "numeric", month: "long" };
  if (first.getMonth() === last.getMonth()) {
    return `${first.getDate()} — ${last.toLocaleDateString("fr-FR", { ...opts, year: "numeric" })}`;
  }
  return `${first.toLocaleDateString("fr-FR", opts)} — ${last.toLocaleDateString("fr-FR", { ...opts, year: "numeric" })}`;
}

function makeWeekDay(d: Date, todayIso: string): WeekDay {
  const date = formatDateIso(d);
  const jsDay = d.getDay();
  const labelIndex = jsDay === 0 ? 6 : jsDay - 1;
  return {
    date,
    label: DAY_LABELS[labelIndex],
    dayNum: d.getDate(),
    isToday: date === todayIso,
  };
}

function startOfWeekMonday(d: Date): Date {
  const copy = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  const day = copy.getDay();
  const diff = day === 0 ? -6 : 1 - day;
  copy.setDate(copy.getDate() + diff);
  return copy;
}

function parseIsoDate(iso: string): Date {
  const [y, m, d] = iso.split("-").map(Number);
  return new Date(y, m - 1, d);
}
