import { isValidElement, Children } from 'react';
import { Item } from '../react-aria'; // from react-stately
import { TextField } from '../TextField';
import { getOptionId } from '../Dropdown/DropdownMenuOption';
import { createElement as _createElement } from "react";
import { jsx as _jsx } from "react/jsx-runtime";
export function renderReactStatelyItems(items, itemToString) {
  return items.map(item => {
    const {
      id,
      name,
      children,
      isResult,
      ...extraAttrs
    } = item;
    return /*#__PURE__*/_createElement(Item, {
      ...extraAttrs,
      textValue: name ?? itemToString?.(item),
      key: id
    }, children ?? name);
  });
}
export function renderStatusMessage(message) {
  return /*#__PURE__*/_jsx("li", {
    "aria-selected": "false",
    className: "ds-c-autocomplete__menu-item-message",
    role: "option",
    children: message
  });
}

/**
 * Determine if a React component is a TextField
 */
function isTextField(child) {
  if (!child || ! /*#__PURE__*/isValidElement(child)) {
    return false;
  }

  // Check child.type first and as a fallback, check child.type.displayName follow by child.type.name
  const componentName = child.type?.displayName || child.type?.name;
  return child.type === TextField || componentName === 'TextField';
}
export function getTextFieldChild(children) {
  let textField;
  Children.forEach(children, child => {
    if (isTextField(child)) {
      textField = child;
    }
  });
  return textField;
}

/**
 * Assumes that it will find the item, so only use in cases where react-aria
 * would define an aria-activedescendent
 */
export function getActiveDescendant(rootId, state, items) {
  const index = (items ?? []).findIndex(item => state.selectionManager.focusedKey === item.id);
  return getOptionId(rootId, index);
}

/**
 * Mutates the original object, deleting properties whose values are undefined.
 * Returns the object.
 */
export function removeUndefined(obj) {
  Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]);
  return obj;
}