import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
var EMPTY_SET = new Set();
var HIGHLIGHT_DURATION_MS = 2000;
export var ScrollToAddedAttributeContext = React.createContext({
    highlightedIds: EMPTY_SET,
    highlight: function () { },
    scrollToFirst: function () { }
});
export var ScrollToAddedAttributeProvider = function (_a) {
    var children = _a.children;
    var _b = useState(EMPTY_SET), highlightedIds = _b[0], setHighlightedIds = _b[1];
    var highlightTimer = useRef(null);
    var highlightDelay = useRef(null);
    var bestScrollTarget = useRef(null);
    var scrollRafId = useRef(0);
    var highlight = useCallback(function (addedIds) {
        if (addedIds.length === 0)
            return;
        bestScrollTarget.current = null;
        clearTimeout(highlightTimer.current);
        clearTimeout(highlightDelay.current);
        highlightDelay.current = setTimeout(function () {
            setHighlightedIds(new Set(addedIds));
            highlightTimer.current = setTimeout(function () { return setHighlightedIds(EMPTY_SET); }, HIGHLIGHT_DURATION_MS);
        }, 300);
    }, []);
    var scrollToFirst = useCallback(function (ref) {
        if (!ref.current)
            return;
        var el = ref.current;
        if (!bestScrollTarget.current ||
            el.getBoundingClientRect().top < bestScrollTarget.current.getBoundingClientRect().top) {
            bestScrollTarget.current = el;
        }
        cancelAnimationFrame(scrollRafId.current);
        scrollRafId.current = requestAnimationFrame(function () {
            var _a, _b;
            (_b = (_a = bestScrollTarget.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView) === null || _b === void 0 ? void 0 : _b.call(_a, { behavior: 'smooth', block: 'center' });
            bestScrollTarget.current = null;
        });
    }, []);
    useEffect(function () {
        return function () {
            clearTimeout(highlightTimer.current);
            clearTimeout(highlightDelay.current);
            cancelAnimationFrame(scrollRafId.current);
        };
    }, []);
    var value = useMemo(function () { return ({ highlightedIds: highlightedIds, highlight: highlight, scrollToFirst: scrollToFirst }); }, [highlightedIds, highlight, scrollToFirst]);
    return React.createElement(ScrollToAddedAttributeContext.Provider, { value: value }, children);
};
