import { isEqual } from 'lodash';
import { useState, useCallback, useEffect } from 'react';

const getPlacementWidth = (el) => {
  if (!el) {
    return 0;
  }
  const computedStyle = window.getComputedStyle(el);
  const width = el.offsetWidth;
  const marginLeft = parseInt(computedStyle.marginLeft || "0");
  const marginRight = parseInt(computedStyle.marginRight || "0");
  return width + marginLeft + marginRight;
};
const useTabAdaptiveLayout = (tabs, tabsRef, extraSlotRef, selectedKey) => {
  const [moreTabs, setMoreTabs] = useState([]);
  const doAdapt = useCallback(() => {
    if (!tabsRef.current)
      return;
    const tabBarEl = tabsRef.current;
    const tabNodeList = tabBarEl.querySelectorAll(".tab-item-title.common");
    const moreTabNode = tabBarEl.querySelector(
      ".tab-item-title.more"
    );
    const moreTabPlacementWidth = getPlacementWidth(moreTabNode);
    tabNodeList.forEach((tab) => tab.classList.remove("__hidden"));
    const maxContentWidth = getPlacementWidth(tabBarEl.parentElement) - getPlacementWidth(extraSlotRef.current) - moreTabPlacementWidth;
    let tabsTotalWidth = 24;
    const hiddenItems = [];
    let endIndex = Infinity;
    for (let i = 0; i < tabNodeList.length; i++) {
      const tab = tabNodeList[i];
      const tabWidth = getPlacementWidth(tab);
      if (maxContentWidth >= tabsTotalWidth + tabWidth) {
        tabsTotalWidth += tabWidth;
      } else {
        endIndex = i;
        break;
      }
    }
    while (endIndex <= tabNodeList.length - 1) {
      tabNodeList[endIndex].classList.add("__hidden");
      hiddenItems.push(tabs[endIndex]);
      endIndex++;
    }
    setMoreTabs((prevMoreTabs) => {
      if (!isEqual(hiddenItems, prevMoreTabs)) {
        return hiddenItems;
      }
      return prevMoreTabs;
    });
  }, [tabs, tabsRef, extraSlotRef]);
  useEffect(() => {
    doAdapt();
  }, [doAdapt, selectedKey]);
  useEffect(() => {
    var _a;
    const parentElement = (_a = tabsRef.current) == null ? void 0 : _a.parentElement;
    if (!parentElement)
      return;
    const resizeObserver = new ResizeObserver(() => {
      doAdapt();
    });
    resizeObserver.observe(parentElement);
    return () => {
      resizeObserver.disconnect();
    };
  }, [doAdapt, tabsRef]);
  return moreTabs;
};

export { useTabAdaptiveLayout };
