import _extends from "@babel/runtime/helpers/esm/extends";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _JSXStyle from "../styled-jsx.es.js";
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import React, { Component, Children } from 'react';
import klass from '../cssClasses';
import { outerWidth } from '../dimensions';
import CSSTranslate from '../CSSTranslate';
// @ts-ignore
import Swipe from '../../swipe';
import getWindow from '../shims/window';
import Button from '../../button';
import { ChevronLeft, ChevronRight } from '@helpdice/icons';
var isKeyboardEvent = function isKeyboardEvent(e) {
  return e.hasOwnProperty('key');
};
var Thumbs = /*#__PURE__*/function (_Component) {
  function Thumbs(_props) {
    var _this;
    _classCallCheck(this, Thumbs);
    _this = _callSuper(this, Thumbs, [_props]);
    _defineProperty(_this, "setItemsWrapperRef", function (node) {
      _this.itemsWrapperRef = node;
    });
    _defineProperty(_this, "setItemsListRef", function (node) {
      _this.itemsListRef = node;
    });
    _defineProperty(_this, "setThumbsRef", function (node, index) {
      if (!_this.thumbsRef) {
        _this.thumbsRef = [];
      }
      _this.thumbsRef[index] = node;
    });
    _defineProperty(_this, "updateSizes", function () {
      if (!_this.props.children || !_this.itemsWrapperRef || !_this.thumbsRef) {
        return;
      }
      var total = Children.count(_this.props.children);
      var wrapperSize = _this.itemsWrapperRef.clientWidth;
      var itemSize = _this.props.thumbWidth ? _this.props.thumbWidth : outerWidth(_this.thumbsRef[0]);
      var visibleItems = Math.floor(wrapperSize / itemSize);
      var showArrows = visibleItems < total;
      var lastPosition = showArrows ? total - visibleItems : 0;
      _this.setState(function (_state, props) {
        return {
          itemSize: itemSize,
          visibleItems: visibleItems,
          firstItem: showArrows ? _this.getFirstItem(props.selectedItem) : 0,
          lastPosition: lastPosition,
          showArrows: showArrows
        };
      });
    });
    _defineProperty(_this, "handleClickItem", function (index, item, e) {
      if (!isKeyboardEvent(e) || e.key === 'Enter') {
        var handler = _this.props.onSelectItem;
        if (typeof handler === 'function') {
          handler(index, item);
        }
      }
    });
    _defineProperty(_this, "onSwipeStart", function () {
      _this.setState({
        swiping: true
      });
    });
    _defineProperty(_this, "onSwipeEnd", function () {
      _this.setState({
        swiping: false
      });
    });
    _defineProperty(_this, "onSwipeMove", function (delta) {
      var deltaX = delta.x;
      if (!_this.state.itemSize || !_this.itemsWrapperRef || !_this.state.visibleItems) {
        return false;
      }
      var leftBoundary = 0;
      var childrenLength = Children.count(_this.props.children);
      var currentPosition = -(_this.state.firstItem * 100) / _this.state.visibleItems;
      var lastLeftItem = Math.max(childrenLength - _this.state.visibleItems, 0);
      var lastLeftBoundary = -lastLeftItem * 100 / _this.state.visibleItems;

      // prevent user from swiping left out of boundaries
      if (currentPosition === leftBoundary && deltaX > 0) {
        deltaX = 0;
      }

      // prevent user from swiping right out of boundaries
      if (currentPosition === lastLeftBoundary && deltaX < 0) {
        deltaX = 0;
      }
      var wrapperSize = _this.itemsWrapperRef.clientWidth;
      var position = currentPosition + 100 / (wrapperSize / deltaX);
      // if 3d isn't available we will use left to move
      if (_this.itemsListRef) {
        ['WebkitTransform', 'MozTransform', 'MsTransform', 'OTransform', 'transform', 'msTransform'].forEach(function (prop) {
          _this.itemsListRef.style[prop] = CSSTranslate(position, '%', _this.props.axis);
        });
      }
      return true;
    });
    _defineProperty(_this, "slideRight", function (positions) {
      _this.moveTo(_this.state.firstItem - (typeof positions === 'number' ? positions : 1));
    });
    _defineProperty(_this, "slideLeft", function (positions) {
      _this.moveTo(_this.state.firstItem + (typeof positions === 'number' ? positions : 1));
    });
    _defineProperty(_this, "moveTo", function (position) {
      // position can't be lower than 0
      position = position < 0 ? 0 : position;
      // position can't be higher than last postion
      position = position >= _this.state.lastPosition ? _this.state.lastPosition : position;
      _this.setState({
        firstItem: position
      });
    });
    _this.state = {
      selectedItem: _props.selectedItem,
      swiping: false,
      showArrows: false,
      firstItem: 0,
      visibleItems: 0,
      lastPosition: 0
    };
    return _this;
  }
  _inherits(Thumbs, _Component);
  return _createClass(Thumbs, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.setupThumbs();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (this.props.selectedItem !== this.state.selectedItem) {
        this.setState({
          selectedItem: this.props.selectedItem,
          firstItem: this.getFirstItem(this.props.selectedItem)
        });
      }
      if (this.props.children === prevProps.children) {
        return;
      }

      // This will capture any size changes for arrow adjustments etc.
      // usually in the same render cycle so we don't see any flickers
      this.updateSizes();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.destroyThumbs();
    }
  }, {
    key: "setupThumbs",
    value: function setupThumbs() {
      // as the widths are calculated, we need to resize
      // the carousel when the window is resized
      getWindow().addEventListener('resize', this.updateSizes);
      // issue #2 - image loading smaller
      getWindow().addEventListener('DOMContentLoaded', this.updateSizes);

      // when the component is rendered we need to calculate
      // the container size to adjust the responsive behaviour
      this.updateSizes();
    }
  }, {
    key: "destroyThumbs",
    value: function destroyThumbs() {
      // removing listeners
      getWindow().removeEventListener('resize', this.updateSizes);
      getWindow().removeEventListener('DOMContentLoaded', this.updateSizes);
    }
  }, {
    key: "getFirstItem",
    value: function getFirstItem(selectedItem) {
      var firstItem = selectedItem;
      if (selectedItem >= this.state.lastPosition) {
        firstItem = this.state.lastPosition;
      }
      if (selectedItem < this.state.firstItem + this.state.visibleItems) {
        firstItem = this.state.firstItem;
      }
      if (selectedItem < this.state.firstItem) {
        firstItem = selectedItem;
      }
      return firstItem;
    }
  }, {
    key: "renderItems",
    value: function renderItems() {
      var _this2 = this;
      return this.props.children.map(function (img, index) {
        var itemClass = klass.ITEM(false, index === _this2.state.selectedItem);
        var thumbProps = {
          key: index,
          ref: function ref(e) {
            return _this2.setThumbsRef(e, index);
          },
          className: itemClass,
          onClick: _this2.handleClickItem.bind(_this2, index, _this2.props.children[index]),
          onKeyDown: _this2.handleClickItem.bind(_this2, index, _this2.props.children[index]),
          'aria-label': "".concat(_this2.props.labels.item, " ").concat(index + 1),
          style: {
            width: _this2.props.thumbWidth
          }
        };
        return /*#__PURE__*/React.createElement("li", _extends({}, thumbProps, {
          role: "button",
          tabIndex: 0,
          className: "jsx-2625056898" + " " + (thumbProps && thumbProps.className != null && thumbProps.className || "")
        }), img, /*#__PURE__*/React.createElement(_JSXStyle, {
          id: "2625056898"
        }, ".thumb.jsx-2625056898{-webkit-transition:border 0.15s ease-in;transition:border 0.15s ease-in;display:inline-block;margin-right:6px;margin-bottom:0 !important;white-space:nowrap;overflow:hidden;border:3px solid #fff;padding:2px;}.thumb.jsx-2625056898:focus{border:3px solid #ccc;outline:none;}.thumb.selected.jsx-2625056898,.thumb.jsx-2625056898:hover{border:3px solid #0099ff;}.thumb.jsx-2625056898 img.jsx-2625056898{vertical-align:top;}"));
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;
      if (!this.props.children) {
        return null;
      }
      var isSwipeable = Children.count(this.props.children) > 1;

      // show left arrow?
      var hasPrev = this.state.showArrows && this.state.firstItem > 0;
      // show right arrow
      var hasNext = this.state.showArrows && this.state.firstItem < this.state.lastPosition;
      // obj to hold the transformations and styles
      var itemListStyles = {};
      var currentPosition = -this.state.firstItem * (this.state.itemSize || 0);
      var transformProp = CSSTranslate(currentPosition, 'px', this.props.axis);
      var transitionTime = this.props.transitionTime + 'ms';
      itemListStyles = {
        WebkitTransform: transformProp,
        MozTransform: transformProp,
        MsTransform: transformProp,
        OTransform: transformProp,
        transform: transformProp,
        msTransform: transformProp,
        WebkitTransitionDuration: transitionTime,
        MozTransitionDuration: transitionTime,
        MsTransitionDuration: transitionTime,
        OTransitionDuration: transitionTime,
        transitionDuration: transitionTime,
        msTransitionDuration: transitionTime
      };
      return /*#__PURE__*/React.createElement("div", {
        className: "jsx-3452014152" + " " + (klass.CAROUSEL(false) || "")
      }, /*#__PURE__*/React.createElement("div", {
        ref: this.setItemsWrapperRef,
        className: "jsx-3452014152" + " " + (klass.WRAPPER(false) || "")
      }, /*#__PURE__*/React.createElement(Button, {
        scale: 2 / 3,
        auto: true,
        px: 0.6,
        type: "button",
        style: {
          position: 'absolute',
          zIndex: '2',
          left: 0
        },
        iconRight: /*#__PURE__*/React.createElement(ChevronLeft, null),
        className: klass.ARROW_PREV(!hasPrev),
        onClick: function onClick() {
          return _this3.slideRight();
        },
        "aria-label": this.props.labels.leftArrow
      }), isSwipeable ? /*#__PURE__*/React.createElement(Swipe, {
        tagName: "ul",
        className: klass.SLIDER(false, this.state.swiping),
        onSwipeLeft: this.slideLeft,
        onSwipeRight: this.slideRight,
        onSwipeMove: this.onSwipeMove,
        onSwipeStart: this.onSwipeStart,
        onSwipeEnd: this.onSwipeEnd,
        style: _extends({
          display: 'flex',
          margin: '20px 45px'
        }, itemListStyles),
        innerRef: this.setItemsListRef,
        allowMouseEvents: this.props.emulateTouch
      }, this.renderItems()) : /*#__PURE__*/React.createElement("ul", {
        ref: function ref(node) {
          return _this3.setItemsListRef(node);
        },
        style: itemListStyles,
        className: "jsx-3452014152" + " " + (klass.SLIDER(false, this.state.swiping) || "")
      }, this.renderItems()), /*#__PURE__*/React.createElement(Button, {
        type: "button",
        scale: 2 / 3,
        auto: true,
        px: 0.6,
        style: {
          position: 'absolute',
          zIndex: '2',
          right: 0
        },
        iconRight: /*#__PURE__*/React.createElement(ChevronRight, null),
        className: klass.ARROW_NEXT(!hasNext),
        onClick: function onClick() {
          return _this3.slideLeft();
        },
        "aria-label": this.props.labels.rightArrow
      })), /*#__PURE__*/React.createElement(_JSXStyle, {
        id: "3452014152"
      }, ".thumbs-wrapper.jsx-3452014152{margin:0;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;position:relative;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}.thumbs.jsx-3452014152{-webkit-transition:all 0.15s ease-in;transition:all 0.15s ease-in;position:relative;list-style:none;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;white-space:nowrap;margin:0 !important;}.control-arrow.control-prev.jsx-3452014152{left:0;}.control-arrow.control-prev.jsx-3452014152:before{border-right:8px solid #fff;}.control-arrow.control-next.jsx-3452014152{right:0;}.control-arrow.control-next.jsx-3452014152:before{border-left:8px solid #fff;}"));
    }
  }]);
}(Component);
_defineProperty(Thumbs, "displayName", 'Thumbs');
_defineProperty(Thumbs, "defaultProps", {
  axis: 'horizontal',
  labels: {
    leftArrow: 'previous slide / item',
    rightArrow: 'next slide / item',
    item: 'slide item'
  },
  selectedItem: 0,
  thumbWidth: 80,
  transitionTime: 350
});
export { Thumbs as default };