import {useCallback, useEffect, useRef} from "@wordpress/element";

const clampProgress = (value) => Math.min(100, Math.max(0, Math.round(value)));

const useProgressDocumentTitle = () => {
    const originalTitleRef = useRef(null);

    const restoreTitle = useCallback(() => {
        if (typeof document === 'undefined') {
            return;
        }
        if (originalTitleRef.current) {
            document.title = originalTitleRef.current;
            originalTitleRef.current = null;
        }
    }, []);

    const updateTitle = useCallback((progressValue, formatter, options = {}) => {
        if (typeof document === 'undefined') {
            return;
        }

        const numericProgress = Number(progressValue);
        const shouldResetOnInvalid = options.resetOnInvalid !== false;

        if (!Number.isFinite(numericProgress) || numericProgress < 0) {
            if (shouldResetOnInvalid) {
                restoreTitle();
            }
            return;
        }

        if (!originalTitleRef.current) {
            originalTitleRef.current = document.title;
        }

        const clampedValue = clampProgress(numericProgress);
        const formattedTitle = typeof formatter === 'function'
            ? formatter(clampedValue, originalTitleRef.current)
            : `${clampedValue}% - ${originalTitleRef.current}`;

        if (formattedTitle) {
            document.title = formattedTitle;
        }
    }, [restoreTitle]);

    useEffect(() => {
        return () => {
            restoreTitle();
        };
    }, [restoreTitle]);

    return {
        updateTitle,
        restoreTitle,
    };
};

export default useProgressDocumentTitle;