import { objectWithoutProperties as _objectWithoutProperties, slicedToArray as _slicedToArray, extends as _extends } from '../../../../_virtual/_rollupPluginBabelHelpers.js';
import React__default, { forwardRef, useRef, useState, useCallback, useEffect, useMemo } from 'react';
import { cx } from '../../../../utils/index.js';
import { IconDisclosureLeftWithOffset } from '../../../_Icon/Icons/IconDisclosureLeftWithOffset.js';
import { IconDisclosureRightWithOffset } from '../../../_Icon/Icons/IconDisclosureRightWithOffset.js';
import { IconDisclosureDownWithOffset } from '../../../_Icon/Icons/IconDisclosureDownWithOffset.js';
import { IconDisclosureUpWithOffset } from '../../../_Icon/Icons/IconDisclosureUpWithOffset.js';
import { tokens, classes } from '../../tokens.js';
import { useSegmentInner } from '../../SegmentProvider/SegmentProvider.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 { base as base$4 } from './variations/_pilled/base.js';
import { base as base$7 } from './variations/_filledBackgound/base.js';
import { base as base$5 } from './variations/_stretch/base.js';
import { base as base$6 } from './variations/_orientation/base.js';
import { StyledContentWrapper, StyledContent, base, StyledTopArrow, StyledLeftArrow, StyledBottomArrow, StyledRightArrow } from './SegmentGroup.styles.js';
import { safeUseId } from '../../../../utils/react.js';

