import * as React from 'react';
import PropTypes from 'prop-types';
import { useTreeViewContext } from "./useTreeViewContext.js";
import { escapeOperandAttributeSelector } from "../utils/utils.js";
import { generateTreeItemIdAttribute } from "../corePlugins/useTreeViewId/useTreeViewId.utils.js";
import { jsx as _jsx } from "react/jsx-runtime";
export const TreeViewChildrenItemContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== 'production') {
  TreeViewChildrenItemContext.displayName = 'TreeViewChildrenItemContext';
}
export function TreeViewChildrenItemProvider(props) {
  const {
    children,
    itemId = null
  } = props;
  const {
    instance,
    treeId,
    rootRef
  } = useTreeViewContext();
  const childrenIdAttrToIdRef = React.useRef(new Map());
  React.useEffect(() => {
    if (!rootRef.current) {
      return;
    }
    let idAttr = null;
    if (itemId == null) {
      idAttr = rootRef.current.id;
    } else {
      // Undefined during 1st render
      const itemMeta = instance.getItemMeta(itemId);
      if (itemMeta !== undefined) {
        idAttr = generateTreeItemIdAttribute({
          itemId,
          treeId,
          id: itemMeta.idAttribute
        });
      }
    }
    if (idAttr == null) {
      return;
    }
    const previousChildrenIds = instance.getItemOrderedChildrenIds(itemId ?? null) ?? [];
    const escapedIdAttr = escapeOperandAttributeSelector(idAttr);
    const childrenElements = rootRef.current.querySelectorAll(`${itemId == null ? '' : `*[id="${escapedIdAttr}"] `}[role="treeitem"]:not(*[id="${escapedIdAttr}"] [role="treeitem"] [role="treeitem"])`);
    const childrenIds = Array.from(childrenElements).map(child => childrenIdAttrToIdRef.current.get(child.id));
    const hasChanged = childrenIds.length !== previousChildrenIds.length || childrenIds.some((childId, index) => childId !== previousChildrenIds[index]);
    if (hasChanged) {
      instance.setJSXItemsOrderedChildrenIds(itemId ?? null, childrenIds);
    }
  });
  const value = React.useMemo(() => ({
    registerChild: (childIdAttribute, childItemId) => childrenIdAttrToIdRef.current.set(childIdAttribute, childItemId),
    unregisterChild: childIdAttribute => childrenIdAttrToIdRef.current.delete(childIdAttribute),
    parentId: itemId
  }), [itemId]);
  return /*#__PURE__*/_jsx(TreeViewChildrenItemContext.Provider, {
    value: value,
    children: children
  });
}
process.env.NODE_ENV !== "production" ? TreeViewChildrenItemProvider.propTypes = {
  children: PropTypes.node,
  id: PropTypes.string
} : void 0;