import "../ResponsiveGroup.css";
import { jsx } from "react/jsx-runtime";
import { useState, useMemo, Children, useRef, useLayoutEffect, useEffect } from "react";
import useResize from "./internal/useResize.js";
import "./Theme/UI.js";
import { Spacing } from "./Theme/themeUtils.js";
import { ShirtSize } from "./Theme/themes.js";
const base = "ResponsiveGroup_base_1933e";
const responsiveChild = "ResponsiveGroup_responsiveChild_1933e";
const css = {
  base,
  responsiveChild
};
const gapMap = {
  [ShirtSize.Small]: Spacing.Xs,
  [ShirtSize.Medium]: Spacing.Md,
  [ShirtSize.Large]: Spacing.Xl
};
function getPotentialWidth(el) {
  if (!el)
    return 0;
  el.style.display = "initial";
  const width = el.clientWidth;
  el.style.display = "";
  return width;
}
const ResponsiveGroup = ({
  children,
  gap = ShirtSize.Medium,
  maxVisible = 3,
  onChange
}) => {
  const [numVisible, setNumVisible] = useState(0);
  const childrenArray = useMemo(() => Children.toArray(children), [children]);
  const refs = useRef(new Array(childrenArray.length));
  const { size, refCallback } = useResize();
  useLayoutEffect(() => {
    const { visible } = refs.current.reduce(
      (obj, el, i, arr) => {
        const newObj = structuredClone(obj);
        newObj.accumulatedWidth += getPotentialWidth(el);
        if (newObj.accumulatedWidth > size.width) {
          if (el)
            el.style.display = "none";
        } else {
          if (el) {
            el.style.display = "initial";
            newObj.visible++;
          }
        }
        if (i !== arr.length - 1)
          newObj.accumulatedWidth += gapMap[gap];
        return newObj;
      },
      { accumulatedWidth: 0, visible: 0 }
    );
    setNumVisible(visible);
  }, [childrenArray, gap, maxVisible, onChange, size.width]);
  useEffect(() => {
    onChange == null ? void 0 : onChange(numVisible);
  }, [onChange, numVisible]);
  return /* @__PURE__ */ jsx("div", { className: css.base, ref: refCallback, style: { gap: gapMap[gap] }, children: childrenArray.slice(0, maxVisible).map((child, idx) => /* @__PURE__ */ jsx(
    "div",
    {
      className: css.responsiveChild,
      ref: (el) => {
        refs.current[idx] = el;
      },
      children: child
    },
    idx
  )) });
};
export {
  ResponsiveGroup as default
};
