import { isValidElement, Children } from "preact/compat";
import { Item, Section } from "../react-aria"; // from react-stately
import { TextField } from "../TextField";
import { getOptionId } from "../Dropdown/DropdownMenuOption";
import { jsx as _jsx } from "preact/compat/jsx-runtime";
import { createElement as _createElement } from "preact/compat";
export function renderReactStatelyItems(items, itemToString) {
  const renderItem = item => {
    const {
      id,
      name,
      children,
      ...extraAttrs
    } = item;
    return /*#__PURE__*/_jsx(Item, {
      textValue: name ?? itemToString?.(item),
      ...extraAttrs,
      children: children ?? name
    }, id);
  };
  return items.map((item, index) => {
    if ('label' in item && 'items' in item) {
      const {
        id,
        label,
        items,
        ...extraAttrs
      } = item;
      const groupKey = `group-${label.replace(/\s+/g, '-').toLowerCase()}-${index}`;
      return /*#__PURE__*/_createElement(Section, {
        ...extraAttrs,
        key: groupKey,
        title: label
      }, items.map(renderItem));
    } else {
      return renderItem(item);
    }
  });
}
export function renderStatusMessage(message) {
  return /*#__PURE__*/_jsx("li", {
    className: "ds-c-autocomplete__menu-item-message",
    role: "option",
    children: message
  });
}

/**
 * Determine if a React component is a TextField
 */
function isTextField(child) {
  if (!child || !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;
}
export const findItemById = (id, items) => {
  for (const item of items) {
    if ('items' in item) {
      const match = item.items.find(child => child.id === id);
      if (match) return match;
    } else {
      if (item.id === id) return item;
    }
  }
};