/*
|--------------------------------------------------------------------------
| One date format for the whole app: MM/DD/YYYY (e.g. 10/25/2026)
|--------------------------------------------------------------------------
| Matches what the browser's date inputs show. Accepts the shapes the app and
| the backend produce — "YYYY-MM-DD", full ISO timestamps, "DD/MM/YYYY"-free
| "MM/DD/YYYY" (returned unchanged) — and returns anything else untouched, so a
| value it can't read is never lost.
*/

const pad = (n: number) => String(n).padStart(2, "0");

export function formatDateMDY(value: unknown): string {
  if (value === null || value === undefined) return "";

  if (value instanceof Date) {
    return Number.isNaN(value.getTime())
      ? ""
      : `${pad(value.getMonth() + 1)}/${pad(value.getDate())}/${value.getFullYear()}`;
  }

  const text = String(value).trim();

  if (!text) return "";

  // Already MM/DD/YYYY.
  if (/^\d{2}\/\d{2}\/\d{4}$/.test(text)) return text;

  // "YYYY-MM-DD" or an ISO timestamp starting with one.
  const iso = text.match(/^(\d{4})-(\d{2})-(\d{2})(?:[T\s].*)?$/);

  if (iso) return `${iso[2]}/${iso[3]}/${iso[1]}`;

  // Other date-looking text ("25 Oct 2026", "October 8, 2026"): reformat when it
  // parses; plain words and bare numbers are left alone.
  if (/\d{1,4}[-/ ,]+[A-Za-z0-9]+[-/ ,]+\d{1,4}/.test(text)) {
    const parsed = new Date(text.replace(" ", "T"));

    if (!Number.isNaN(parsed.getTime())) return formatDateMDY(parsed);
  }

  return text;
}

// The inverse, for code that needs the machine format back (kundli generation,
// date inputs): "MM/DD/YYYY" → "YYYY-MM-DD". Anything else is returned as is.
export function toISODate(value: unknown): string {
  const text = String(value ?? "").trim();

  const mdy = text.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

  return mdy ? `${mdy[3]}-${mdy[1]}-${mdy[2]}` : text;
}
