// packages/block-editor/src/components/inserter/block-types-tab.js
import { __, _x } from "@wordpress/i18n";
import { useMemo, useEffect, forwardRef } from "@wordpress/element";
import { useAsyncList } from "@wordpress/compose";
import BlockTypesList from "../block-types-list";
import InserterPanel from "./panel";
import useBlockTypesState from "./hooks/use-block-types-state";
import InserterListbox from "../inserter-listbox";
import { orderBy } from "../../utils/sorting";
import InserterNoResults from "./no-results";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var getBlockNamespace = (item) => item.name.split("/")[0];
var MAX_SUGGESTED_ITEMS = 6;
var EMPTY_ARRAY = [];
function BlockTypesTabPanel({
  items,
  collections,
  categories,
  onSelectItem,
  onHover,
  showMostUsedBlocks,
  className
}) {
  const suggestedItems = useMemo(() => {
    return orderBy(items, "frecency", "desc").slice(
      0,
      MAX_SUGGESTED_ITEMS
    );
  }, [items]);
  const uncategorizedItems = useMemo(() => {
    return items.filter((item) => !item.category);
  }, [items]);
  const itemsPerCollection = useMemo(() => {
    const result = { ...collections };
    Object.keys(collections).forEach((namespace) => {
      result[namespace] = items.filter(
        (item) => getBlockNamespace(item) === namespace
      );
      if (result[namespace].length === 0) {
        delete result[namespace];
      }
    });
    return result;
  }, [items, collections]);
  useEffect(() => () => onHover(null), []);
  const currentlyRenderedCategories = useAsyncList(categories);
  const didRenderAllCategories = categories.length === currentlyRenderedCategories.length;
  const collectionEntries = useMemo(() => {
    return Object.entries(collections);
  }, [collections]);
  const currentlyRenderedCollections = useAsyncList(
    didRenderAllCategories ? collectionEntries : EMPTY_ARRAY
  );
  return /* @__PURE__ */ jsxs("div", { className, children: [
    showMostUsedBlocks && // Only show the most used blocks if the total amount of block
    // is larger than 1 row, otherwise it is not so useful.
    items.length > 3 && !!suggestedItems.length && /* @__PURE__ */ jsx(InserterPanel, { title: _x("Most used", "blocks"), children: /* @__PURE__ */ jsx(
      BlockTypesList,
      {
        items: suggestedItems,
        onSelect: onSelectItem,
        onHover,
        label: _x("Most used", "blocks")
      }
    ) }),
    currentlyRenderedCategories.map((category) => {
      const categoryItems = items.filter(
        (item) => item.category === category.slug
      );
      if (!categoryItems || !categoryItems.length) {
        return null;
      }
      return /* @__PURE__ */ jsx(
        InserterPanel,
        {
          title: category.title,
          icon: category.icon,
          children: /* @__PURE__ */ jsx(
            BlockTypesList,
            {
              items: categoryItems,
              onSelect: onSelectItem,
              onHover,
              label: category.title
            }
          )
        },
        category.slug
      );
    }),
    didRenderAllCategories && uncategorizedItems.length > 0 && /* @__PURE__ */ jsx(
      InserterPanel,
      {
        className: "block-editor-inserter__uncategorized-blocks-panel",
        title: __("Uncategorized"),
        children: /* @__PURE__ */ jsx(
          BlockTypesList,
          {
            items: uncategorizedItems,
            onSelect: onSelectItem,
            onHover,
            label: __("Uncategorized")
          }
        )
      }
    ),
    currentlyRenderedCollections.map(
      ([namespace, collection]) => {
        const collectionItems = itemsPerCollection[namespace];
        if (!collectionItems || !collectionItems.length) {
          return null;
        }
        return /* @__PURE__ */ jsx(
          InserterPanel,
          {
            title: collection.title,
            icon: collection.icon,
            children: /* @__PURE__ */ jsx(
              BlockTypesList,
              {
                items: collectionItems,
                onSelect: onSelectItem,
                onHover,
                label: collection.title
              }
            )
          },
          namespace
        );
      }
    )
  ] });
}
function BlockTypesTab({ rootClientId, onInsert, onHover, showMostUsedBlocks }, ref) {
  const [items, categories, collections, onSelectItem] = useBlockTypesState(
    rootClientId,
    onInsert
  );
  if (!items.length) {
    return /* @__PURE__ */ jsx(InserterNoResults, {});
  }
  const itemsForCurrentRoot = [];
  const itemsRemaining = [];
  for (const item of items) {
    if (item.category === "reusable") {
      continue;
    }
    if (item.isAllowedInCurrentRoot) {
      itemsForCurrentRoot.push(item);
    } else {
      itemsRemaining.push(item);
    }
  }
  return /* @__PURE__ */ jsx(InserterListbox, { children: /* @__PURE__ */ jsxs("div", { ref, children: [
    !!itemsForCurrentRoot.length && /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(
      BlockTypesTabPanel,
      {
        items: itemsForCurrentRoot,
        categories,
        collections,
        onSelectItem,
        onHover,
        showMostUsedBlocks,
        className: "block-editor-inserter__insertable-blocks-at-selection"
      }
    ) }),
    /* @__PURE__ */ jsx(
      BlockTypesTabPanel,
      {
        items: itemsRemaining,
        categories,
        collections,
        onSelectItem,
        onHover,
        showMostUsedBlocks,
        className: "block-editor-inserter__all-blocks"
      }
    )
  ] }) });
}
var block_types_tab_default = forwardRef(BlockTypesTab);
export {
  BlockTypesTab,
  BlockTypesTabPanel,
  block_types_tab_default as default
};
//# sourceMappingURL=block-types-tab.js.map
