import React, { useCallback, useContext, useEffect, useState } from "react";
import { RicosContext } from "./../../../ricos-context/index.js";
import { ToolbarButtons } from "../../models/index.js";
const MORE_BUTTON_WIDTH = 30;
const GAP_BETWEEN_BUTTONS = 4;
const Overflow = ({
  width,
  toolbarButtons,
  onChange,
  onlyShownButtons
}) => {
  const { jsdomMode } = useContext(RicosContext);
  const [containerRef, setContainerRef] = useState(null);
  const buttonsToRender = new ToolbarButtons(
    toolbarButtons.toolbarButtons.filter((button) => onlyShownButtons === void 0 || onlyShownButtons.includes(button.getId())).sort(
      (a, b) => (onlyShownButtons?.findIndex((id) => id === a.getId()) ?? 0) - (onlyShownButtons?.findIndex((id) => id === b.getId()) ?? 0)
    )
  );
  const alwaysOverflownButtons = toolbarButtons.toolbarButtons.filter(
    (button) => onlyShownButtons !== void 0 && !onlyShownButtons.includes(button.getId())
  );
  useEffect(() => {
    let sumVisible = 0;
    const visibleButtons = new ToolbarButtons([]);
    const overflownButtons = new ToolbarButtons([]);
    if (!containerRef) {
      return;
    }
    const elements = Array.from(containerRef.children).map((child) => {
      return {
        child,
        width: Math.ceil(child.getBoundingClientRect().width)
      };
    });
    let stackIsFull = false;
    elements.forEach((element, index) => {
      if (!stackIsFull && sumVisible + element.width <= width - MORE_BUTTON_WIDTH || jsdomMode) {
        visibleButtons.addButton(buttonsToRender.getButtonByIndex(index));
        sumVisible += element.width + GAP_BETWEEN_BUTTONS;
      } else {
        stackIsFull = true;
        overflownButtons.addButton(buttonsToRender.getButtonByIndex(index));
      }
    });
    alwaysOverflownButtons.forEach((button) => {
      overflownButtons.addButton(button);
    });
    onChange({
      visibleButtons,
      overflownButtons
    });
  }, [width, toolbarButtons, containerRef]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      style: { visibility: "hidden", position: "absolute", display: "flex" },
      ref: setContainerRef
    },
    buttonsToRender.getButtonsElements()
  );
};
const useSizeCalculator = ({
  width,
  toolbarButtons,
  onlyShownButtons
}) => {
  const [data, setData] = useState();
  const OverflowCalculator = useCallback(
    () => /* @__PURE__ */ React.createElement(
      Overflow,
      {
        width: Number(width),
        toolbarButtons,
        onChange: setData,
        onlyShownButtons
      }
    ),
    [width, toolbarButtons, onlyShownButtons, setData]
  );
  return { data, OverflowCalculator };
};
export {
  useSizeCalculator
};
//# sourceMappingURL=use-size-calculator.js.map
