'use client';

import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
const _excluded = ["children", "className", "slots", "slotProps", "ContentComponent", "ContentProps", "itemId", "id", "label", "onClick", "onMouseDown", "onFocus", "onBlur", "onKeyDown"],
  _excluded2 = ["ownerState"],
  _excluded3 = ["ownerState"],
  _excluded4 = ["ownerState"];
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import Collapse from '@mui/material/Collapse';
import useForkRef from '@mui/utils/useForkRef';
import { shouldForwardProp } from '@mui/system/createStyled';
import { alpha } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import extractEventHandlers from '@mui/utils/extractEventHandlers';
import resolveComponentProps from '@mui/utils/resolveComponentProps';
import useSlotProps from '@mui/utils/useSlotProps';
import unsupportedProp from '@mui/utils/unsupportedProp';
import elementTypeAcceptingRef from '@mui/utils/elementTypeAcceptingRef';
import { warnOnce } from '@mui/x-internals/warning';
import { styled, createUseThemeProps } from "../internals/zero-styled/index.js";
import { TreeItemContent } from "./TreeItemContent.js";
import { treeItemClasses, getTreeItemUtilityClass } from "./treeItemClasses.js";
import { useTreeViewContext } from "../internals/TreeViewProvider/index.js";
import { TreeViewCollapseIcon, TreeViewExpandIcon } from "../icons/index.js";
import { TreeItem2Provider } from "../TreeItem2Provider/index.js";
import { TreeViewItemDepthContext } from "../internals/TreeViewItemDepthContext/index.js";
import { useTreeItemState } from "./useTreeItemState.js";
import { isTargetInDescendants } from "../internals/utils/tree.js";
import { generateTreeItemIdAttribute } from "../internals/corePlugins/useTreeViewId/useTreeViewId.utils.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const useThemeProps = createUseThemeProps('MuiTreeItem');
const useUtilityClasses = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    content: ['content'],
    expanded: ['expanded'],
    selected: ['selected'],
    focused: ['focused'],
    disabled: ['disabled'],
    iconContainer: ['iconContainer'],
    checkbox: ['checkbox'],
    label: ['label'],
    labelInput: ['labelInput'],
    editing: ['editing'],
    editable: ['editable'],
    groupTransition: ['groupTransition']
  };
  return composeClasses(slots, getTreeItemUtilityClass, classes);
};
const TreeItemRoot = styled('li', {
  name: 'MuiTreeItem',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  listStyle: 'none',
  margin: 0,
  padding: 0,
  outline: 0
});
const StyledTreeItemContent = styled(TreeItemContent, {
  name: 'MuiTreeItem',
  slot: 'Content',
  overridesResolver: (props, styles) => {
    return [styles.content, styles.iconContainer && {
      [`& .${treeItemClasses.iconContainer}`]: styles.iconContainer
    }, styles.label && {
      [`& .${treeItemClasses.label}`]: styles.label
    }];
  },
  shouldForwardProp: prop => shouldForwardProp(prop) && prop !== 'indentationAtItemLevel'
})(({
  theme
}) => ({
  padding: theme.spacing(0.5, 1),
  borderRadius: theme.shape.borderRadius,
  width: '100%',
  boxSizing: 'border-box',
  // prevent width + padding to overflow
  position: 'relative',
  display: 'flex',
  alignItems: 'center',
  gap: theme.spacing(1),
  cursor: 'pointer',
  WebkitTapHighlightColor: 'transparent',
  '&:hover': {
    backgroundColor: (theme.vars || theme).palette.action.hover,
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  },
  [`&.${treeItemClasses.disabled}`]: {
    opacity: (theme.vars || theme).palette.action.disabledOpacity,
    backgroundColor: 'transparent'
  },
  [`&.${treeItemClasses.focused}`]: {
    backgroundColor: (theme.vars || theme).palette.action.focus
  },
  [`&.${treeItemClasses.selected}`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
    '&:hover': {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)
      }
    },
    [`&.${treeItemClasses.focused}`]: {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
    }
  },
  [`& .${treeItemClasses.iconContainer}`]: {
    width: 16,
    display: 'flex',
    flexShrink: 0,
    justifyContent: 'center',
    '& svg': {
      fontSize: 18
    }
  },
  [`& .${treeItemClasses.label}`]: _extends({
    width: '100%',
    boxSizing: 'border-box',
    // prevent width + padding to overflow
    // fixes overflow - see https://github.com/mui/material-ui/issues/27372
    minWidth: 0,
    position: 'relative'
  }, theme.typography.body1),
  [`& .${treeItemClasses.checkbox}`]: {
    padding: 0
  },
  variants: [{
    props: {
      indentationAtItemLevel: true
    },
    style: {
      paddingLeft: `calc(${theme.spacing(1)} + var(--TreeView-itemChildrenIndentation) * var(--TreeView-itemDepth))`
    }
  }]
}));
const TreeItemGroup = styled(Collapse, {
  name: 'MuiTreeItem',
  slot: 'GroupTransition',
  overridesResolver: (props, styles) => styles.groupTransition,
  shouldForwardProp: prop => shouldForwardProp(prop) && prop !== 'indentationAtItemLevel'
})({
  margin: 0,
  padding: 0,
  paddingLeft: 'var(--TreeView-itemChildrenIndentation)',
  variants: [{
    props: {
      indentationAtItemLevel: true
    },
    style: {
      paddingLeft: 0
    }
  }]
});

