const TZ = "America/New_York";

export const money = (n: number | string | null | undefined, currency = "USD") => {
  const v = Number(n ?? 0);
  try {
    return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(v);
  } catch {
    return `${currency} ${v.toFixed(2)}`;
  }
};

/**
 * Format a date for display in Eastern Time (America/New_York).
 *
 * - Date-only strings like "2026-05-29" are parsed as LOCAL midnight
 *   (not UTC midnight) to avoid the off-by-one day bug in timezones
 *   west of UTC.
 * - Date+time strings and Date objects are converted to Eastern Time.
 */
export const fmtDate = (d: string | Date | null | undefined): string => {
  if (!d) return "—";

  // Date-only string (YYYY-MM-DD) — create as local date, no UTC conversion
  if (typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d.trim())) {
    const [y, m, day] = d.trim().split("-").map(Number);
    const local = new Date(y, m - 1, day); // local midnight — stays on correct day
    return local.toLocaleDateString("en-US", { timeZone: TZ, month: "numeric", day: "numeric", year: "numeric" });
  }

  // Datetime strings (ISO 8601) or Date objects — use Eastern Time explicitly
  const dt = typeof d === "string" ? new Date(d) : d;
  if (isNaN(dt.getTime())) return "—";
  return dt.toLocaleDateString("en-US", { timeZone: TZ, month: "numeric", day: "numeric", year: "numeric" });
};

/**
 * Format a datetime for display (date + time) in Eastern Time.
 */
export const fmtDateTime = (d: string | Date | null | undefined): string => {
  if (!d) return "—";
  const dt = typeof d === "string" ? new Date(d) : d;
  if (isNaN(dt.getTime())) return "—";
  return dt.toLocaleString("en-US", {
    timeZone: TZ,
    month: "numeric", day: "numeric", year: "numeric",
    hour: "numeric", minute: "2-digit",
  });
};

/**
 * Today's date string in YYYY-MM-DD in Eastern Time.
 */
export const todayET = (): string => {
  return new Date().toLocaleDateString("en-CA", { timeZone: TZ }); // en-CA gives YYYY-MM-DD
};

/**
 * Start of the current fiscal year (Jan 1) in Eastern Time.
 */
export const startOfYearET = (): string => {
  const year = new Date().toLocaleDateString("en-US", { timeZone: TZ, year: "numeric" });
  return `${year}-01-01`;
};
