"use client";

import { useLayoutEffect, useMemo, useRef } from "react";
import { usePathname } from "next/navigation";
import {
  buildListScrollKey,
  consumeListScroll,
} from "@/lib/listScrollRestoration";

export function useListScrollRestoration(
  scope: string,
  filters?: Record<string, unknown>,
  ready = true
): string {
  const pathname = usePathname();
  const scrollKey = useMemo(
    () => buildListScrollKey(scope, filters),
    [scope, filters]
  );
  const restoredRef = useRef(false);

  useLayoutEffect(() => {
    restoredRef.current = false;
  }, [scrollKey]);

  useLayoutEffect(() => {
    if (!ready || restoredRef.current) return;
    const y = consumeListScroll(scrollKey);
    if (y != null && y > 0) {
      window.scrollTo(0, y);
    }
    restoredRef.current = true;
  }, [scrollKey, ready, pathname]);

  return scrollKey;
}
