// Manual, deterministic date formatting (no Intl/locale APIs). Server and
// client environments can have different ICU data for a given locale
// (especially a less-common one like "mn-MN"), which makes
// `Date#toLocaleDateString(locale, ...)` a real hydration-mismatch risk in
// SSR — this avoids that class of bug entirely by never depending on the
// runtime's locale support.

const WEEKDAYS_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS_EN = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

function dateParts(iso: string) {
  const d = new Date(`${iso}T00:00:00`);
  return {
    year: d.getFullYear(),
    month: d.getMonth(),
    day: d.getDate(),
    weekday: d.getDay(),
  };
}

// "May 10, 2025" (en) / "2025.05.10" (mn)
export function formatDate(iso: string, isEn: boolean): string {
  const { year, month, day } = dateParts(iso);
  if (isEn) return `${MONTHS_EN[month]} ${day}, ${year}`;
  return `${year}.${String(month + 1).padStart(2, "0")}.${String(day).padStart(
    2,
    "0"
  )}`;
}

// "Sat, May 10, 2025" (en) / "2025.05.10" (mn)
export function formatDateWithWeekday(iso: string, isEn: boolean): string {
  if (!isEn) return formatDate(iso, isEn);
  const { weekday } = dateParts(iso);
  return `${WEEKDAYS_EN[weekday]}, ${formatDate(iso, isEn)}`;
}
