import { usePathname } from 'next/navigation';
import { useEffect } from 'react';

const scrollToHash = () => {
  const hash = window.location.hash.slice(1);
  if (hash) {
    const targetElement = document.getElementById(hash);
    if (targetElement) {
      targetElement.scrollIntoView({ behavior: 'smooth' });
    }
  }
};

export const useScrollToSection = () => {
  const pathname = usePathname();

  useEffect(() => {
    if (typeof window === 'undefined') return;

    // Initial scroll on mount - timeout ensures DOM is ready
    const timeoutId = setTimeout(scrollToHash, 500);

    const handleHashChange = () => scrollToHash();
    window.addEventListener('hashchange', handleHashChange);

    return () => {
      clearTimeout(timeoutId);
      window.removeEventListener('hashchange', handleHashChange);
    };
  }, [pathname]);
};
