import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
export function useScrollToLocation() {
  const scrolledRef = React.useRef(false);
  const navigate = useNavigate();
  const { hash } = useLocation();
  const hashRef = React.useRef(hash);

  React.useEffect(() => {
    if (!hash) return;
    if (hashRef.current !== hash) {
      hashRef.current = hash;
      scrolledRef.current = false;
    }
    navigate();
    if (scrolledRef.current) return;
    const id = hash.replace("#", "");
    const element = document.getElementById(id);
    if (!element) return;
    element.scrollIntoView({ behavior: "smooth", block: "start" });
    scrolledRef.current = true;
  });
}
