export function formatDate(
  date: Date | string | number | undefined,
  opts: Intl.DateTimeFormatOptions = {}
) {
  if (!date) return '';

  try {
    return new Intl.DateTimeFormat('en-US', {
      month: opts.month ?? 'long',
      day: opts.day ?? 'numeric',
      year: opts.year ?? 'numeric',
      ...opts
    }).format(new Date(date));
  } catch {
    return '';
  }
}

export function formatDateTime(
  date: Date | string | number | undefined,
  opts: Intl.DateTimeFormatOptions = {}
) {
  if (!date) return '';

  try {
    return new Intl.DateTimeFormat('th-TH-u-ca-gregory-nu-latn', {
      day: opts.day ?? '2-digit',
      month: opts.month ?? '2-digit',
      year: opts.year ?? 'numeric',
      hour: opts.hour ?? '2-digit',
      minute: opts.minute ?? '2-digit',
      second: opts.second ?? '2-digit',
      hour12: opts.hour12 ?? false,
      timeZone: opts.timeZone ?? 'Asia/Bangkok',
      ...opts
    }).format(new Date(date));
  } catch {
    return '';
  }
}

/**
 * Formats a date to YYYY-MM-DD format (ISO date).
 * This is used to prevent hydration mismatches between server and client.
 */
export function formatDateIso(date: Date | string | number | undefined): string {
  if (!date) return '';

  try {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch {
    return '';
  }
}
