import { useCallback, useEffect, useState } from 'react';

function readHash(defaultId: string): string {
  const hash = window.location.hash.slice(1); // strip leading '#'
  return hash || defaultId;
}

export function useHashTab(defaultId: string): [string, (id: string) => void] {
  const [activeId, setActiveId] = useState<string>(() => readHash(defaultId));

  useEffect(() => {
    function onHashChange() {
      setActiveId(readHash(defaultId));
    }
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, [defaultId]);

  const navigate = useCallback((id: string) => {
    // replaceState: no history entry (Back button unaffected), no anchor-jump scroll
    history.replaceState(null, '', '#' + id);
    setActiveId(id);
  }, []);

  return [activeId, navigate];
}
