/**
 * Converting between the three date shapes the schedule fields pass around: a
 * `Date`, a bare `yyyy-MM-dd` day, and the full ISO timestamp the form stores.
 *
 * Pure and separate because the local-vs-UTC rule documented on
 * `toFormDateValue` is the whole reason these exist, and it is invisible until
 * someone runs the app in a timezone west of Greenwich.
 */
export const toIsoDay = (date: Date): string => {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}-${month}-${day}`;
};

export const parseIsoDay = (value: string): Date | null => {
  const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
  if (!match) return null;
  const parsed = new Date(
    Number(match[1]),
    Number(match[2]) - 1,
    Number(match[3])
  );
  return Number.isNaN(parsed.getTime()) ? null : parsed;
};

/**
 * `startDate` / `endDate` carry a full ISO timestamp taken from local midnight,
 * which is what the rest of the form and its helpers expect. It matters:
 * `formatDateToYYYYMMDD()` and the `notInPast` rule both build a `new Date()`
 * from these values and then read `.getDate()` off it, and `new Date()` treats
 * a bare `yyyy-MM-dd` as **UTC** while those getters are **local** — so a plain
 * date string lands on the previous day everywhere west of Greenwich, and
 * "today" reads as being in the past. Round-tripping through local midnight
 * keeps the calendar day the organiser clicked.
 */
export const toFormDateValue = (day?: string): string => {
  if (!day) return "";
  const parsed = parseIsoDay(day);
  return parsed ? parsed.toISOString() : "";
};

export const formatForDisplay = (value: string, locale: string): string => {
  const parsed = parseIsoDay(value);
  if (!parsed) return value;
  // Latin digits in both languages, like every other date on the site (the API client also
  // normalises digits); `ar-EG` alone would print Arabic-Indic numerals here only.
  return parsed.toLocaleDateString(locale === "ar" ? "ar-EG-u-nu-latn" : "en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
};

/**
 * The three values a day selection writes.
 *
 * Deduplicated and **sorted**, because the picker hands days back in click
 * order: without the sort, picking the 9th then the 2nd would store the 9th as
 * `startDate`, and every date rule, sort and card downstream reads those two.
 *
 * Both modes write all three. That is what lets the existing due-date and
 * end-after-start rules, the listing sort and every card that prints a range
 * keep working untouched — only `scheduleDates` differs between the modes.
 */
export function deriveScheduleFromDays(days: string[]): {
  scheduleDates: string[];
  startDate: string;
  endDate: string;
} {
  const ordered = [...new Set(days)].sort();
  return {
    scheduleDates: ordered,
    startDate: toFormDateValue(ordered[0]),
    endDate: toFormDateValue(ordered[ordered.length - 1]),
  };
}
