"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/block-library/src/query/edit/inspector-controls/parent-control.js
var parent_control_exports = {};
__export(parent_control_exports, {
  default: () => parent_control_default
});
module.exports = __toCommonJS(parent_control_exports);
var import_i18n = require("@wordpress/i18n");
var import_components = require("@wordpress/components");
var import_data = require("@wordpress/data");
var import_core_data = require("@wordpress/core-data");
var import_element = require("@wordpress/element");
var import_compose = require("@wordpress/compose");
var import_utils = require("../../utils");
var import_jsx_runtime = require("react/jsx-runtime");
var EMPTY_ARRAY = [];
var BASE_QUERY = {
  order: "asc",
  _fields: "id,title",
  context: "view"
};
function ParentControl({ parents, postType, onChange }) {
  const [search, setSearch] = (0, import_element.useState)("");
  const [value, setValue] = (0, import_element.useState)(EMPTY_ARRAY);
  const [suggestions, setSuggestions] = (0, import_element.useState)(EMPTY_ARRAY);
  const debouncedSearch = (0, import_compose.useDebounce)(setSearch, 250);
  const { searchResults, searchHasResolved } = (0, import_data.useSelect)(
    (select) => {
      if (!search) {
        return { searchResults: EMPTY_ARRAY, searchHasResolved: true };
      }
      const { getEntityRecords, hasFinishedResolution } = select(import_core_data.store);
      const selectorArgs = [
        "postType",
        postType,
        {
          ...BASE_QUERY,
          search,
          orderby: "relevance",
          exclude: parents,
          per_page: 20
        }
      ];
      return {
        searchResults: getEntityRecords(...selectorArgs),
        searchHasResolved: hasFinishedResolution(
          "getEntityRecords",
          selectorArgs
        )
      };
    },
    [search, postType, parents]
  );
  const currentParents = (0, import_data.useSelect)(
    (select) => {
      if (!parents?.length) {
        return EMPTY_ARRAY;
      }
      const { getEntityRecords } = select(import_core_data.store);
      return getEntityRecords("postType", postType, {
        ...BASE_QUERY,
        include: parents,
        per_page: parents.length
      });
    },
    [parents, postType]
  );
  (0, import_element.useEffect)(() => {
    if (!parents?.length) {
      setValue(EMPTY_ARRAY);
    }
    if (!currentParents?.length) {
      return;
    }
    const currentParentsInfo = (0, import_utils.getEntitiesInfo)(
      (0, import_utils.mapToIHasNameAndId)(currentParents, "title.rendered")
    );
    const sanitizedValue = parents.reduce((accumulator, id) => {
      const entity = currentParentsInfo.mapById[id];
      if (entity) {
        accumulator.push({
          id,
          value: entity.name
        });
      }
      return accumulator;
    }, []);
    setValue(sanitizedValue);
  }, [parents, currentParents]);
  const entitiesInfo = (0, import_element.useMemo)(() => {
    if (!searchResults?.length) {
      return EMPTY_ARRAY;
    }
    return (0, import_utils.getEntitiesInfo)(
      (0, import_utils.mapToIHasNameAndId)(searchResults, "title.rendered")
    );
  }, [searchResults]);
  (0, import_element.useEffect)(() => {
    if (!searchHasResolved) {
      return;
    }
    setSuggestions(entitiesInfo.names);
  }, [entitiesInfo.names, searchHasResolved]);
  const getIdByValue = (entitiesMappedByName, entity) => {
    const id = entity?.id || entitiesMappedByName?.[entity]?.id;
    if (id) {
      return id;
    }
  };
  const onParentChange = (newValue) => {
    const ids = Array.from(
      newValue.reduce((accumulator, entity) => {
        const id = getIdByValue(entitiesInfo.mapByName, entity);
        if (id) {
          accumulator.add(id);
        }
        return accumulator;
      }, /* @__PURE__ */ new Set())
    );
    setSuggestions(EMPTY_ARRAY);
    onChange({ parents: ids });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_components.FormTokenField,
    {
      __next40pxDefaultSize: true,
      label: (0, import_i18n.__)("Parents"),
      value,
      onInputChange: debouncedSearch,
      suggestions,
      onChange: onParentChange,
      __experimentalShowHowTo: false,
      __nextHasNoMarginBottom: true
    }
  );
}
var parent_control_default = ParentControl;
//# sourceMappingURL=parent-control.js.map
