"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useIntersectionEffect = void 0;
var react_1 = require("react");
var getTarget = function (targetRef, root) {
    if ('current' in targetRef) {
        return targetRef.current;
    }
    else if (typeof targetRef === 'function') {
        return targetRef(root);
    }
    else {
        return targetRef;
    }
};
exports.useIntersectionEffect = function (rootRef, targetRef, options, fn) {
    var effectFn = react_1.useRef();
    effectFn.current = fn;
    var _a = options !== null && options !== void 0 ? options : {}, rootMargin = _a.rootMargin, threshold = _a.threshold;
    react_1.useLayoutEffect(function () {
        if (!window.IntersectionObserver)
            return undefined;
        var target = (rootRef === null || rootRef === void 0 ? void 0 : rootRef.current) ? getTarget(targetRef, rootRef === null || rootRef === void 0 ? void 0 : rootRef.current)
            : getTarget(targetRef, rootRef === null || rootRef === void 0 ? void 0 : rootRef.current);
        if (target) {
            var observer_1 = new window.IntersectionObserver(function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return effectFn.current.apply(effectFn, args);
            }, //TODO not sure why args have to be passed in explicitly
            { root: rootRef === null || rootRef === void 0 ? void 0 : rootRef.current, rootMargin: rootMargin, threshold: threshold });
            observer_1.observe(target);
            return function () { return observer_1.unobserve(target); };
        }
        return undefined;
    }, [rootRef, targetRef, rootMargin, threshold]);
};