/**
 *
 * Demos:
 *
 * - [Tree View](https://mui.com/x/react-tree-view/)
 *
 * API:
 *
 * - [TreeItem API](https://mui.com/x/api/tree-view/tree-item/)
 */
export const TreeItem = /*#__PURE__*/React.forwardRef(function TreeItem(inProps, inRef) {
  const {
    icons: contextIcons,
    runItemPlugins,
    items: {
      disabledItemsFocusable,
      indentationAtItemLevel
    },
    selection: {
      disableSelection
    },
    treeId,
    instance
  } = useTreeViewContext();
  const depthContext = React.useContext(TreeViewItemDepthContext);
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTreeItem'
  });
  const {
      children,
      className,
      slots: inSlots,
      slotProps: inSlotProps,
      ContentComponent = TreeItemContent,
      ContentProps,
      itemId,
      id,
      label,
      onClick,
      onMouseDown,
      onBlur,
      onKeyDown
    } = props,
    other = _objectWithoutPropertiesLoose(props, _excluded);
  const {
    expanded,
    focused,
    selected,
    disabled,
    editing,
    handleCancelItemLabelEditing,
    handleSaveItemLabel
  } = useTreeItemState(itemId);
  if (process.env.NODE_ENV !== 'production') {
    // Checking directly the `props` to avoid having the default value applied
    if (props.ContentComponent) {
      warnOnce(['MUI X: The ContentComponent prop of the TreeItem component is deprecated and will be removed in the next major release.', 'You can use the new TreeItem2 component or the new useTreeItem2 hook to customize the rendering of the content.', 'For more detail, see https://mui.com/x/react-tree-view/tree-item-customization/.']);
    }
    if (props.ContentProps) {
      warnOnce(['MUI X: The ContentProps prop of the TreeItem component is deprecated and will be removed in the next major release.', 'You can use the new TreeItem2 component or the new useTreeItem2 hook to customize the rendering of the content.', 'For more detail, see https://mui.com/x/react-tree-view/tree-item-customization/.']);
    }
  }
  const {
    contentRef,
    rootRef,
    propsEnhancers
  } = runItemPlugins(props);
  const rootRefObject = React.useRef(null);
  const contentRefObject = React.useRef(null);
  const handleRootRef = useForkRef(inRef, rootRef, rootRefObject);
  const handleContentRef = useForkRef(ContentProps?.ref, contentRef, contentRefObject);
  const slots = {
    expandIcon: inSlots?.expandIcon ?? contextIcons.slots.expandIcon ?? TreeViewExpandIcon,
    collapseIcon: inSlots?.collapseIcon ?? contextIcons.slots.collapseIcon ?? TreeViewCollapseIcon,
    endIcon: inSlots?.endIcon ?? contextIcons.slots.endIcon,
    icon: inSlots?.icon,
    groupTransition: inSlots?.groupTransition
  };
  const isExpandable = reactChildren => {
    if (Array.isArray(reactChildren)) {
      return reactChildren.length > 0 && reactChildren.some(isExpandable);
    }
    return Boolean(reactChildren);
  };
  const expandable = isExpandable(children);
  const ownerState = _extends({}, props, {
    expanded,
    focused,
    selected,
    disabled,
    indentationAtItemLevel
  });
  const classes = useUtilityClasses(ownerState);
  const GroupTransition = slots.groupTransition ?? undefined;
  const groupTransitionProps = useSlotProps({
    elementType: GroupTransition,
    ownerState: {},
    externalSlotProps: inSlotProps?.groupTransition,
    additionalProps: _extends({
      unmountOnExit: true,
      in: expanded,
      component: 'ul',
      role: 'group'
    }, indentationAtItemLevel ? {
      indentationAtItemLevel: true
    } : {}),
    className: classes.groupTransition
  });
  const ExpansionIcon = expanded ? slots.collapseIcon : slots.expandIcon;
  const _useSlotProps = useSlotProps({
      elementType: ExpansionIcon,
      ownerState: {},
      externalSlotProps: tempOwnerState => {
        if (expanded) {
          return _extends({}, resolveComponentProps(contextIcons.slotProps.collapseIcon, tempOwnerState), resolveComponentProps(inSlotProps?.collapseIcon, tempOwnerState));
        }
        return _extends({}, resolveComponentProps(contextIcons.slotProps.expandIcon, tempOwnerState), resolveComponentProps(inSlotProps?.expandIcon, tempOwnerState));
      }
    }),
    expansionIconProps = _objectWithoutPropertiesLoose(_useSlotProps, _excluded2);
  const expansionIcon = expandable && !!ExpansionIcon ? /*#__PURE__*/_jsx(ExpansionIcon, _extends({}, expansionIconProps)) : null;
  const DisplayIcon = expandable ? undefined : slots.endIcon;
  const _useSlotProps2 = useSlotProps({
      elementType: DisplayIcon,
      ownerState: {},
      externalSlotProps: tempOwnerState => {
        if (expandable) {
          return {};
        }
        return _extends({}, resolveComponentProps(contextIcons.slotProps.endIcon, tempOwnerState), resolveComponentProps(inSlotProps?.endIcon, tempOwnerState));
      }
    }),
    displayIconProps = _objectWithoutPropertiesLoose(_useSlotProps2, _excluded3);
  const displayIcon = DisplayIcon ? /*#__PURE__*/_jsx(DisplayIcon, _extends({}, displayIconProps)) : null;
  const Icon = slots.icon;
  const _useSlotProps3 = useSlotProps({
      elementType: Icon,
      ownerState: {},
      externalSlotProps: inSlotProps?.icon
    }),
    iconProps = _objectWithoutPropertiesLoose(_useSlotProps3, _excluded4);
  const icon = Icon ? /*#__PURE__*/_jsx(Icon, _extends({}, iconProps)) : null;

  // https://www.w3.org/WAI/ARIA/apg/patterns/treeview/
  let ariaSelected;
  if (selected) {
    // - each selected node has aria-selected set to true.
    ariaSelected = true;
  } else if (disableSelection || disabled) {
    // - if the tree contains nodes that are not selectable, aria-selected is not present on those nodes.
    ariaSelected = undefined;
  } else {
    // - all nodes that are selectable but not selected have aria-selected set to false.
    ariaSelected = false;
  }
  function handleFocus(event) {
    const canBeFocused = !disabled || disabledItemsFocusable;
    if (!focused && canBeFocused && event.currentTarget === event.target) {
      instance.focusItem(event, itemId);
    }
  }
  function handleBlur(event) {
    onBlur?.(event);
    if (editing ||
    // we can exit the editing state by clicking outside the input (within the Tree Item) or by pressing Enter or Escape -> we don't want to remove the focused item from the state in these cases
    // we can also exit the editing state by clicking on the root itself -> want to remove the focused item from the state in this case
    event.relatedTarget && isTargetInDescendants(event.relatedTarget, rootRefObject.current) && (event.target && event.target?.dataset?.element === 'labelInput' && isTargetInDescendants(event.target, rootRefObject.current) || event.relatedTarget?.dataset?.element === 'labelInput')) {
      return;
    }
    instance.removeFocusedItem();
  }
  const handleKeyDown = event => {
    onKeyDown?.(event);
    if (event.target?.dataset?.element === 'labelInput') {
      return;
    }
    instance.handleItemKeyDown(event, itemId);
  };
  const idAttribute = generateTreeItemIdAttribute({
    itemId,
    treeId,
    id
  });
  const tabIndex = instance.canItemBeTabbed(itemId) ? 0 : -1;
  const sharedPropsEnhancerParams = {
    rootRefObject,
    contentRefObject,
    interactions: {
      handleSaveItemLabel,
      handleCancelItemLabelEditing
    }
  };
  const enhancedRootProps = propsEnhancers.root?.(_extends({}, sharedPropsEnhancerParams, {
    externalEventHandlers: extractEventHandlers(other)
  })) ?? {};
  const enhancedContentProps = propsEnhancers.content?.(_extends({}, sharedPropsEnhancerParams, {
    externalEventHandlers: extractEventHandlers(ContentProps)
  })) ?? {};
  const enhancedDragAndDropOverlayProps = propsEnhancers.dragAndDropOverlay?.(_extends({}, sharedPropsEnhancerParams, {
    externalEventHandlers: {}
  })) ?? {};
  const enhancedLabelInputProps = propsEnhancers.labelInput?.(_extends({}, sharedPropsEnhancerParams, {
    externalEventHandlers: {}
  })) ?? {};
  return /*#__PURE__*/_jsx(TreeItem2Provider, {
    itemId: itemId,
    children: /*#__PURE__*/_jsxs(TreeItemRoot, _extends({
      className: clsx(classes.root, className),
      role: "treeitem",
      "aria-expanded": expandable ? expanded : undefined,
      "aria-selected": ariaSelected,
      "aria-disabled": disabled || undefined,
      id: idAttribute,
      tabIndex: tabIndex
    }, other, {
      ownerState: ownerState,
      onFocus: handleFocus,
      onBlur: handleBlur,
      onKeyDown: handleKeyDown,
      ref: handleRootRef,
      style: indentationAtItemLevel ? _extends({}, other.style, {
        '--TreeView-itemDepth': typeof depthContext === 'function' ? depthContext(itemId) : depthContext
      }) : other.style
    }, enhancedRootProps, {
      children: [/*#__PURE__*/_jsx(StyledTreeItemContent, _extends({
        as: ContentComponent,
        classes: {
          root: classes.content,
          expanded: classes.expanded,
          selected: classes.selected,
          focused: classes.focused,
          disabled: classes.disabled,
          editable: classes.editable,
          editing: classes.editing,
          iconContainer: classes.iconContainer,
          label: classes.label,
          labelInput: classes.labelInput,
          checkbox: classes.checkbox
        },
        label: label,
        itemId: itemId,
        onClick: onClick,
        onMouseDown: onMouseDown,
        icon: icon,
        expansionIcon: expansionIcon,
        displayIcon: displayIcon,
        ownerState: ownerState
      }, ContentProps, enhancedContentProps, enhancedDragAndDropOverlayProps.action == null ? {} : {
        dragAndDropOverlayProps: enhancedDragAndDropOverlayProps
      }, enhancedLabelInputProps.value == null ? {} : {
        labelInputProps: enhancedLabelInputProps
      }, {
        ref: handleContentRef
      })), children && /*#__PURE__*/_jsx(TreeItemGroup, _extends({
        as: GroupTransition
      }, groupTransitionProps, {
        children: children
      }))]
    }))
  });
});
process.env.NODE_ENV !== "production" ? TreeItem.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // | To update them edit the TypeScript types and run "pnpm proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  className: PropTypes.string,
  /**
   * The component used to render the content of the item.
   * @deprecated Consider using the `<TreeItem2 />` component or the `useTreeItem2` hook instead. For more details, see https://mui.com/x/react-tree-view/tree-item-customization/.
   * @default TreeItemContent
   */
  ContentComponent: elementTypeAcceptingRef,
  /**
   * Props applied to ContentComponent.
   * @deprecated Consider using the `<TreeItem2 />` component or the `useTreeItem2` hook instead. For more details, see https://mui.com/x/react-tree-view/tree-item-customization/.
   */
  ContentProps: PropTypes.object,
  /**
   * If `true`, the item is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * The id of the item.
   */
  itemId: PropTypes.string.isRequired,
  /**
   * The Tree Item label.
   */
  label: PropTypes.node,
  /**
   * This prop isn't supported.
   * Use the `onItemFocus` callback on the tree if you need to monitor a item's focus.
   */
  onFocus: unsupportedProp,
  /**
   * Callback fired when a key of the keyboard is pressed on the item.
   */
  onKeyDown: PropTypes.func,
  /**
   * The props used for each component slot.
   * @default {}
   */
  slotProps: PropTypes.object,
  /**
   * Overridable component slots.
   * @default {}
   */
  slots: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} : void 0;