function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
import React, { Children, useState, useCallback, useMemo, useEffect } from "react";
import { Tab } from "./tab";
export var useBuildTabs = function useBuildTabs(children, activeIndex, onChange) {
  return useMemo(function () {
    var indeces = [];
    var nav = [];
    var content = null;
    var firstActiveIndex = -1;
    var activeIsDisabled = false;
    Children.forEach(children, function (tab, index) {
      var props = (tab == null ? void 0 : tab.props) || {};
      if (firstActiveIndex < 0 && !props.disabled) firstActiveIndex = index;
      var isActive = activeIndex === indeces.length;
      var key = index + "-" + props.label;
      if (tab) {
        nav.push(/*#__PURE__*/React.createElement(Tab, _extends({
          key: key
        }, props, {
          onChange: onChange,
          index: index,
          active: isActive
        })));
      }
      if (isActive) {
        activeIsDisabled = !!props.disabled;
        content = props.children;
      }
      indeces.push(index);
    });
    return [nav, content, firstActiveIndex, activeIsDisabled];
  }, [children, activeIndex, onChange]);
};
export var useSetActive = function useSetActive(selected, onChange) {
  if (selected === void 0) {
    selected = 0;
  }
  var _useState = useState(onChange ? selected : 0),
    activeIndex = _useState[0],
    setActiveIndex = _useState[1];
  var setActive = useCallback(function (index) {
    if (onChange) {
      onChange(index);
      return;
    }
    setActiveIndex(index);
  }, [onChange]);
  useEffect(function () {
    setActiveIndex(selected || 0);
  }, [selected]);
  return [activeIndex, setActive];
};