'use client';

import { useEffect } from 'react';

import { usePathname } from '@/i18n/navigation';

export default function ScrollRestorer() {
  const pathname = usePathname();

  useEffect(() => {
    const handleScroll = () => {
      sessionStorage.setItem(`scrollY:${pathname}`, String(window.scrollY));
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [pathname]);

  useEffect(() => {
    const saved = Number(sessionStorage.getItem(`scrollY:${pathname}`));
    if (saved) {
      setTimeout(() => window.scrollTo(0, saved), 400);
    }
  }, [pathname]);

  return null;
}

// "use client";

// import { usePathname } from "@/i18n/navigation";
// import { useEffect } from "react";
// import { VirtuosoHandle } from "react-virtuoso";

// interface ScrollRestorerProps {
//   virtuosoRef?: React.RefObject<VirtuosoHandle>;
// }

// const ScrollRestorer: React.FC<ScrollRestorerProps> = ({ virtuosoRef }) => {
//   const pathname = usePathname();
//   const isAlkotasok = pathname.startsWith("/alkotasok");

//   useEffect(() => {
//     const handleScroll = () => {
//       if (isAlkotasok && virtuosoRef?.current) {
//         const index = virtuosoRef.current.getState().firstItemIndex;
//         sessionStorage.setItem(`virtuosoIndex:${pathname}`, String(index));
//       } else {
//         sessionStorage.setItem(`scrollY:${pathname}`, String(window.scrollY));
//       }
//     };
//     window.addEventListener("scroll", handleScroll);
//     return () => window.removeEventListener("scroll", handleScroll);
//   }, [pathname, isAlkotasok, virtuosoRef]);

//   useEffect(() => {
//     if (isAlkotasok && virtuosoRef?.current) {
//       const saved = Number(sessionStorage.getItem(`virtuosoIndex:${pathname}`));
//       if (saved) {
//         setTimeout(
//           () =>
//             virtuosoRef.current.scrollToIndex({ index: saved, align: "start" }),
//           400
//         );
//       }
//     } else {
//       const saved = Number(sessionStorage.getItem(`scrollY:${pathname}`));
//       if (saved) {
//         setTimeout(() => window.scrollTo(0, saved), 400);
//       }
//     }
//   }, [pathname, isAlkotasok, virtuosoRef]);

//   return null;
// };

// export default ScrollRestorer;
