/** 列表分頁（page 從 1 起） */

export function pageCount(total: number, pageSize: number): number {
  const size = Math.max(1, pageSize || 10);
  return Math.max(1, Math.ceil(Math.max(0, total) / size) || 1);
}

export function clampPage(page: number, totalPages: number): number {
  return Math.max(1, Math.min(Math.max(1, totalPages), page || 1));
}

export function pageSlice<T>(list: T[], page: number, pageSize: number): T[] {
  const size = Math.max(1, pageSize || 10);
  const pages = pageCount(list.length, size);
  const p = clampPage(page, pages);
  const start = (p - 1) * size;
  return list.slice(start, start + size);
}

export function pageRangeLabel(page: number, pageSize: number, total: number): string {
  if (total <= 0) return "0";
  const size = Math.max(1, pageSize || 10);
  const pages = pageCount(total, size);
  const p = clampPage(page, pages);
  const from = (p - 1) * size + 1;
  const to = Math.min(p * size, total);
  return `${from}–${to} / ${total}`;
}

export const DEFAULT_PAGE_SIZES = [5, 10, 20, 50] as const;
