/**
 * Parse a date string safely, anchoring date-only strings to noon local
 * to prevent timezone shifts that cause off-by-one-day errors.
 */
export function parseLocalDate(dateStr: string): Date {
  if (!dateStr) return new Date();
  if (typeof dateStr === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
    return new Date(dateStr + "T12:00:00");
  }
  return new Date(dateStr);
}

/**
 * Get today's date as YYYY-MM-DD in local timezone (not UTC).
 */
export function todayLocal(): string {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, "0");
  const d = String(now.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

/**
 * Safely format a date value to a readable string (MMM dd, yyyy).
 * Handles strings, Date objects, null/undefined gracefully.
 */
export function formatDateSafe(value: string | Date | null | undefined, fallback = "—"): string {
  if (!value) return fallback;
  try {
    const d = typeof value === "string" ? parseLocalDate(value) : value;
    if (isNaN(d.getTime())) return fallback;
    const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    return `${months[d.getMonth()]} ${String(d.getDate()).padStart(2,"0")}, ${d.getFullYear()}`;
  } catch {
    return fallback;
  }
}
