// ui/pager.jsx — pagination strip.
/* ------------------------------------------------------------- pagination */
// Build the page-number strip with leading/trailing ellipses, e.g. 1 … 5 6 7 … 42.
function pageStrip(cur, total) {
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
  const out = [1];
  if (cur > 3) out.push("…");
  for (let i = Math.max(2, cur - 1); i <= Math.min(total - 1, cur + 1); i++) out.push(i);
  if (cur < total - 2) out.push("…");
  out.push(total);
  return out;
}

// The pager under a long list — the ledger, a component's matched CVEs, its SBOM
// inventory. `total` is the size of the WHOLE result set, not of the current page.
// Renders nothing while the rows fit on one page, so callers drop it in
// unconditionally rather than repeating the "is it worth showing" test.
// `label` opts the strip in as a named navigation landmark, with each number button
// named "Page N" and the current one marked aria-current. A page that carries two
// pagers passes one each, so a screen reader moving between them by landmark can
// tell which list it is about to page. Callers that pass no label (the ledger, the
// SBOM wizard review) keep exactly the markup they had.
function Pager({ page, total, pageSize, onPage, label }) {
  if (total <= pageSize) return null;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  return (
    <div className="pager" role={label ? "navigation" : undefined} aria-label={label}>
      <span className="pager-info">
        Showing {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total}
      </span>
      <div className="pager-ctrls">
        <button className="pager-btn" disabled={page <= 1} onClick={() => onPage(Math.max(1, page - 1))}>
          <Icon name="arrowL" size={14} />Prev
        </button>
        {pageStrip(page, totalPages).map((p, i) =>
          p === "…"
            ? <span key={"e" + i} className="pager-ellip">…</span>
            : <button key={p} className={"pager-num" + (p === page ? " is-on" : "")} onClick={() => onPage(p)}
                aria-label={label ? "Page " + p : undefined} aria-current={label && p === page ? "page" : undefined}>{p}</button>
        )}
        <button className="pager-btn" disabled={page >= totalPages} onClick={() => onPage(Math.min(totalPages, page + 1))}>
          Next<Icon name="arrowR" size={14} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { Pager });
