import { __read } from "tslib";
import * as React from "react";
var reducer = function (state, action) {
    switch (action) {
        case "hide":
            if (!state.active) {
                return state;
            }
            return {
                active: false,
                showTime: undefined,
            };
        case "show":
            if (state.active) {
                return state;
            }
            return {
                active: true,
                showTime: Date.now(),
            };
    }
    return state;
};
var createTimer = function (callback, timeout) {
    var timer = setTimeout(callback, timeout);
    return function () { return clearTimeout(timer); };
};
export var useDelayedActive = function (_a) {
    var active = _a.active, _b = _a.timeout, timeout = _b === void 0 ? 600 : _b, _c = _a.minimumActiveTime, minimumActiveTime = _c === void 0 ? 1000 : _c, delayInitialActive = _a.delayInitialActive;
    var _d = __read(React.useReducer(reducer, {
        active: delayInitialActive ? false : active,
        showTime: Date.now(),
    }), 2), state = _d[0], dispatch = _d[1];
    React.useEffect(function () {
        if (state.active === active) {
            return active ? dispatch("show") : dispatch("hide");
        }
        if (!active) {
            var diff = Date.now() - state.showTime;
            if (minimumActiveTime === undefined || diff > minimumActiveTime) {
                dispatch("hide");
                return;
            }
            return createTimer(function () { return dispatch("hide"); }, minimumActiveTime - diff);
        }
        return createTimer(function () { return dispatch("show"); }, timeout);
    }, [active]);
    return state.active;
};
var DelayedActive = function (props) {
    var active = useDelayedActive(props);
    return props.children(active);
};
DelayedActive.displayName = "DelayedActive";
export default DelayedActive;
