import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import useEventCallback from '@mui/utils/useEventCallback';
import useForkRef from '@mui/utils/useForkRef';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
import { publishTreeViewEvent } from "../../utils/publishTreeViewEvent.js";
import { useTreeViewContext } from "../../TreeViewProvider/index.js";
import { TreeViewChildrenItemContext, TreeViewChildrenItemProvider } from "../../TreeViewProvider/TreeViewChildrenItemProvider.js";
import { buildSiblingIndexes, TREE_VIEW_ROOT_PARENT_ID } from "../useTreeViewItems/useTreeViewItems.utils.js";
import { TreeViewItemDepthContext } from "../../TreeViewItemDepthContext/index.js";
import { generateTreeItemIdAttribute } from "../../corePlugins/useTreeViewId/useTreeViewId.utils.js";
import { jsx as _jsx } from "react/jsx-runtime";
export const useTreeViewJSXItems = ({
  instance,
  setState
}) => {
  instance.preventItemUpdates();
  const insertJSXItem = useEventCallback(item => {
    setState(prevState => {
      if (prevState.items.itemMetaMap[item.id] != null) {
        throw new Error(['MUI X: The Tree View component requires all items to have a unique `id` property.', 'Alternatively, you can use the `getItemId` prop to specify a custom id for each item.', `Two items were provided with the same id in the \`items\` prop: "${item.id}"`].join('\n'));
      }
      return _extends({}, prevState, {
        items: _extends({}, prevState.items, {
          itemMetaMap: _extends({}, prevState.items.itemMetaMap, {
            [item.id]: item
          }),
          // For Simple Tree View, we don't have a proper `item` object, so we create a very basic one.
          itemMap: _extends({}, prevState.items.itemMap, {
            [item.id]: {
              id: item.id,
              label: item.label
            }
          })
        })
      });
    });
    return () => {
      setState(prevState => {
        const newItemMetaMap = _extends({}, prevState.items.itemMetaMap);
        const newItemMap = _extends({}, prevState.items.itemMap);
        delete newItemMetaMap[item.id];
        delete newItemMap[item.id];
        return _extends({}, prevState, {
          items: _extends({}, prevState.items, {
            itemMetaMap: newItemMetaMap,
            itemMap: newItemMap
          })
        });
      });
      publishTreeViewEvent(instance, 'removeItem', {
        id: item.id
      });
    };
  });
  const setJSXItemsOrderedChildrenIds = (parentId, orderedChildrenIds) => {
    const parentIdWithDefault = parentId ?? TREE_VIEW_ROOT_PARENT_ID;
    setState(prevState => _extends({}, prevState, {
      items: _extends({}, prevState.items, {
        itemOrderedChildrenIds: _extends({}, prevState.items.itemOrderedChildrenIds, {
          [parentIdWithDefault]: orderedChildrenIds
        }),
        itemChildrenIndexes: _extends({}, prevState.items.itemChildrenIndexes, {
          [parentIdWithDefault]: buildSiblingIndexes(orderedChildrenIds)
        })
      })
    }));
  };
  const mapFirstCharFromJSX = useEventCallback((itemId, firstChar) => {
    instance.updateFirstCharMap(firstCharMap => {
      firstCharMap[itemId] = firstChar;
      return firstCharMap;
    });
    return () => {
      instance.updateFirstCharMap(firstCharMap => {
        const newMap = _extends({}, firstCharMap);
        delete newMap[itemId];
        return newMap;
      });
    };
  });
  return {
    instance: {
      insertJSXItem,
      setJSXItemsOrderedChildrenIds,
      mapFirstCharFromJSX
    }
  };
};
const isItemExpandable = reactChildren => {
  if (Array.isArray(reactChildren)) {
    return reactChildren.length > 0 && reactChildren.some(isItemExpandable);
  }
  return Boolean(reactChildren);
};
const useTreeViewJSXItemsItemPlugin = ({
  props,
  rootRef,
  contentRef
}) => {
  const {
    instance,
    treeId
  } = useTreeViewContext();
  const {
    children,
    disabled = false,
    label,
    itemId,
    id
  } = props;
  const parentContext = React.useContext(TreeViewChildrenItemContext);
  if (parentContext == null) {
    throw new Error(['MUI X: Could not find the Tree View Children Item context.', 'It looks like you rendered your component outside of a SimpleTreeView parent component.', 'This can also happen if you are bundling multiple versions of the Tree View.'].join('\n'));
  }
  const {
    registerChild,
    unregisterChild,
    parentId
  } = parentContext;
  const expandable = isItemExpandable(children);
  const pluginContentRef = React.useRef(null);
  const handleContentRef = useForkRef(pluginContentRef, contentRef);

  // Prevent any flashing
  useEnhancedEffect(() => {
    const idAttribute = generateTreeItemIdAttribute({
      itemId,
      treeId,
      id
    });
    registerChild(idAttribute, itemId);
    return () => {
      unregisterChild(idAttribute);
    };
  }, [registerChild, unregisterChild, itemId, id, treeId]);
  React.useEffect(() => {
    return instance.insertJSXItem({
      id: itemId,
      idAttribute: id,
      parentId,
      expandable,
      disabled
    });
  }, [instance, parentId, itemId, expandable, disabled, id]);
  React.useEffect(() => {
    if (label) {
      return instance.mapFirstCharFromJSX(itemId, (pluginContentRef.current?.textContent ?? '').substring(0, 1).toLowerCase());
    }
    return undefined;
  }, [instance, itemId, label]);
  return {
    contentRef: handleContentRef,
    rootRef
  };
};
useTreeViewJSXItems.itemPlugin = useTreeViewJSXItemsItemPlugin;
useTreeViewJSXItems.wrapItem = ({
  children,
  itemId
}) => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const depthContext = React.useContext(TreeViewItemDepthContext);
  return /*#__PURE__*/_jsx(TreeViewChildrenItemProvider, {
    itemId: itemId,
    children: /*#__PURE__*/_jsx(TreeViewItemDepthContext.Provider, {
      value: depthContext + 1,
      children: children
    })
  });
};
useTreeViewJSXItems.wrapRoot = ({
  children
}) => /*#__PURE__*/_jsx(TreeViewChildrenItemProvider, {
  children: /*#__PURE__*/_jsx(TreeViewItemDepthContext.Provider, {
    value: 0,
    children: children
  })
});
useTreeViewJSXItems.params = {};