// Per-page selector: remembers the chosen page size in localStorage and keeps
// the URL's `per` query param in sync. CSP-safe (external file, no inline JS).
(function () {
  const select = document.querySelector("[data-per-page]");
  if (!select) {
    return;
  }

  const key = "warpbox-perpage-" + select.dataset.perPage;
  const url = new URL(window.location.href);
  const current = url.searchParams.get("per");
  let stored = null;
  try {
    stored = window.localStorage.getItem(key);
  } catch (err) {
    stored = null;
  }

  // No explicit choice in the URL but a remembered preference exists: apply it.
  if (!current && stored && stored !== select.value) {
    const valid = Array.prototype.some.call(select.options, function (opt) {
      return opt.value === stored;
    });
    if (valid) {
      url.searchParams.set("per", stored);
      url.searchParams.delete("page");
      window.location.replace(url.toString());
      return;
    }
  }

  select.addEventListener("change", function () {
    try {
      window.localStorage.setItem(key, select.value);
    } catch (err) {
      /* ignore storage failures (private mode, etc.) */
    }
    const next = new URL(window.location.href);
    next.searchParams.set("per", select.value);
    next.searchParams.delete("page");
    window.location.assign(next.toString());
  });
})();
