import { useContext, useEffect, useRef } from 'react';
import { ConfigContext } from '../../../ConfigProvider';
import { getNodeText } from '../../../utils/getNodeText';
export const usePageTitle = ({ shouldUpdateDocumentTitle, title, htmlTitle, }) => {
    const prevTitleRef = useRef(null);
    const { components } = useContext(ConfigContext);
    useEffect(() => {
        const isDynamicTitle = typeof shouldUpdateDocumentTitle === 'boolean'
            ? shouldUpdateDocumentTitle
            : components?.layout?.defaultProps?.shouldUpdateDocumentTitle;
        if (!isDynamicTitle) {
            return;
        }
        const newTitle = getNodeText(title);
        if (!newTitle && !htmlTitle) {
            // biome-ignore lint/suspicious/noConsole: Ошибка для интеграторов
            console.warn('@astral/ui:PageHeader: Не получилось определить заголовок страницы. Передайте htmlTitle.');
            return;
        }
        prevTitleRef.current = document.title;
        document.title = htmlTitle ?? newTitle;
        return () => {
            if (prevTitleRef.current !== null) {
                document.title = prevTitleRef.current;
            }
        };
    }, [
        shouldUpdateDocumentTitle,
        title,
        components?.layout?.defaultProps,
        htmlTitle,
    ]);
};
