import { __assign } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import cx from 'classnames';
import { useCallback, useEffect, useState, forwardRef } from 'react';
import BlockLoading from '../loading/BlockLoading';
import { Waypoint } from '../waypoint';
import isBrowser from '../utils/isBrowser';
import { useMounted } from '../utils/hooks/useMounted';
var DEFAULT_LOADER = _jsx(BlockLoading, { height: 60, loading: true, icon: "circle" }, void 0);
export var InfiniteScroller = forwardRef(function (_a, ref) {
    var _b;
    var _c = _a.hasMore, hasMore = _c === void 0 ? false : _c, loadMore = _a.loadMore, _d = _a.skipLoadOnMount, skipLoadOnMount = _d === void 0 ? false : _d, _e = _a.useWindow, useWindow = _e === void 0 ? false : _e, _f = _a.loader, loader = _f === void 0 ? DEFAULT_LOADER : _f, _g = _a.threshold, threshold = _g === void 0 ? 1 : _g, className = _a.className, children = _a.children;
    var _h = useState(false), loading = _h[0], setLoading = _h[1];
    var mounted = useMounted();
    var stopLoading = useCallback(function () {
        if (mounted.current) {
            setLoading(false);
        }
    }, [mounted]);
    var load = useCallback(function () {
        if (typeof loadMore !== 'function') {
            return;
        }
        setLoading(true);
        if (loadMore.length > 0) {
            loadMore(stopLoading);
        }
        else {
            loadMore().then(stopLoading, stopLoading);
        }
    }, [loadMore, stopLoading]);
    var onEnter = useCallback(function (data) {
        if (loading) {
            return;
        }
        var previousPosition = data.previousPosition;
        if (previousPosition === 2) {
            load();
        }
    }, [load, loading]);
    useEffect(function () {
        if (!skipLoadOnMount) {
            load();
        }
    }, []);
    return (_jsxs("div", __assign({ className: cx("zent-infinite-scroller", className, (_b = {},
            _b["zent-infinite-scroller-y"] = !useWindow,
            _b)), ref: ref, "data-zv": 'v10.0.11' }, { children: [children, hasMore && isBrowser && (_jsx(Waypoint, { scrollableAncestor: useWindow ? window : undefined, onEnter: onEnter, bottomOffset: -threshold }, void 0)), loading && loader] }), void 0));
});
InfiniteScroller.displayName = 'InfiniteScroller';
export default InfiniteScroller;
