/**
 * The time picker's pure conversions, between the 24-hour string Formik holds
 * and the 12-hour parts the dropdown shows.
 *
 * Extracted from `TimePicker` so the edge cases can be tested without a DOM.
 * Midnight and noon are the ones that matter: 12 AM is hour 0 and 12 PM is
 * hour 12, so a naive `hour + 12` breaks both ends of the day.
 */

export interface TimeParts {
  /** 1–12, as shown. */
  hour: number;
  minute: number;
  period: "AM" | "PM";
}

/** Parse a stored `HH:mm` into display parts, or `null` if it is not one. */
export function parseTimeString(timeString: string): TimeParts | null {
  if (!timeString) return null;

  try {
    const [h, m] = timeString.split(":").map(Number);
    if (isNaN(h) || isNaN(m)) return null;
    return {
      hour: h === 0 ? 12 : h > 12 ? h - 12 : h,
      minute: m,
      period: (h >= 12 ? "PM" : "AM") as "AM" | "PM",
    };
  } catch {
    return null;
  }
}

/** Always pad both parts for display consistency. */
export const formatTimeForDisplay = (hour: number, minute: number): string =>
  `${hour.toString().padStart(2, "0")}:${minute
    .toString()
    .padStart(2, "0")}`;

/** Convert 12-hour parts to the 24-hour `HH:mm` string Formik stores. */
export function convertTo24Hour(
  hour: number,
  minute: number,
  period: "AM" | "PM"
): string {
  let hour24 = hour;
  if (period === "AM" && hour === 12) {
    hour24 = 0;
  } else if (period === "PM" && hour !== 12) {
    hour24 = hour + 12;
  }
  return `${hour24.toString().padStart(2, "0")}:${minute
    .toString()
    .padStart(2, "0")}`;
}

/**
 * Fold a position in the repeated scroll lists back into a real time.
 *
 * The dropdown stacks the 12 hours and 60 minutes fifty times over so the
 * wheels can be spun freely, which means the index handed back can be far
 * outside the real range.
 */
export function normalizeScrollTime(hour: number, minute: number) {
  return {
    hour: ((hour - 1) % 12) + 1,
    minute: minute % 60,
  };
}

/**
 * What the box holds when the reader switches to typing: the stored time as
 * 24-hour `HH:mm`, because typed entry is read as 24-hour (`13:30`). Seeding
 * it with the 12-hour display (`01:30` for 13:30) — or leaving the previous
 * draft, often empty — meant an edit started from the wrong or no value.
 */
export function typedTimeDraft(stored: string | null | undefined): string {
  const match = /^(\d{2}):(\d{2})/.exec(stored ?? "");
  return match ? `${match[1]}:${match[2]}` : "";
}
