import Link from "next/link";

// Shared by the employee list and the audit log, which both used to render
// one link per page: 54 of them for ~800 employees, and an unbounded number
// for the audit log, all in a single overflowing row. This shows the first
// and last page plus a window around the current one, with the gaps elided.
const WINDOW = 2;

function pageItems(current: number, total: number): number[] {
  const pages = new Set<number>([1, total]);
  for (let p = current - WINDOW; p <= current + WINDOW; p++) {
    if (p >= 1 && p <= total) pages.add(p);
  }
  return [...pages].sort((a, b) => a - b);
}

type PaginationProps = {
  page: number;
  totalPages: number;
  hrefFor: (page: number) => string;
  /** Screen-reader name, e.g. "Mitarbeiter:innen" — several lists per app. */
  label: string;
};

export function Pagination({ page, totalPages, hrefFor, label }: PaginationProps) {
  if (totalPages <= 1) return null;

  const current = Math.min(Math.max(1, page), totalPages);
  const items = pageItems(current, totalPages);

  return (
    <nav aria-label={`Seiten – ${label}`} className="flex flex-wrap items-center justify-center gap-1 text-sm">
      {current > 1 && (
        <Link href={hrefFor(current - 1)} rel="prev" className="rounded px-3 py-1 font-semibold text-ink-body hover:bg-surface">
          Zurück
        </Link>
      )}
      {items.map((p, i) => (
        <span key={p} className="flex items-center gap-1">
          {i > 0 && p - items[i - 1] > 1 && <span className="px-1 text-ink-muted">…</span>}
          <Link
            href={hrefFor(p)}
            aria-current={p === current ? "page" : undefined}
            className={`rounded px-3 py-1 ${p === current ? "bg-brand-500 font-semibold text-white" : "text-ink-body hover:bg-surface"}`}
          >
            {p}
          </Link>
        </span>
      ))}
      {current < totalPages && (
        <Link href={hrefFor(current + 1)} rel="next" className="rounded px-3 py-1 font-semibold text-ink-body hover:bg-surface">
          Weiter
        </Link>
      )}
    </nav>
  );
}
