/**
 * Format an ISO date string into a human-readable locale date.
 * Returns an empty string (or "—" when `dash` is true) for missing/invalid values.
 * Date-only ISO strings (e.g. "2025-03-15T00:00:00.000Z") are interpreted as
 * calendar dates to avoid off-by-one errors west of UTC.
 */
export function formatDate(
  dateStr?: string | null,
  opts: { dash?: boolean } = { dash: true },
): string {
  const fallback = opts.dash ? "—" : "";
  if (!dateStr) return fallback;
  try {
    // Strip time portion for date-only fields to prevent timezone shift
    const dateOnly = dateStr.split("T")[0];
    const date = new Date(dateOnly + "T00:00:00");
    if (isNaN(date.getTime())) return fallback;
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  } catch {
    return fallback;
  }
}

/**
 * Compute a list of page numbers (with "..." ellipsis) for a pagination control.
 * Always includes page 1 and the last page; collapses distant pages into ellipsis.
 */
export function getPageNumbers(
  current: number,
  total: number,
): (number | "...")[] {
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);

  const pages: (number | "...")[] = [1];
  if (current > 3) pages.push("...");

  const start = Math.max(2, current - 1);
  const end = Math.min(total - 1, current + 1);
  for (let i = start; i <= end; i++) pages.push(i);

  if (current < total - 2) pages.push("...");
  pages.push(total);
  return pages;
}
