import { objectWithoutProperties as _objectWithoutProperties, slicedToArray as _slicedToArray, extends as _extends } from '../../../../../_virtual/_rollupPluginBabelHelpers.js';
import React__default, { forwardRef, useState, useMemo, useRef, useCallback, useLayoutEffect } from 'react';
import { cx } from '../../../../../utils/index.js';
import { classes } from '../../../tokens.js';
import { TabItemRefs, TabsContext } from '../../../TabsContext.js';
import { IconDisclosureLeft } from '../../../../_Icon/Icons/IconDisclosureLeft.js';
import { IconDisclosureRight } from '../../../../_Icon/Icons/IconDisclosureRight.js';
import { getFirstOverflowingTab, getLastOverflowingTab } from '../../../utils/index.js';
import { StyledContentWrapper, StyledContent, base, StyledArrow } from './VerticalTabs.styles.js';
import { base as base$1 } from './variations/_size/base.js';
import { base as base$2 } from './variations/_view/base.js';
import { base as base$3 } from './variations/_disabled/base.js';
import { safeUseId } from '../../../../../utils/react.js';

var _IconDisclosureLeft, _IconDisclosureRight;
var _excluded = ["id", "disabled", "clip", "size", "view", "children", "index", "className", "orientation", "hasDivider"];
var Keys = /*#__PURE__*/function (Keys) {
  Keys[Keys["end"] = 35] = "end";
  Keys[Keys["home"] = 36] = "home";
  Keys[Keys["up"] = 38] = "up";
  Keys[Keys["down"] = 40] = "down";
  return Keys;
}(Keys || {}); // TODO: https://github.com/salute-developers/plasma/issues/1474
var verticalTabsRoot = function verticalTabsRoot(Root) {
  return /*#__PURE__*/forwardRef(function (props, outerRef) {
    var id = props.id,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$clip = props.clip,
      clip = _props$clip === void 0 ? 'showAll' : _props$clip,
      size = props.size,
      view = props.view,
      children = props.children,
      index = props.index,
      className = props.className,
      orientation = props.orientation,
      _props$hasDivider = props.hasDivider,
      hasDivider = _props$hasDivider === void 0 ? true : _props$hasDivider,
      rest = _objectWithoutProperties(props, _excluded);
    var _useState = useState(true),
      _useState2 = _slicedToArray(_useState, 2),
      firstItemVisible = _useState2[0],
      setFirstItemVisible = _useState2[1];
    var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      lastItemVisible = _useState4[0],
      setLastItemVisible = _useState4[1];

    // Триггер доп. скролла при появлении левой стрелки, которая отъедает ширину scroll-контейнера
    var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      shouldTriggerAdditionalScroll = _useState6[0],
      setShouldTriggerAdditionalScroll = _useState6[1];
    var refs = useMemo(function () {
      return new TabItemRefs(index);
    }, []);
    var uniqId = safeUseId();
    var tabsId = id || uniqId;
    var noDividerClass = !hasDivider ? classes.tabsNoDivider : undefined;
    var hasTopArrowClass = !firstItemVisible ? classes.tabsHasTopArrow : undefined;
    var hasBottomArrowClass = !lastItemVisible ? classes.tabsHasBottomArrow : undefined;
    var clipScrollClass = clip === 'scroll' ? classes.tabsClipScroll : undefined;
    var clipShowAllClass = clip === 'showAll' ? classes.tabsClipShowAll : undefined;
    var scrollRef = useRef(null);
    var trackRef = useRef(null);
    var upArrowRef = useRef(null);
    var onPrev = useCallback(function () {
      if (disabled || !scrollRef.current) {
        return;
      }
      var scrollTop = scrollRef.current.scrollTop;
      var firstOverflowingTab = getFirstOverflowingTab(refs.items.slice().reverse(), scrollTop, orientation);
      if (!(firstOverflowingTab !== null && firstOverflowingTab !== void 0 && firstOverflowingTab.current)) {
        return;
      }
      var scrollElStyle = getComputedStyle(scrollRef.current);
      scrollRef.current.scrollTo({
        top: firstOverflowingTab.current.offsetTop - parseInt(scrollElStyle.paddingTop, 10)
      });
    }, [disabled, scrollRef, refs]);
    var onNext = useCallback(function () {
      if (disabled || !scrollRef.current) {
        return;
      }
      var scrollBottom = Math.round(scrollRef.current.scrollTop + scrollRef.current.clientHeight);
      var lastOverflowingTab = getLastOverflowingTab(refs.items, scrollBottom, orientation);
      if (!(lastOverflowingTab !== null && lastOverflowingTab !== void 0 && lastOverflowingTab.current)) {
        return;
      }
      if (firstItemVisible) {
        setShouldTriggerAdditionalScroll(true);
      }
      var scrollElStyle = getComputedStyle(scrollRef.current);
      scrollRef.current.scrollTo({
        top: Math.round(lastOverflowingTab.current.offsetTop + lastOverflowingTab.current.offsetHeight - scrollRef.current.clientHeight + parseInt(scrollElStyle.paddingTop, 10))
      });
    }, [firstItemVisible, disabled, scrollRef, refs]);
    var PreviousButton = /*#__PURE__*/React__default.createElement(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,
      ref: upArrowRef
    }, _IconDisclosureLeft || (_IconDisclosureLeft = /*#__PURE__*/React__default.createElement(IconDisclosureLeft, {
      color: "inherit"
    })));
    var NextButton = /*#__PURE__*/React__default.createElement(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
    }, _IconDisclosureRight || (_IconDisclosureRight = /*#__PURE__*/React__default.createElement(IconDisclosureRight, {
      color: "inherit"
    })));
    var handleScroll = useCallback(function (event) {
      event.stopPropagation();
      var scrollElStyle = getComputedStyle(event.currentTarget);
      var minScrollTop = parseInt(scrollElStyle.paddingLeft, 10);
      var maxScrollTop = event.currentTarget.scrollHeight - event.currentTarget.clientHeight - parseInt(scrollElStyle.paddingTop, 10);
      var scrollTop = Math.round(event.currentTarget.scrollTop);
      setFirstItemVisible(scrollTop <= minScrollTop);
      setLastItemVisible(scrollTop >= maxScrollTop);
    }, [setFirstItemVisible, setLastItemVisible]);
    var onKeyDown = useCallback(function (event) {
      if (index === undefined) {
        return;
      }
      var minIndex = 0;
      var maxIndex = refs.items.length - 1;
      var nextIndex;
      switch (event.keyCode) {
        case Keys.end:
          nextIndex = maxIndex;
          break;
        case Keys.up:
          nextIndex = index > minIndex ? index - 1 : index;
          break;
        case Keys.down:
          nextIndex = index < maxIndex ? index + 1 : index;
          break;
        case Keys.home:
          nextIndex = minIndex;
          break;
        default:
          return;
      }
      if (nextIndex !== index) {
        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: 'nearest',
          behavior: 'smooth'
        });
      }
    }, [index]);
    useLayoutEffect(function () {
      var _scrollRef$current, _scrollRef$current2;
      setLastItemVisible(((_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.scrollHeight) === ((_scrollRef$current2 = scrollRef.current) === null || _scrollRef$current2 === void 0 ? void 0 : _scrollRef$current2.clientHeight));
    }, [clip]);

    // Этот хук компенсирует появление верхней стрелки при прокрутке
    useLayoutEffect(function () {
      if (firstItemVisible || !shouldTriggerAdditionalScroll || !scrollRef.current || !upArrowRef.current) {
        return;
      }
      var style = getComputedStyle(scrollRef.current);
      scrollRef.current.scrollTo({
        top: Math.round(scrollRef.current.scrollTop + upArrowRef.current.clientHeight + parseInt(style.paddingTop, 10))
      });
      setShouldTriggerAdditionalScroll(false);
    }, [firstItemVisible, shouldTriggerAdditionalScroll, scrollRef, upArrowRef]);
    return /*#__PURE__*/React__default.createElement(TabsContext.Provider, {
      value: refs
    }, /*#__PURE__*/React__default.createElement(Root, _extends({
      view: view,
      role: "tablist",
      size: size,
      id: tabsId,
      ref: outerRef,
      disabled: disabled,
      className: cx(hasTopArrowClass, hasBottomArrowClass, noDividerClass, className),
      onKeyDown: onKeyDown,
      orientation: orientation
    }, rest), !firstItemVisible && clip === 'scroll' && PreviousButton, /*#__PURE__*/React__default.createElement(StyledContentWrapper, {
      className: cx(clipScrollClass, clipShowAllClass),
      ref: scrollRef,
      onScroll: handleScroll
    }, /*#__PURE__*/React__default.createElement(StyledContent, {
      ref: trackRef
    }, children)), !lastItemVisible && clip === 'scroll' && NextButton));
  });
};
var verticalTabsConfig = {
  name: 'VerticalTabs',
  tag: 'div',
  layout: verticalTabsRoot,
  base: base,
  variations: {
    size: {
      css: base$1
    },
    view: {
      css: base$2
    },
    disabled: {
      css: base$3,
      attrs: true
    }
  },
  defaults: {
    view: 'divider',
    size: 'xs'
  }
};

export { verticalTabsConfig, verticalTabsRoot };
