import { useEffect, useRef } from "react";

const DEFAULT_TITLE = "Chrysopedia";

/**
 * Sets `document.title` to the given value. Resets to the default
 * title on unmount so navigating away doesn't leave a stale tab name.
 */
export function useDocumentTitle(title: string): void {
  const prevTitle = useRef(document.title);

  useEffect(() => {
    document.title = title || DEFAULT_TITLE;
  }, [title]);

  useEffect(() => {
    const fallback = prevTitle.current;
    return () => {
      document.title = fallback || DEFAULT_TITLE;
    };
  }, []);
}
