"use client";

import { useEffect } from "react";
import { useSearchParams, usePathname } from "next/navigation";

export function usePersistentScroll(namespace: string) {
  const searchParams = useSearchParams();
  const pathname = usePathname();

  // Unique key per page + filter state
  const scrollKey = `${namespace}_scroll_${pathname}`;

  // ✅ Restore scroll on mount / filter change
  useEffect(() => {
  if (typeof window === "undefined") return;

  const savedScroll = sessionStorage.getItem(scrollKey);
  if (!savedScroll) return;

  const scrollPosition = parseInt(savedScroll, 10);

  const restoreScroll = () => {
    if (document.body.scrollHeight >= scrollPosition) {
      window.scrollTo(0, scrollPosition);
    } else {
      requestAnimationFrame(restoreScroll);
    }
  };

  restoreScroll();
}, [scrollKey]);

  // ✅ Persist scroll while scrolling
  useEffect(() => {
    if (typeof window === "undefined") return;

    const handleScroll = () => {
      sessionStorage.setItem(scrollKey, window.scrollY.toString());
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [scrollKey]);

  // Optional utility if you ever want to clear manually
  const clearScroll = () => {
    sessionStorage.removeItem(scrollKey);
  };

  return { clearScroll };
}
