import { useRef, useEffect, useCallback } from 'react';
import { S as SCROLL_BUFFER } from './consts-44eaef6b.js';

function useDebounce(callback, delay) {
  const timeoutRef = useRef(null);
  useEffect(() => {
    // Cleanup the timeout on unmount
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);
  function debounceFunction() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    timeoutRef.current = setTimeout(() => {
      callback(...args);
    }, delay);
  }
  return debounceFunction;
}

const DELAY = 500;
function calcScrollBottom(scrollHeight, scrollTop) {
  return scrollHeight - scrollTop;
}
function useHandleOnScrollCallback(_ref) {
  let {
    hasMore,
    hasNext,
    onScroll,
    scrollRef,
    setShowScrollDownButton
  } = _ref;
  const scrollCb = useCallback(() => {
    const element = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (element == null) {
      return;
    }
    const {
      scrollTop,
      scrollHeight,
      clientHeight
    } = element;
    // https://sendbird.atlassian.net/browse/SBISSUE-11759
    // the edge case where channel is inside a page that already has scroll
    // scrollintoView will move the whole page, which we dont want
    const scrollBottom = calcScrollBottom(scrollHeight, scrollTop);
    // even if there is more to fetch or not,
    // we still have to show the scroll to bottom button
    if (typeof setShowScrollDownButton === 'function') {
      setShowScrollDownButton(scrollHeight > scrollTop + clientHeight + 1);
    }
    if (hasMore && scrollTop < SCROLL_BUFFER) {
      onScroll(() => {
        // sets the scroll position to the bottom of the new messages
        element.scrollTop = element.scrollHeight - scrollBottom;
      });
    }
    if (hasNext) {
      onScroll(() => {
        // sets the scroll position to the top of the new messages
        element.scrollTop = scrollTop - (scrollHeight - element.scrollHeight);
      });
    }
  }, [setShowScrollDownButton, hasMore, onScroll, scrollRef]);
  return useDebounce(scrollCb, DELAY);
}

export { useHandleOnScrollCallback as a, useDebounce as u };
//# sourceMappingURL=index-3461216d.js.map
