'use strict';

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

var _rollupPluginBabelHelpers = require('../../../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var index$1 = require('../../../../../utils/index.js');
var IconDisclosureLeft = require('../../../../_Icon/Icons/IconDisclosureLeft.js');
var IconDisclosureRight = require('../../../../_Icon/Icons/IconDisclosureRight.js');
var tokens = require('../../../tokens.js');
var TabsContext = require('../../../TabsContext.js');
var index = require('../../../utils/index.js');
var base = require('./variations/_size/base.js');
var base$1 = require('./variations/_view/base.js');
var base$2 = require('./variations/_disabled/base.js');
var base$4 = require('./variations/_pilled/base.js');
var base$3 = require('./variations/_stretch/base.js');
var HorizontalTabs_styles = require('./HorizontalTabs.styles.js');
var react = require('../../../../../utils/react.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var _excluded = ["id", "stretch", "disabled", "clip", "size", "view", "children", "pilled", "index", "className", "hasDivider"];
var Keys = /*#__PURE__*/function (Keys) {
  Keys[Keys["end"] = 35] = "end";
  Keys[Keys["home"] = 36] = "home";
  Keys[Keys["left"] = 37] = "left";
  Keys[Keys["right"] = 39] = "right";
  return Keys;
}(Keys || {});
var getIconSize = function getIconSize(size) {
  return size === 'h1' || size === 'h2' ? 'm' : 's';
};

// TODO: https://github.com/salute-developers/plasma/issues/1474
var horizontalTabsRoot = function horizontalTabsRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (props, outerRef) {
    var id = props.id,
      _props$stretch = props.stretch,
      stretch = _props$stretch === void 0 ? false : _props$stretch,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$clip = props.clip,
      clip = _props$clip === void 0 ? 'scroll' : _props$clip,
      size = props.size,
      view = props.view,
      children = props.children,
      _props$pilled = props.pilled,
      pilled = _props$pilled === void 0 ? false : _props$pilled,
      index$2 = props.index,
      className = props.className,
      _props$hasDivider = props.hasDivider,
      hasDivider = _props$hasDivider === void 0 ? true : _props$hasDivider,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(props, _excluded);
    var _useState = React.useState(true),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      firstItemVisible = _useState2[0],
      setFirstItemVisible = _useState2[1];
    var _useState3 = React.useState(false),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      lastItemVisible = _useState4[0],
      setLastItemVisible = _useState4[1];

    // Триггер доп. скролла при появлении левой стрелки, которая отъедает ширину scroll-контейнера
    var _useState5 = React.useState(false),
      _useState6 = _rollupPluginBabelHelpers.slicedToArray(_useState5, 2),
      shouldTriggerAdditionalScroll = _useState6[0],
      setShouldTriggerAdditionalScroll = _useState6[1];
    var refs = React.useMemo(function () {
      return new TabsContext.TabItemRefs(index$2);
    }, []);
    var uniqId = react.safeUseId();
    var tabsId = id || uniqId;
    var isFilled = view === 'filled'; // outer padding is only for filled view
    var pilledAttr = view !== 'clear' && pilled;
    var pilledClass = pilledAttr ? tokens.classes.tabsPilled : undefined;
    var noDividerClass = !hasDivider ? tokens.classes.tabsNoDivider : undefined;
    var stretchClass = firstItemVisible && lastItemVisible && stretch ? tokens.classes.tabsStretch : undefined;
    var hasLeftArrowClass = !firstItemVisible ? tokens.classes.tabsHasLeftArrow : undefined;
    var hasRightArrowClass = !lastItemVisible ? tokens.classes.tabsHasRightArrow : undefined;
    var clipScrollClass = clip === 'scroll' ? tokens.classes.tabsClipScroll : undefined;
    var clipShowAllClass = clip === 'showAll' ? tokens.classes.tabsClipShowAll : undefined;
    var scrollRef = React.useRef(null);
    var trackRef = React.useRef(null);
    var leftArrowRef = React.useRef(null);
    var onPrev = React.useCallback(function () {
      if (disabled || !scrollRef.current) {
        return;
      }
      var scrollLeft = scrollRef.current.scrollLeft;
      var firstOverflowingTab = index.getFirstOverflowingTab(refs.items.slice().reverse(), scrollLeft, rest.orientation);
      if (!(firstOverflowingTab !== null && firstOverflowingTab !== void 0 && firstOverflowingTab.current)) {
        return;
      }
      var scrollElStyle = getComputedStyle(scrollRef.current);
      scrollRef.current.scrollTo({
        left: firstOverflowingTab.current.offsetLeft - parseInt(scrollElStyle.paddingLeft, 10)
      });
    }, [disabled, scrollRef, refs]);
    var onNext = React.useCallback(function () {
      if (disabled || !scrollRef.current) {
        return;
      }
      var scrollRight = Math.round(scrollRef.current.scrollLeft + scrollRef.current.clientWidth);
      var lastOverflowingTab = index.getLastOverflowingTab(refs.items, scrollRight, rest.orientation);
      if (!(lastOverflowingTab !== null && lastOverflowingTab !== void 0 && lastOverflowingTab.current)) {
        return;
      }
      if (firstItemVisible) {
        setShouldTriggerAdditionalScroll(true);
      }
      var scrollElStyle = getComputedStyle(scrollRef.current);
      scrollRef.current.scrollTo({
        left: Math.round(lastOverflowingTab.current.offsetLeft + lastOverflowingTab.current.offsetWidth - scrollRef.current.clientWidth + parseInt(scrollElStyle.paddingRight, 10))
      });
    }, [firstItemVisible, disabled, scrollRef, refs]);
    var PreviousButton = React.useMemo(function () {
      return /*#__PURE__*/React__default.default.createElement(HorizontalTabs_styles.StyledArrow, {
        type: "button",
        "aria-label": "\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439 \u0442\u0430\u0431",
        onClick: onPrev,
        tabIndex: disabled ? -1 : 0,
        disabled: disabled,
        isFilled: isFilled,
        ref: leftArrowRef,
        isLeftArrow: true
      }, /*#__PURE__*/React__default.default.createElement(IconDisclosureLeft.IconDisclosureLeft, {
        size: getIconSize(size),
        color: "inherit"
      }));
    }, [onPrev, size, disabled, isFilled]);
    var NextButton = React.useMemo(function () {
      return /*#__PURE__*/React__default.default.createElement(HorizontalTabs_styles.StyledArrow, {
        type: "button",
        "aria-label": "\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439 \u0442\u0430\u0431",
        onClick: onNext,
        tabIndex: disabled ? -1 : 0,
        disabled: disabled,
        isFilled: isFilled
      }, /*#__PURE__*/React__default.default.createElement(IconDisclosureRight.IconDisclosureRight, {
        size: getIconSize(size),
        color: "inherit"
      }));
    }, [onNext, size, disabled, isFilled]);
    var handleScroll = React.useCallback(function (event) {
      event.stopPropagation();
      var scrollElStyle = getComputedStyle(event.currentTarget);
      var minScrollLeft = parseInt(scrollElStyle.paddingLeft, 10);
      var maxScrollLeft = event.currentTarget.scrollWidth - event.currentTarget.clientWidth - parseInt(scrollElStyle.paddingRight, 10);
      var scrollLeft = Math.round(event.currentTarget.scrollLeft);
      setFirstItemVisible(scrollLeft <= minScrollLeft);
      setLastItemVisible(scrollLeft >= maxScrollLeft);
    }, [setFirstItemVisible, setLastItemVisible]);
    var onKeyDown = React.useCallback(function (event) {
      if (index$2 === undefined) {
        return;
      }
      var minIndex = 0;
      var maxIndex = refs.items.length - 1;
      var nextIndex;
      switch (event.keyCode) {
        case Keys.end:
          nextIndex = maxIndex;
          break;
        case Keys.left:
          nextIndex = index$2 > minIndex ? index$2 - 1 : index$2;
          break;
        case Keys.right:
          nextIndex = index$2 < maxIndex ? index$2 + 1 : index$2;
          break;
        case Keys.home:
          nextIndex = minIndex;
          break;
        default:
          return;
      }
      if (nextIndex !== index$2) {
        var _refs$items$nextIndex, _refs$items$nextIndex2;
        event.preventDefault();
        (_refs$items$nextIndex = refs.items[nextIndex].current) === null || _refs$items$nextIndex === void 0 || _refs$items$nextIndex.focus();
        (_refs$items$nextIndex2 = refs.items[nextIndex].current) === null || _refs$items$nextIndex2 === void 0 || _refs$items$nextIndex2.scrollIntoView({
          block: 'nearest',
          inline: 'center',
          behavior: 'smooth'
        });
      }
    }, [index$2]);
    React.useLayoutEffect(function () {
      var _scrollRef$current, _scrollRef$current2;
      setLastItemVisible(((_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.scrollWidth) === ((_scrollRef$current2 = scrollRef.current) === null || _scrollRef$current2 === void 0 ? void 0 : _scrollRef$current2.clientWidth));
    }, [clip]);

    // Этот хук компенсирует появление левой стрелки при прокрутке
    React.useLayoutEffect(function () {
      if (firstItemVisible || !shouldTriggerAdditionalScroll || !scrollRef.current || !leftArrowRef.current) {
        return;
      }
      var style = getComputedStyle(scrollRef.current);
      scrollRef.current.scrollTo({
        left: Math.round(scrollRef.current.scrollLeft + leftArrowRef.current.clientWidth + parseInt(style.paddingLeft, 10))
      });
      setShouldTriggerAdditionalScroll(false);
    }, [firstItemVisible, shouldTriggerAdditionalScroll, scrollRef, leftArrowRef]);
    return /*#__PURE__*/React__default.default.createElement(TabsContext.TabsContext.Provider, {
      value: refs
    }, /*#__PURE__*/React__default.default.createElement(Root, _rollupPluginBabelHelpers.extends({
      view: view,
      role: "tablist"
      // TODO: убрать каст any, когда будут удалены deprecated props
      ,
      size: size,
      pilled: pilled,
      id: tabsId,
      ref: outerRef,
      disabled: disabled,
      className: index$1.cx(pilledClass, stretchClass, hasLeftArrowClass, hasRightArrowClass, noDividerClass, className),
      onKeyDown: onKeyDown
    }, rest), !firstItemVisible && clip === 'scroll' && PreviousButton, /*#__PURE__*/React__default.default.createElement(HorizontalTabs_styles.StyledContentWrapper, {
      className: index$1.cx(clipScrollClass, clipShowAllClass),
      ref: scrollRef,
      onScroll: handleScroll
    }, /*#__PURE__*/React__default.default.createElement(HorizontalTabs_styles.StyledContent, {
      ref: trackRef
    }, children)), !lastItemVisible && clip === 'scroll' && NextButton));
  });
};
var horizontalTabsConfig = {
  name: 'HorizontalTabs',
  tag: 'div',
  layout: horizontalTabsRoot,
  base: HorizontalTabs_styles.base,
  variations: {
    size: {
      css: base.base
    },
    view: {
      css: base$1.base
    },
    disabled: {
      css: base$2.base,
      attrs: true
    },
    stretch: {
      css: base$3.base,
      attrs: true
    },
    pilled: {
      css: base$4.base
    }
  },
  defaults: {
    view: 'clear',
    size: 'xs'
  }
};

exports.horizontalTabsConfig = horizontalTabsConfig;
exports.horizontalTabsRoot = horizontalTabsRoot;
