import { useEffect } from "react";
import { useLocation } from "react-router-dom";

/**
 * Scroll to the element whose `id` matches the URL hash. Retries for a short
 * window so it still lands on sections that mount after an async fetch (the app
 * has no router-level hash handling). Deep-link targets give a card an `id`.
 */
export function useScrollToHash(): void {
  const { hash } = useLocation();

  useEffect(() => {
    if (!hash) return;
    const id = decodeURIComponent(hash.slice(1));
    let tries = 0;
    let timer: ReturnType<typeof setTimeout>;

    const tick = () => {
      const el = document.getElementById(id);
      if (el) {
        el.scrollIntoView({ behavior: "smooth", block: "start" });
        return;
      }
      if (tries++ < 20) timer = setTimeout(tick, 100);
    };

    timer = setTimeout(tick, 100);
    return () => clearTimeout(timer);
  }, [hash]);
}
