import moment from "moment";

/**
 * Day and month names for the consultation slot picker.
 *
 * Written out rather than taken from `toLocaleDateString`: the Arabic month
 * names here are the Levantine/Gulf set the client uses («يناير، فبراير…»), and
 * `ar-EG` would give them, but `ar` on some runtimes returns the Levantine set
 * («كانون الثاني…») instead. A fixed table is the only way to be sure the same
 * names appear on every device.
 */
export const DAYS_AR = [
  "الأحد",
  "الإثنين",
  "الثلاثاء",
  "الأربعاء",
  "الخميس",
  "الجمعة",
  "السبت",
];
export const DAYS_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
export const MONTHS_AR = [
  "يناير",
  "فبراير",
  "مارس",
  "أبريل",
  "مايو",
  "يونيو",
  "يوليو",
  "أغسطس",
  "سبتمبر",
  "أكتوبر",
  "نوفمبر",
  "ديسمبر",
];
export const MONTHS_EN = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];

/**
 * "الأحد, يناير 5, 2027" / "Sun, January 5, 2027".
 *
 * Built from the tables above rather than `toLocaleDateString`, so the month
 * names are the same set on every device.
 */
export function formatConsultationDate(
  dateString: string,
  selectedLanguage: string
): string {
  const date = moment(dateString);
  const dayName =
    selectedLanguage === "ar" ? DAYS_AR[date.day()] : DAYS_EN[date.day()];
  const monthName =
    selectedLanguage === "ar" ? MONTHS_AR[date.month()] : MONTHS_EN[date.month()];
  return `${dayName}, ${monthName} ${date.date()}, ${date.year()}`;
}

/**
 * A slot's start time, 12-hour.
 *
 * Arabic uses **ص / م** rather than am / pm, and moment's `a` token gives the
 * English pair regardless of locale unless the locale bundle is loaded — which
 * this app strips from the build (`IgnorePlugin` on moment's locale data). So
 * the Arabic branch is written out: midnight is 12 (not 0), noon stays 12 and is
 * م, and minutes are zero-padded.
 */
export function formatConsultationTime(
  /* `| null`: `LearnServeTimeSlotResource` emits `start_time` / `end_time`
     straight off nullable columns. Without the guard below,
     `moment(null, "HH:mm:ss")` is an invalid date and the slot would read
     "Invalid date" in the picker. */
  timeString: string | null,
  selectedLanguage: string
): string {
  /* A language-neutral dash rather than a translated placeholder: this sits
     inside `"{start} - {end}"`, where an empty string would render as a bare
     " - " with nothing either side of it. */
  if (!timeString) return "—";

  const time = moment(timeString, "HH:mm:ss");
  if (selectedLanguage !== "ar") return time.format("h:mm a");

  const hour = time.hour();
  const minute = time.minute();
  const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
  return `${hour12}:${minute < 10 ? `0${minute}` : minute} ${hour < 12 ? "ص" : "م"}`;
}