'use strict';

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

var React = require('react');
var Swipe = require('react-easy-swipe');
var classNames = require('clsx');
require('intersection-observer');
var Icon = require('@prom-ui/core/Icon');
var useBodyTTag = require('@prom-ui/core/useBodyTTag');
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 React__namespace = /*#__PURE__*/_interopNamespaceCompat(React);
var Swipe__default = /*#__PURE__*/_interopDefaultCompat(Swipe);
var classNames__default = /*#__PURE__*/_interopDefaultCompat(classNames);

function _iterableToArrayLimit(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function (sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
      _defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _extends() {
  _extends = Object.assign ? Object.assign.bind() : function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;
  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }
  return target;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }
  return target;
}
function _taggedTemplateLiteral(strings, raw) {
  if (!raw) {
    raw = strings.slice(0);
  }
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
}
function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toPrimitive(input, hint) {
  if (typeof input !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}

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

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 _objectSpread2({
    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___WuTIM","track":"SimpleSlider__track___G8BYu","trackItem":"SimpleSlider__trackItem___94Eq7","resetButton":"SimpleSlider__resetButton___LXJjI","buttonCommon":"SimpleSlider__buttonCommon___I5yQD SimpleSlider__resetButton___LXJjI","buttonPrev":"SimpleSlider__buttonPrev___UqTOk SimpleSlider__buttonCommon___I5yQD SimpleSlider__resetButton___LXJjI","buttonNext":"SimpleSlider__buttonNext___BbLNv SimpleSlider__buttonCommon___I5yQD SimpleSlider__resetButton___LXJjI","buttonIcon":"SimpleSlider__buttonIcon___89h6n","dots":"SimpleSlider__dots___E7g4J","dotsTransparent":"SimpleSlider__dotsTransparent___v-ZWk","dotsItem":"SimpleSlider__dotsItem___cbWCu","dotsButton":"SimpleSlider__dotsButton___7N4yb SimpleSlider__resetButton___LXJjI","showOnHoverButtons":"SimpleSlider__showOnHoverButtons___yssoj","showOnHoverDots":"SimpleSlider__showOnHoverDots___ig5DV"};

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"];
var SimpleSlider = /*#__PURE__*/React__namespace.forwardRef(function (_ref, ref) {
  var _classNames;
  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(_ref, _excluded);
  var _useBodyTTag = useBodyTTag.useBodyTTag(),
    t = _useBodyTTag.t;
  var refTrack = React__namespace.useRef(null);
  var transitionRunning = React__namespace.useRef(false);
  var _React$useState = React__namespace.useState(false),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    disableAutoPlay = _React$useState2[0],
    setDisableAutoPlay = _React$useState2[1];
  var _React$useState3 = React__namespace.useState({
      index: showIndex,
      offset: undefined
    }),
    _React$useState4 = _slicedToArray(_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(_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 ? void 0 : _refTrack$current.addEventListener('transitionstart', handleTransitionStart);
    (_refTrack$current2 = refTrack.current) === null || _refTrack$current2 === void 0 ? 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 ? void 0 : _refTrack$current3.removeEventListener('transitionstart', handleTransitionStart);
      (_refTrack$current4 = refTrack.current) === null || _refTrack$current4 === void 0 ? 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({
    ref: ref,
    onSwipeLeft: handleSwipeNext,
    onSwipeRight: handleSwipePrev,
    onSwipeMove: handleSwipeMove,
    className: classNames__default.default(css.root, className, (_classNames = {}, _defineProperty(_classNames, css.showOnHoverButtons, showOnHoverButtons), _defineProperty(_classNames, css.showOnHoverDots, showOnHoverDots), _classNames)),
    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: child.key,
      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(["\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(["\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({}, css.dotsTransparent, isDotsTransparent))
  }, childrenArray.map(function (child, index) {
    var viewIndex = index + 1;
    return /*#__PURE__*/React__namespace.createElement("li", {
      className: css.dotsItem,
      key: child.key
    }, /*#__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(["\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.css');
