"use client";

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

export function useScrollToHash() {
    const pathname = usePathname();

    const scrollToHash = useCallback(() => {
        const hash = window.location.hash;
        if (hash) {
            setTimeout(() => {
                const elementId = hash.substring(1);
                const element = document.getElementById(elementId);
                if (element) {
                    const yOffset = -100; // Adjust this value as needed
                    const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
                    window.scrollTo({ top: y, behavior: "smooth" });
                }
            }, 0);
        }
    }, []);

    useEffect(() => {
        if (window.location.hash) {
            scrollToHash();
        }
    }, [pathname, scrollToHash]);

    useEffect(() => {
        window.addEventListener("hashchange", scrollToHash);
        return () => window.removeEventListener("hashchange", scrollToHash);
    }, [scrollToHash]);
}
