import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { __ } from "@wordpress/i18n";
import { InspectorControls, useBlockProps } from "@wordpress/block-editor";
import {
  ToggleControl,
  TextControl,
  SelectControl,
  __experimentalToolsPanel as ToolsPanel,
  __experimentalToolsPanelItem as ToolsPanelItem,
  Spinner
} from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { store as coreStore } from "@wordpress/core-data";
import { useEffect, useState, RawHTML } from "@wordpress/element";
import { useServerSideRender } from "@wordpress/server-side-render";
import { useToolsPanelDropdownMenuProps } from "../utils/hooks";
const separatorDefaultValue = "/";
const typeDefaultValue = "auto";
const BREADCRUMB_TYPES = {
  auto: {
    help: __(
      "Try to automatically determine the best type of breadcrumb for the template."
    )
  },
  postWithAncestors: {
    help: __(
      "Shows breadcrumbs based on post hierarchy. Only works for hierarchical post types."
    ),
    placeholderItems: [__("Ancestor"), __("Parent")]
  },
  postWithTerms: {
    help: __(
      "Shows breadcrumbs based on taxonomy terms. Chooses the first taxonomy with assigned terms and includes ancestors if the taxonomy is hierarchical."
    ),
    placeholderItems: [__("Category")]
  }
};
function BreadcrumbEdit({
  attributes,
  setAttributes,
  context: { postId, postType, templateSlug }
}) {
  const { separator, showHomeLink, type } = attributes;
  const { post, isPostTypeHierarchical, hasTermsAssigned, isLoading } = useSelect(
    (select) => {
      if (!postType) {
        return {};
      }
      const _post = select(coreStore).getEntityRecord(
        "postType",
        postType,
        postId
      );
      const postTypeObject = select(coreStore).getPostType(postType);
      const postTypeHasTaxonomies = postTypeObject && postTypeObject.taxonomies.length;
      let taxonomies;
      if (postTypeHasTaxonomies) {
        taxonomies = select(coreStore).getTaxonomies({
          type: postType,
          per_page: -1
        });
      }
      return {
        post: _post,
        isPostTypeHierarchical: postTypeObject?.hierarchical,
        hasTermsAssigned: _post && (taxonomies || []).filter(
          ({ visibility }) => visibility?.publicly_queryable
        ).some((taxonomy) => {
          return !!_post[taxonomy.rest_base]?.length;
        }),
        isLoading: !_post || !postTypeObject || postTypeHasTaxonomies && !taxonomies
      };
    },
    [postType, postId]
  );
  const [invalidationKey, setInvalidationKey] = useState(0);
  useEffect(() => {
    setInvalidationKey((c) => c + 1);
  }, [post]);
  const blockProps = useBlockProps();
  const dropdownMenuProps = useToolsPanelDropdownMenuProps();
  const { content } = useServerSideRender({
    attributes,
    skipBlockSupportAttributes: true,
    block: "core/breadcrumbs",
    urlQueryArgs: { post_id: postId, invalidationKey }
  });
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { ...blockProps, children: /* @__PURE__ */ jsx(Spinner, {}) });
  }
  let breadcrumbsType;
  const isSpecificSupportedTypeSet = [
    "postWithAncestors",
    "postWithTerms"
  ].includes(type);
  if (isSpecificSupportedTypeSet) {
    breadcrumbsType = type;
  } else {
    breadcrumbsType = isPostTypeHierarchical ? "postWithAncestors" : "postWithTerms";
  }
  let placeholder = null;
  const showPlaceholder = !postId || !postType || // When `templateSlug` is set only show placeholder if the post type is not.
  // This is needed because when we are showing the template in post editor we
  // want to show the real breadcrumbs if we have the post type.
  templateSlug && !postType || breadcrumbsType === "postWithAncestors" && !isPostTypeHierarchical || breadcrumbsType === "postWithTerms" && !hasTermsAssigned;
  if (showPlaceholder) {
    const placeholderItems = [
      showHomeLink && __("Home"),
      // For now if we are adding this in a template show a generic placeholder.
      ...templateSlug && !isSpecificSupportedTypeSet ? [__("Page")] : BREADCRUMB_TYPES[breadcrumbsType].placeholderItems
    ].filter(Boolean);
    placeholder = /* @__PURE__ */ jsx(
      "nav",
      {
        style: {
          "--separator": `'${separator}'`
        },
        inert: "true",
        children: /* @__PURE__ */ jsxs("ol", { children: [
          placeholderItems.map((text, index) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("a", { href: `#breadcrumbs-pseudo-link-${index}`, children: text }) }, index)),
          /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("span", { "aria-current": "page", children: __("Current") }) })
        ] })
      }
    );
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(InspectorControls, { children: /* @__PURE__ */ jsxs(
      ToolsPanel,
      {
        label: __("Settings"),
        resetAll: () => {
          setAttributes({
            separator: separatorDefaultValue,
            showHomeLink: true,
            type: typeDefaultValue
          });
        },
        dropdownMenuProps,
        children: [
          /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              label: __("Type"),
              isShownByDefault: true,
              hasValue: () => type !== typeDefaultValue,
              onDeselect: () => setAttributes({
                type: typeDefaultValue
              }),
              children: /* @__PURE__ */ jsx(
                SelectControl,
                {
                  __nextHasNoMarginBottom: true,
                  __next40pxDefaultSize: true,
                  label: __("Type"),
                  value: type,
                  onChange: (value) => setAttributes({ type: value }),
                  options: [
                    {
                      label: __("Auto"),
                      value: "auto"
                    },
                    {
                      label: __("Post with ancestors"),
                      value: "postWithAncestors"
                    },
                    {
                      label: __("Post with terms"),
                      value: "postWithTerms"
                    }
                  ],
                  help: BREADCRUMB_TYPES[type].help
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              label: __("Show home link"),
              isShownByDefault: true,
              hasValue: () => !showHomeLink,
              onDeselect: () => setAttributes({
                showHomeLink: true
              }),
              children: /* @__PURE__ */ jsx(
                ToggleControl,
                {
                  __nextHasNoMarginBottom: true,
                  label: __("Show home link"),
                  onChange: (value) => setAttributes({ showHomeLink: value }),
                  checked: showHomeLink
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            ToolsPanelItem,
            {
              label: __("Separator"),
              isShownByDefault: true,
              hasValue: () => separator !== separatorDefaultValue,
              onDeselect: () => setAttributes({
                separator: separatorDefaultValue
              }),
              children: /* @__PURE__ */ jsx(
                TextControl,
                {
                  __nextHasNoMarginBottom: true,
                  __next40pxDefaultSize: true,
                  autoComplete: "off",
                  label: __("Separator"),
                  value: separator,
                  onChange: (value) => setAttributes({ separator: value }),
                  onBlur: () => {
                    if (!separator) {
                      setAttributes({
                        separator: separatorDefaultValue
                      });
                    }
                  }
                }
              )
            }
          )
        ]
      }
    ) }),
    /* @__PURE__ */ jsx("div", { ...blockProps, children: showPlaceholder ? placeholder : /* @__PURE__ */ jsx(RawHTML, { inert: "true", children: content }) })
  ] });
}
export {
  BreadcrumbEdit as default
};
//# sourceMappingURL=edit.js.map
