import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import { useRef, useState, useCallback, useLayoutEffect } from 'react';

const useSnapScroll = (itemDistance, size) => {
  const ref = useRef(null);
  const [isLeftDisabled, setLeftDisabled] = useState(true);
  const [isRightDisabled, setRightDisabled] = useState(false);
  const [showScrollButtons, setShowScrollButtons] = useState(true);
  const onResizeHandler = useCallback(() => {
    if (ref.current) {
      const {
        scrollWidth,
        clientWidth
      } = ref.current;
      if (typeof scrollWidth !== 'undefined' && typeof clientWidth !== 'undefined') {
        const hasOverflown = scrollWidth > clientWidth;
        setShowScrollButtons(hasOverflown);
      }
    }
  }, []);
  useLayoutEffect(() => {
    onResizeHandler();
  }, [size, onResizeHandler]);
  const moveLeft = () => {
    var _a;
    (_a = ref.current) === null || _a === void 0 ? void 0 : _a.scrollBy({
      left: -itemDistance,
      behavior: 'smooth'
    });
  };
  const moveRight = () => {
    var _a;
    (_a = ref.current) === null || _a === void 0 ? void 0 : _a.scrollBy({
      left: itemDistance,
      behavior: 'smooth'
    });
  };
  const onScrollHandler = useCallback(e => {
    if (e.currentTarget) {
      const {
        scrollLeft,
        scrollWidth,
        clientWidth
      } = e.currentTarget;
      // Left
      if (scrollLeft === 0) {
        setLeftDisabled(true);
      } else {
        setLeftDisabled(false);
      }
      // Right
      if (scrollWidth - scrollLeft <= clientWidth) {
        setRightDisabled(true);
      } else {
        setRightDisabled(false);
      }
    }
  }, []);
  return {
    ref,
    isLeftDisabled,
    isRightDisabled,
    showScrollButtons,
    moveLeft,
    moveRight,
    onScrollHandler,
    onResizeHandler
  };
};

export { useSnapScroll };