var _excluded = ["id", "selectionMode", "pilled", "stretch", "clip", "orientation", "filledBackground", "hasBackground", "hasDivider", "disabled", "size", "view", "children"];
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 getChildNodes = function getChildNodes(wrapper) {
  var container = wrapper === null || wrapper === void 0 ? void 0 : wrapper.firstChild;
  return container ? Array.from(container === null || container === void 0 ? void 0 : container.childNodes) : [];
};
var segmentGroupRoot = function segmentGroupRoot(Root) {
  return /*#__PURE__*/forwardRef(function (props, outerRef) {
    var id = props.id,
      selectionMode = props.selectionMode,
      pilled = props.pilled,
      stretch = props.stretch,
      _props$clip = props.clip,
      clip = _props$clip === void 0 ? true : _props$clip,
      _props$orientation = props.orientation,
      orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,
      _props$filledBackgrou = props.filledBackground,
      filledBackground = _props$filledBackgrou === void 0 ? false : _props$filledBackgrou,
      _props$hasBackground = props.hasBackground,
      hasBackground = _props$hasBackground === void 0 ? false : _props$hasBackground,
      _props$hasDivider = props.hasDivider,
      hasDivider = _props$hasDivider === void 0 ? false : _props$hasDivider,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      size = props.size,
      view = props.view,
      children = props.children,
      rest = _objectWithoutProperties(props, _excluded);
    var scrollRef = useRef(null);
    var trackRef = useRef(null);
    var leftArrowRef = useRef(null);
    var _useSegmentInner = useSegmentInner(),
      setSelectionMode = _useSegmentInner.setSelectionMode,
      setDisabledGroup = _useSegmentInner.setDisabledGroup,
      setHasDivider = _useSegmentInner.setHasDivider,
      setOrientation = _useSegmentInner.setOrientation;
    var _useState = useState(true),
      _useState2 = _slicedToArray(_useState, 2),
      firstItemVisible = _useState2[0],
      setFirstItemVisible = _useState2[1];
    var _useState3 = useState(true),
      _useState4 = _slicedToArray(_useState3, 2),
      lastItemVisible = _useState4[0],
      setLastItemVisible = _useState4[1];
    var uniqId = safeUseId();
    var segmentGroupId = id || uniqId;
    var canClip = clip && !stretch;
    var isVertical = orientation === 'vertical';
    var stretchClass = (clip ? firstItemVisible && lastItemVisible : true) && stretch ? classes.segmentStretch : undefined;
    var orientationClass = isVertical ? classes.segmentVertical : undefined;
    var clipScrollClass = canClip ? classes.segmentGroupClipScroll : undefined;
    var pilledAttr = (view !== 'clear' || hasBackground) && pilled;
    var filledBackgroundAttr = view !== 'clear' && filledBackground || hasBackground;
    var pilledClass = pilledAttr ? classes.segmentPilled : undefined;
    var filledClass = filledBackgroundAttr ? classes.segmentGroupFilledBackground : undefined;
    var onPrev = useCallback(function () {
      if (disabled || !scrollRef.current) {
        return;
      }
      var childNodes = getChildNodes(scrollRef.current);
      var scrollLeft = Math.round(scrollRef.current.scrollLeft);
      var firstOverflowingTab = childNodes.slice().reverse().find(function (child) {
        if (!child || child.offsetLeft === undefined) {
          return;
        }
        var tabStartX = child.offsetLeft;
        return tabStartX < scrollLeft;
      });
      firstOverflowingTab === null || firstOverflowingTab === void 0 || firstOverflowingTab.scrollIntoView({
        block: 'nearest',
        inline: 'nearest'
      });
    }, [disabled, scrollRef]);
    var onNext = useCallback(function () {
      if (disabled || !scrollRef.current) {
        return;
      }
      var scrollRight = Math.round(scrollRef.current.scrollLeft + scrollRef.current.clientWidth);
      var childNodes = getChildNodes(scrollRef.current);
      var lastOverflowingChild = childNodes.find(function (child) {
        if (!child || child.offsetLeft === undefined) {
          return;
        }
        var tabEndX = child.offsetLeft + child.offsetWidth;
        return tabEndX > scrollRight;
      });
      lastOverflowingChild === null || lastOverflowingChild === void 0 || lastOverflowingChild.scrollIntoView({
        block: 'nearest',
        inline: 'nearest'
      });
    }, [disabled, scrollRef]);
    var onKeyDown = useCallback(function (event) {
      var childNodes = getChildNodes(scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current);
      var index = childNodes.findIndex(function (child) {
        return document.activeElement === child;
      });
      var minIndex = 0;
      var maxIndex = childNodes.length - 1;
      var nextIndex;
      switch (event.keyCode) {
        case Keys.end:
          nextIndex = maxIndex;
          break;
        case Keys.left:
          nextIndex = index > minIndex ? index - 1 : index;
          break;
        case Keys.right:
          nextIndex = index < maxIndex ? index + 1 : index;
          break;
        case Keys.home:
          nextIndex = minIndex;
          break;
        default:
          return;
      }
      if (nextIndex !== index) {
        var _childNodes$nextIndex, _childNodes$nextIndex2;
        event.preventDefault();
        (_childNodes$nextIndex = childNodes[nextIndex]) === null || _childNodes$nextIndex === void 0 || _childNodes$nextIndex.focus();
        (_childNodes$nextIndex2 = childNodes[nextIndex]) === null || _childNodes$nextIndex2 === void 0 || _childNodes$nextIndex2.scrollIntoView({
          block: 'center',
          inline: 'center',
          behavior: 'smooth'
        });
      }
    }, []);
    var handleScroll = useCallback(function (event) {
      var _event$stopPropagatio;
      (_event$stopPropagatio = event.stopPropagation) === null || _event$stopPropagatio === void 0 || _event$stopPropagatio.call(event);
      if (!canClip) {
        setFirstItemVisible(true);
        setLastItemVisible(true);
        return;
      }
      if (isVertical) {
        var maxScrollTop = event.currentTarget.scrollHeight - event.currentTarget.clientHeight;
        var scrollTop = Math.round(event.currentTarget.scrollTop);
        setFirstItemVisible(scrollTop <= 0);
        setLastItemVisible(scrollTop >= maxScrollTop);
        return;
      }
      var maxScrollLeft = event.currentTarget.scrollWidth - event.currentTarget.clientWidth;
      var scrollLeft = Math.round(event.currentTarget.scrollLeft);
      setFirstItemVisible(scrollLeft <= 0);
      setLastItemVisible(scrollLeft >= maxScrollLeft);
    }, [isVertical, canClip]);
    useEffect(function () {
      handleScroll({
        currentTarget: scrollRef.current
      });
    }, [handleScroll]);
    useEffect(function () {
      var _scrollRef$current, _scrollRef$current2, _scrollRef$current3, _scrollRef$current4;
      if (!canClip) {
        setLastItemVisible(true);
        return;
      }
      setLastItemVisible(isVertical ? ((_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) : ((_scrollRef$current3 = scrollRef.current) === null || _scrollRef$current3 === void 0 ? void 0 : _scrollRef$current3.scrollWidth) === ((_scrollRef$current4 = scrollRef.current) === null || _scrollRef$current4 === void 0 ? void 0 : _scrollRef$current4.clientWidth));
    }, [isVertical, canClip]);

    // Этот хук компенсирует появление левой/верхней стрелки при прокрутке
    useEffect(function () {
      if (firstItemVisible || !scrollRef.current || !leftArrowRef.current) {
        return;
      }
      if (isVertical) {
        scrollRef.current.scrollTo({
          top: Math.round(scrollRef.current.scrollTop + leftArrowRef.current.clientHeight)
        });
        return;
      }
      scrollRef.current.scrollTo({
        left: Math.round(scrollRef.current.scrollLeft + leftArrowRef.current.clientWidth)
      });
    }, [firstItemVisible, isVertical]);
    var PreviousButton = useMemo(function () {
      var ArrowNode = isVertical ? StyledTopArrow : StyledLeftArrow;
      return /*#__PURE__*/React__default.createElement(ArrowNode, {
        type: "button",
        "aria-label": "\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439 \u0441\u0435\u0433\u043C\u0435\u043D\u0442",
        onClick: onPrev,
        tabIndex: disabled ? -1 : 0,
        disabled: disabled
      }, isVertical ? /*#__PURE__*/React__default.createElement(IconDisclosureUpWithOffset, {
        color: "var(".concat(tokens.arrowColor, ")"),
        size: "s"
      }) : /*#__PURE__*/React__default.createElement(IconDisclosureLeftWithOffset, {
        color: "var(".concat(tokens.arrowColor, ")")
      }));
    }, [onPrev, isVertical]);
    var NextButton = useMemo(function () {
      var ArrowNode = isVertical ? StyledBottomArrow : StyledRightArrow;
      return /*#__PURE__*/React__default.createElement(ArrowNode, {
        type: "button",
        "aria-label": "\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439 \u0441\u0435\u0433\u043C\u0435\u043D\u0442",
        onClick: onNext,
        tabIndex: disabled ? -1 : 0,
        disabled: disabled
      }, isVertical ? /*#__PURE__*/React__default.createElement(IconDisclosureDownWithOffset, {
        color: "var(".concat(tokens.arrowColor, ")"),
        size: "s"
      }) : /*#__PURE__*/React__default.createElement(IconDisclosureRightWithOffset, {
        color: "var(".concat(tokens.arrowColor, ")")
      }));
    }, [onNext, isVertical]);
    useEffect(function () {
      selectionMode && setSelectionMode(selectionMode);
      setDisabledGroup(disabled);
      setHasDivider(hasDivider);
      setOrientation(orientation);
    }, [selectionMode, disabled, hasDivider, orientation]);
    return /*#__PURE__*/React__default.createElement(Root, _extends({
      view: view,
      size: size,
      orientation: orientation,
      id: segmentGroupId,
      ref: outerRef,
      filledBackground: filledBackgroundAttr,
      disabled: disabled,
      pilled: pilledAttr,
      className: cx(pilledClass, filledClass, stretchClass, orientationClass),
      onKeyDown: onKeyDown
    }, rest), !firstItemVisible && PreviousButton, /*#__PURE__*/React__default.createElement(StyledContentWrapper, {
      className: cx(clipScrollClass),
      ref: scrollRef,
      onScroll: handleScroll
    }, /*#__PURE__*/React__default.createElement(StyledContent, {
      ref: trackRef
    }, children)), !lastItemVisible && NextButton);
  });
};
var segmentGroupConfig = {
  name: 'SegmentGroup',
  tag: 'div',
  layout: segmentGroupRoot,
  base: base,
  variations: {
    size: {
      css: base$1
    },
    view: {
      css: base$2
    },
    disabled: {
      css: base$3,
      attrs: true
    },
    pilled: {
      css: base$4,
      attrs: true
    },
    stretch: {
      css: base$5,
      attrs: true
    },
    orientation: {
      css: base$6
    },
    filledBackground: {
      css: base$7,
      attrs: true
    }
  },
  defaults: {
    view: 'clear',
    size: 'xs'
  }
};

export { getChildNodes, segmentGroupConfig, segmentGroupRoot };
