import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";

const PREFIX = "modstagram-list-scroll";

export function buildListScrollKey(
  scope: string,
  filters?: Record<string, unknown>
): string {
  const filterPart = filters ? JSON.stringify(filters) : "";
  return `${PREFIX}:${scope}:${filterPart}`;
}

export function saveListScroll(key: string): void {
  if (typeof window === "undefined") return;
  sessionStorage.setItem(key, String(window.scrollY));
}

export function peekListScroll(key: string): number | null {
  if (typeof window === "undefined") return null;
  const raw = sessionStorage.getItem(key);
  if (raw == null) return null;
  const y = Number.parseInt(raw, 10);
  return Number.isFinite(y) ? y : null;
}

export function consumeListScroll(key: string): number | null {
  if (typeof window === "undefined") return null;
  const y = peekListScroll(key);
  if (y != null) sessionStorage.removeItem(key);
  return y;
}

export function navigateWithSavedScroll(
  router: AppRouterInstance,
  key: string,
  url: string
): void {
  saveListScroll(key);
  router.push(url, { scroll: false });
}

export function initManualScrollRestoration(): void {
  if (typeof window === "undefined") return;
  if ("scrollRestoration" in window.history) {
    window.history.scrollRestoration = "manual";
  }
}
