import flattenChildren from "react-keyed-flatten-children";
const isIcon = (node, options = {}) => {
  var _a;
  const checkChildren = options.checkChildren ?? true;
  if (node == null || typeof node !== "object" || !("type" in node)) {
    return false;
  }
  if (node.type.isGdsIcon) {
    return true;
  }
  if (checkChildren) {
    let element = null;
    if (typeof node.type === "function") {
      element = node.type(node.props);
    } else if (typeof node.type === "object" && "render" in node.type && typeof node.type.render === "function") {
      element = node.type.render(node.props);
    }
    return [((_a = element == null ? void 0 : element.props) == null ? void 0 : _a.children) ?? null].flat().some(
      (child) => isIcon(child, {
        checkChildren: false
      })
    );
  } else {
    return false;
  }
};
const getChildrenChunks = (children, trimWhitespace = false) => {
  const childrenArray = flattenChildren(children);
  const childrenChunks = [];
  childrenArray.forEach((child, childIndex) => {
    const childIsIcon = isIcon(child);
    let currentChunk = childrenChunks[childrenChunks.length - 1] ?? null;
    const previousChildIsIcon = (currentChunk == null ? void 0 : currentChunk.isIcon) ?? false;
    if (trimWhitespace) {
      const previousChildren = (currentChunk == null ? void 0 : currentChunk.children) ?? [];
      const previousChild = previousChildren.length > 0 ? previousChildren[previousChildren.length - 1] : null;
      if (typeof previousChild === "string" && childIsIcon) {
        previousChildren[previousChildren.length - 1] = previousChild.trimEnd();
      }
      if ((previousChildIsIcon || childIndex === 0) && typeof child === "string") {
        child = child.trimStart();
      }
      if (childIndex === childrenArray.length - 1 && typeof child === "string") {
        child = child.trimEnd();
      }
    }
    if (currentChunk === null || childIsIcon || previousChildIsIcon) {
      childrenChunks.push({
        children: [],
        isIcon: childIsIcon
      });
      currentChunk = childrenChunks[childrenChunks.length - 1];
    }
    currentChunk.children.push(child);
  });
  return childrenChunks;
};
export {
  getChildrenChunks,
  isIcon
};
