import { formatNumber } from "../../../../lib/number-utils";

export type TranslationPaginationItem = number | "ellipsis";

export function getTranslationPaginationItems(
  page: number,
  totalPages: number,
): TranslationPaginationItem[] {
  const total = Math.max(1, Math.floor(totalPages));
  const current = Math.min(total, Math.max(1, Math.floor(page)));
  const visible = new Set([1, total]);

  for (let index = Math.max(1, current - 1); index <= Math.min(total, current + 1); index += 1) {
    visible.add(index);
  }
  if (current <= 3) {
    visible.add(2);
    visible.add(3);
  }
  if (current >= total - 2) {
    visible.add(total - 1);
    visible.add(total - 2);
  }

  const pages = [...visible].filter(index => index >= 1 && index <= total).sort((a, b) => a - b);
  const items: TranslationPaginationItem[] = [];
  for (const value of pages) {
    const previous = items.at(-1);
    if (typeof previous === "number" && value - previous === 2) {
      items.push(previous + 1);
    } else if (typeof previous === "number" && value - previous > 2) {
      items.push("ellipsis");
    }
    items.push(value);
  }
  return items;
}

export function formatTranslationPageNumber(page: number, locale: "en" | "km") {
  // Explicit digit conversion produces identical SSR and browser output,
  // even when their Intl implementations support different numbering systems.
  return formatNumber(page, locale);
}
