import { useEffect, RefObject } from 'react';
import { useLocation } from 'react-router-dom';

/**
 * Hook to scroll to top on route changes
 * Should be used in layout components to ensure scroll restoration
 * works consistently across all routes
 *
 * @param containerRef - Optional ref to a scrollable container element.
 *                       If provided, scrolls that element instead of window.
 */
export function useScrollToTop(containerRef?: RefObject<HTMLElement | null>) {
  const { pathname } = useLocation();

  useEffect(() => {
    if (containerRef?.current) {
      containerRef.current.scrollTo(0, 0);
    } else {
      window.scrollTo(0, 0);
    }
  }, [pathname, containerRef]);
}
