'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _extends = require('@babel/runtime/helpers/extends');
var _taggedTemplateLiteral = require('@babel/runtime/helpers/taggedTemplateLiteral');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var React = require('react');
var Swipe = require('react-easy-swipe');
var classNames = require('clsx');
var Icon = require('@prom-ui/core/Icon');
var BodyProvider = require('@prom-ui/core/BodyProvider');
var Left = require('@prom-ui/icons/Left');
var Right = require('@prom-ui/icons/Right');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }

function _interopNamespaceCompat(e) {
    if (e && typeof e === 'object' && 'default' in e) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n.default = e;
    return Object.freeze(n);
}

var _extends__default = /*#__PURE__*/_interopDefaultCompat(_extends);
var _taggedTemplateLiteral__default = /*#__PURE__*/_interopDefaultCompat(_taggedTemplateLiteral);
var _defineProperty__default = /*#__PURE__*/_interopDefaultCompat(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultCompat(_slicedToArray);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefaultCompat(_objectWithoutProperties);
var React__namespace = /*#__PURE__*/_interopNamespaceCompat(React);
var Swipe__default = /*#__PURE__*/_interopDefaultCompat(Swipe);
var classNames__default = /*#__PURE__*/_interopDefaultCompat(classNames);

var useAutoPlay = function useAutoPlay(callback, delay) {
  var timeout = React.useRef(null);
  var stop = function stop() {
    if (timeout.current) {
      clearTimeout(timeout.current);
    }
  };
  var start = function start() {
    stop();
    timeout.current = setTimeout(callback, delay);
  };
  return [start, stop];
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var isValidRatio = function isValidRatio(ratio) {
  return !!ratio && /\d\/\d/.test(ratio);
};
var getInfiniteIndex = function getInfiniteIndex(index, count) {
  return Math.abs((index % count + count) % count);
};
var getRatioHolderStyle = function getRatioHolderStyle(ratio) {
  return {
    paddingTop: "calc(".concat(ratio.split('/').reverse().join('/'), " * 100%)")
  };
};
var getRootStyle = function getRootStyle(_ref) {
  var width = _ref.width,
    height = _ref.height,
    ratio = _ref.ratio,
    style = _ref.style;
  var hasRatio = isValidRatio(ratio);
  return _objectSpread({
    width: width,
    height: hasRatio ? 'auto' : height,
    maxWidth: hasRatio ? '100%' : 'none',
    aspectRatio: hasRatio ? ratio : undefined
  }, style);
};
var getTrackStyle = function getTrackStyle(_ref2) {
  var index = _ref2.index,
    childrenCount = _ref2.childrenCount,
    duration = _ref2.duration,
    offset = _ref2.offset;
  var hasOffset = typeof offset === 'number';
  var currentOffset = hasOffset ? offset : 0;
  return {
    transform: "translateX(calc(".concat(index * (100 / childrenCount) * -1, "% + ").concat(currentOffset, "px))"),
    transition: hasOffset ? undefined : "transform ".concat(duration, "ms ease"),
    width: "".concat(childrenCount * 100, "%")
    // willChange: 'transform',
  };
};

var css = {"root":"SimpleSlider__root___bXdCd","track":"SimpleSlider__track___igqgQ","trackItem":"SimpleSlider__trackItem___7TgGX","resetButton":"SimpleSlider__resetButton___gHpEr","buttonCommon":"SimpleSlider__buttonCommon___cQvz3 SimpleSlider__resetButton___gHpEr","buttonPrev":"SimpleSlider__buttonPrev___543BF SimpleSlider__buttonCommon___cQvz3 SimpleSlider__resetButton___gHpEr","buttonNext":"SimpleSlider__buttonNext___uU4Gw SimpleSlider__buttonCommon___cQvz3 SimpleSlider__resetButton___gHpEr","buttonIcon":"SimpleSlider__buttonIcon___LD9ov","dots":"SimpleSlider__dots___GA591","dotsTransparent":"SimpleSlider__dotsTransparent___fybKk","dotsItem":"SimpleSlider__dotsItem___d4JnV","dotsButton":"SimpleSlider__dotsButton___UPQSI SimpleSlider__resetButton___gHpEr","showOnHoverButtons":"SimpleSlider__showOnHoverButtons___0cn-k","showOnHoverDots":"SimpleSlider__showOnHoverDots___q4PLm"};

var _templateObject, _templateObject2, _templateObject3;
var _excluded = ["showIndex", "autoPlay", "children", "className", "duration", "height", "infinite", "ratio", "style", "width", "onChangeIndex", "onClickDot", "onClickItem", "onClickButtonNext", "onClickButtonPrev", "onSwipeNext", "onSwipePrev", "showOnHoverButtons", "showOnHoverDots", "isDotsTransparent"];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var SimpleSlider = /*#__PURE__*/React__namespace.forwardRef(function (_ref, ref) {
  var _ref$showIndex = _ref.showIndex,
    showIndex = _ref$showIndex === void 0 ? 0 : _ref$showIndex,
    _ref$autoPlay = _ref.autoPlay,
    autoPlay = _ref$autoPlay === void 0 ? 0 : _ref$autoPlay,
    children = _ref.children,
    className = _ref.className,
    _ref$duration = _ref.duration,
    duration = _ref$duration === void 0 ? 500 : _ref$duration,
    height = _ref.height,
    _ref$infinite = _ref.infinite,
    infinite = _ref$infinite === void 0 ? false : _ref$infinite,
    ratio = _ref.ratio,
    style = _ref.style,
    width = _ref.width,
    onChangeIndex = _ref.onChangeIndex,
    onClickDot = _ref.onClickDot,
    onClickItem = _ref.onClickItem,
    onClickButtonNext = _ref.onClickButtonNext,
    onClickButtonPrev = _ref.onClickButtonPrev,
    onSwipeNext = _ref.onSwipeNext,
    onSwipePrev = _ref.onSwipePrev,
    _ref$showOnHoverButto = _ref.showOnHoverButtons,
    showOnHoverButtons = _ref$showOnHoverButto === void 0 ? false : _ref$showOnHoverButto,
    _ref$showOnHoverDots = _ref.showOnHoverDots,
    showOnHoverDots = _ref$showOnHoverDots === void 0 ? false : _ref$showOnHoverDots,
    _ref$isDotsTransparen = _ref.isDotsTransparent,
    isDotsTransparent = _ref$isDotsTransparen === void 0 ? false : _ref$isDotsTransparen,
    props = _objectWithoutProperties__default.default(_ref, _excluded);
  var _useBodyStoreTTag = BodyProvider.useBodyStoreTTag(),
    t = _useBodyStoreTTag.t;
  var refTrack = React__namespace.useRef(null);
  var transitionRunning = React__namespace.useRef(false);
  var _React$useState = React__namespace.useState(false),
    _React$useState2 = _slicedToArray__default.default(_React$useState, 2),
    disableAutoPlay = _React$useState2[0],
    setDisableAutoPlay = _React$useState2[1];
  var _React$useState3 = React__namespace.useState({
      index: showIndex,
      offset: undefined
    }),
    _React$useState4 = _slicedToArray__default.default(_React$useState3, 2),
    position = _React$useState4[0],
    setPosition = _React$useState4[1];
  var childrenArray = React__namespace.Children.toArray(children);
  var childrenCount = childrenArray.length;
  var isDisablePrev = !infinite && position.index === 0;
  var isDisableNext = !infinite && position.index === childrenCount - 1;
  var isShowNavi = childrenCount > 1;
  var isShowDots = childrenCount > 1;
  var isAutoPlay = !disableAutoPlay && autoPlay > 0;
  var prevIndex = position.index - 1;
  var nextIndex = position.index + 1;
  var infiniteIndex = getInfiniteIndex(position.index, childrenCount);
  var infinitePrevIndex = getInfiniteIndex(prevIndex, childrenCount);
  var infiniteNextIndex = getInfiniteIndex(nextIndex, childrenCount);
  var handleClickButtonNext = function handleClickButtonNext() {
    if (transitionRunning.current || isDisableNext) return;
    if (typeof onClickButtonNext === 'function') {
      onClickButtonNext(infiniteNextIndex);
    }
    setPosition({
      index: nextIndex,
      offset: undefined
    });
  };
  var handleClickButtonPrev = function handleClickButtonPrev() {
    if (transitionRunning.current || isDisablePrev) return;
    if (typeof onClickButtonPrev === 'function') {
      onClickButtonPrev(infinitePrevIndex);
    }
    setPosition({
      index: prevIndex,
      offset: undefined
    });
  };
  var handleClickDot = function handleClickDot(i) {
    if (transitionRunning.current) return;
    if (typeof onClickDot === 'function') {
      onClickDot(i);
    }
    setPosition({
      index: i,
      offset: undefined
    });
  };
  var handleSwipeNext = function handleSwipeNext() {
    if (transitionRunning.current || isDisableNext) return;
    if (typeof onSwipeNext === 'function') {
      onSwipeNext(infiniteNextIndex);
    }
    setPosition({
      index: nextIndex,
      offset: undefined
    });
  };
  var handleSwipePrev = function handleSwipePrev() {
    if (transitionRunning.current || isDisablePrev) return;
    if (typeof onSwipePrev === 'function') {
      onSwipePrev(infinitePrevIndex);
    }
    setPosition({
      index: prevIndex,
      offset: undefined
    });
  };
  var handleSwipeMove = function handleSwipeMove(_ref2, event) {
    var x = _ref2.x;
    if (transitionRunning.current || event.touches && event.touches.length > 1) return;
    var offset = x;
    if (isDisablePrev && x > 0 || isDisableNext && x < 0) {
      offset = 0;
    }
    setPosition({
      index: position.index,
      offset: offset
    });
  };
  var _useAutoPlay = useAutoPlay(function () {
      if (transitionRunning.current || isDisableNext) return;
      setPosition({
        index: nextIndex,
        offset: undefined
      });
    }, autoPlay),
    _useAutoPlay2 = _slicedToArray__default.default(_useAutoPlay, 2),
    startAutoPlay = _useAutoPlay2[0],
    stopAutoPlay = _useAutoPlay2[1];
  var handleTransitionStart = function handleTransitionStart() {
    transitionRunning.current = true;
    stopAutoPlay();
  };
  var handleTransitionEnd = function handleTransitionEnd() {
    transitionRunning.current = false;
    if (isAutoPlay) {
      startAutoPlay();
    }
    if (!(position.index in childrenArray)) {
      setPosition({
        index: infiniteIndex,
        offset: 0
      });
    }
    if (typeof onChangeIndex === 'function') {
      onChangeIndex(infiniteIndex);
    }
  };
  React__namespace.useEffect(function () {
    var _refTrack$current, _refTrack$current2;
    var autoPlayObserver = new IntersectionObserver(function (entries) {
      if (entries[0].isIntersecting) {
        startAutoPlay();
      } else {
        stopAutoPlay();
      }
    });
    (_refTrack$current = refTrack.current) === null || _refTrack$current === void 0 || _refTrack$current.addEventListener('transitionstart', handleTransitionStart);
    (_refTrack$current2 = refTrack.current) === null || _refTrack$current2 === void 0 || _refTrack$current2.addEventListener('transitionend', handleTransitionEnd);
    if (isAutoPlay && refTrack.current) {
      autoPlayObserver.observe(refTrack.current);
    }
    return function () {
      var _refTrack$current3, _refTrack$current4;
      (_refTrack$current3 = refTrack.current) === null || _refTrack$current3 === void 0 || _refTrack$current3.removeEventListener('transitionstart', handleTransitionStart);
      (_refTrack$current4 = refTrack.current) === null || _refTrack$current4 === void 0 || _refTrack$current4.removeEventListener('transitionend', handleTransitionEnd);
      stopAutoPlay();
      autoPlayObserver.disconnect();
    };
  }, [position.index, isAutoPlay]);
  React__namespace.useEffect(function () {
    if (showIndex !== position.index) {
      setPosition({
        index: showIndex,
        offset: undefined
      });
    }
  }, [showIndex]);
  return /*#__PURE__*/React__namespace.createElement(Swipe__default.default, _extends__default.default({
    ref: ref,
    onSwipeLeft: handleSwipeNext,
    onSwipeRight: handleSwipePrev,
    onSwipeMove: handleSwipeMove,
    className: classNames__default.default(css.root, className, _defineProperty__default.default(_defineProperty__default.default({}, css.showOnHoverButtons, showOnHoverButtons), css.showOnHoverDots, showOnHoverDots)),
    style: getRootStyle({
      width: width,
      height: height,
      ratio: ratio,
      style: style
    }),
    onSwipeStart: function onSwipeStart() {
      return setDisableAutoPlay(true);
    },
    onSwipeEnd: function onSwipeEnd() {
      return setDisableAutoPlay(false);
    },
    onMouseEnter: function onMouseEnter() {
      return setDisableAutoPlay(true);
    },
    onMouseLeave: function onMouseLeave() {
      return setDisableAutoPlay(false);
    }
  }, props), isValidRatio(ratio) && /*#__PURE__*/React__namespace.createElement("div", {
    style: getRatioHolderStyle(ratio)
  }), /*#__PURE__*/React__namespace.createElement("ul", {
    ref: refTrack,
    className: css.track,
    style: getTrackStyle({
      index: infinite ? position.index + 1 : position.index,
      childrenCount: infinite ? childrenCount + 2 : childrenCount,
      duration: duration,
      offset: position.offset
    }),
    "data-testid": "simple_slider_track"
  }, infinite && /*#__PURE__*/React__namespace.createElement("li", {
    className: css.trackItem
  }, childrenArray[childrenArray.length - 1]), childrenArray.map(function (child, index) {
    return /*#__PURE__*/React__namespace.createElement("li", {
      key: index,
      className: css.trackItem,
      onClick: function onClick() {
        if (typeof onClickItem === 'function') {
          onClickItem(index);
        }
      },
      "data-qaid": "image_slider_".concat(index)
    }, child);
  }), infinite && /*#__PURE__*/React__namespace.createElement("li", {
    className: css.trackItem
  }, childrenArray[0])), isShowNavi && /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("button", {
    type: "button",
    className: css.buttonPrev,
    onClick: handleClickButtonPrev,
    disabled: isDisablePrev,
    "aria-label": t(_templateObject || (_templateObject = _taggedTemplateLiteral__default.default(["\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439 \u0431\u0430\u043D\u043D\u0435\u0440"]))),
    "data-qaid": "prev_image"
  }, /*#__PURE__*/React__namespace.createElement(Icon.Icon, {
    className: css.buttonIcon,
    "icon-as": Left.SvgLeft
  })), /*#__PURE__*/React__namespace.createElement("button", {
    type: "button",
    className: css.buttonNext,
    onClick: handleClickButtonNext,
    disabled: isDisableNext,
    "aria-label": t(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral__default.default(["\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439 \u0431\u0430\u043D\u043D\u0435\u0440"]))),
    "data-qaid": "next_image"
  }, /*#__PURE__*/React__namespace.createElement(Icon.Icon, {
    className: css.buttonIcon,
    "icon-as": Right.SvgRight
  }))), isShowDots && /*#__PURE__*/React__namespace.createElement("ul", {
    className: classNames__default.default(css.dots, _defineProperty__default.default({}, css.dotsTransparent, isDotsTransparent))
  }, childrenArray.map(function (_, index) {
    var viewIndex = index + 1;
    return /*#__PURE__*/React__namespace.createElement("li", {
      className: css.dotsItem,
      key: index
    }, /*#__PURE__*/React__namespace.createElement("button", {
      type: "button",
      className: css.dotsButton,
      onClick: function onClick() {
        return handleClickDot(index);
      },
      disabled: index === infiniteIndex,
      "aria-label": t(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral__default.default(["\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0431\u0430\u043D\u043D\u0435\u0440 \u043D\u043E\u043C\u0435\u0440 ", ""])), viewIndex),
      "data-qaid": "view_image_".concat(viewIndex)
    }, viewIndex));
  })));
});
SimpleSlider.displayName = 'SimpleSlider';

exports.SimpleSlider = SimpleSlider;

require('./style.development.v2.css');
