export const WEEKDAYS = [
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday",
] as const;

export function toMinutes(t: string): number {
  const [h, m] = t.split(":").map(Number);
  return h * 60 + m;
}

export function toHHMM(mins: number): string {
  const h = Math.floor(mins / 60).toString().padStart(2, "0");
  const m = (mins % 60).toString().padStart(2, "0");
  return `${h}:${m}`;
}

export function fmt12(t: string): string {
  const [h, m] = t.split(":").map(Number);
  const period = h >= 12 ? "pm" : "am";
  const h12 = h % 12 === 0 ? 12 : h % 12;
  return `${h12}${m ? ":" + m.toString().padStart(2, "0") : ""}${period}`;
}

export function chunkTimeRange(
  start: string,
  end: string,
  durationMins: number
): { start: string; end: string }[] {
  const chunks: { start: string; end: string }[] = [];
  let cursor = toMinutes(start);
  const endMinutes = toMinutes(end);

  while (cursor + durationMins <= endMinutes) {
    chunks.push({ start: toHHMM(cursor), end: toHHMM(cursor + durationMins) });
    cursor += durationMins;
  }
  return chunks;
}

// Parses "2026-07-10" as UTC midnight, explicitly — never local time.
// This is the fix: avoids the silent day-shift that happens when
// new Date("2026-07-10T00:00:00") gets interpreted in a UTC+5:30 timezone.
export function parseDateUTC(dateStr: string): Date {
  const [y, m, d] = dateStr.split("-").map(Number);
  return new Date(Date.UTC(y, m - 1, d));
}

export function formatDateUTC(date: Date): string {
  return date.toISOString().slice(0, 10);
}

// Inclusive on both ends — selecting 6 to 10 now genuinely returns 6,7,8,9,10
export function getDatesInRange(startDate: string, endDate: string): Date[] {
  const dates: Date[] = [];
  const cursor = parseDateUTC(startDate);
  const end = parseDateUTC(endDate);

  while (cursor.getTime() <= end.getTime()) {
    dates.push(new Date(cursor));
    cursor.setUTCDate(cursor.getUTCDate() + 1);
  }
  return dates;
}