import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import clsx from "clsx";
import { createBlock } from "@wordpress/blocks";
import { useSelect, useDispatch } from "@wordpress/data";
import { ToolbarButton, ToolbarGroup } from "@wordpress/components";
import { displayShortcut, isKeyboardEvent } from "@wordpress/keycodes";
import { __ } from "@wordpress/i18n";
import {
  BlockControls,
  InspectorControls,
  RichText,
  useBlockProps,
  store as blockEditorStore,
  getColorClassName,
  useInnerBlocksProps,
  useBlockEditingMode
} from "@wordpress/block-editor";
import { isURL, prependHTTP } from "@wordpress/url";
import { useState, useEffect, useRef, useCallback } from "@wordpress/element";
import { decodeEntities } from "@wordpress/html-entities";
import { link as linkIcon, addSubmenu } from "@wordpress/icons";
import { store as coreStore } from "@wordpress/core-data";
import { useMergeRefs, usePrevious } from "@wordpress/compose";
import { getColors } from "../navigation/edit/utils";
import { Controls, LinkUI, updateAttributes, useEntityBinding } from "./shared";
const DEFAULT_BLOCK = { name: "core/navigation-link" };
const NESTING_BLOCK_NAMES = [
  "core/navigation-link",
  "core/navigation-submenu"
];
const useIsDraggingWithin = (elementRef) => {
  const [isDraggingWithin, setIsDraggingWithin] = useState(false);
  useEffect(() => {
    const { ownerDocument } = elementRef.current;
    function handleDragStart(event) {
      handleDragEnter(event);
    }
    function handleDragEnd() {
      setIsDraggingWithin(false);
    }
    function handleDragEnter(event) {
      if (elementRef.current.contains(event.target)) {
        setIsDraggingWithin(true);
      } else {
        setIsDraggingWithin(false);
      }
    }
    ownerDocument.addEventListener("dragstart", handleDragStart);
    ownerDocument.addEventListener("dragend", handleDragEnd);
    ownerDocument.addEventListener("dragenter", handleDragEnter);
    return () => {
      ownerDocument.removeEventListener("dragstart", handleDragStart);
      ownerDocument.removeEventListener("dragend", handleDragEnd);
      ownerDocument.removeEventListener("dragenter", handleDragEnter);
    };
  }, [elementRef]);
  return isDraggingWithin;
};
const useIsInvalidLink = (kind, type, id, enabled) => {
  const isPostType = kind === "post-type" || type === "post" || type === "page";
  const hasId = Number.isInteger(id);
  const blockEditingMode = useBlockEditingMode();
  const { postStatus, isDeleted } = useSelect(
    (select) => {
      if (!isPostType) {
        return { postStatus: null, isDeleted: false };
      }
      if (blockEditingMode === "disabled" || !enabled) {
        return { postStatus: null, isDeleted: false };
      }
      const { getEntityRecord, hasFinishedResolution } = select(coreStore);
      const entityRecord = getEntityRecord("postType", type, id);
      const hasResolved = hasFinishedResolution("getEntityRecord", [
        "postType",
        type,
        id
      ]);
      const deleted = hasResolved && entityRecord === void 0;
      return {
        postStatus: entityRecord?.status,
        isDeleted: deleted
      };
    },
    [isPostType, blockEditingMode, enabled, type, id]
  );
  const isInvalid = isPostType && hasId && (isDeleted || postStatus && "trash" === postStatus);
  const isDraft = "draft" === postStatus;
  return [isInvalid, isDraft];
};
function getMissingText(type) {
  let missingText = "";
  switch (type) {
    case "post":
      missingText = __("Select post");
      break;
    case "page":
      missingText = __("Select page");
      break;
    case "category":
      missingText = __("Select category");
      break;
    case "tag":
      missingText = __("Select tag");
      break;
    default:
      missingText = __("Add link");
  }
  return missingText;
}
function NavigationLinkEdit({
  attributes,
  isSelected,
  setAttributes,
  insertBlocksAfter,
  mergeBlocks,
  onReplace,
  context,
  clientId
}) {
  const { id, label, type, url, description, kind, metadata } = attributes;
  const { maxNestingLevel } = context;
  const {
    replaceBlock,
    __unstableMarkNextChangeAsNotPersistent,
    selectBlock
  } = useDispatch(blockEditorStore);
  const [isLinkOpen, setIsLinkOpen] = useState(isSelected && !url);
  const [popoverAnchor, setPopoverAnchor] = useState(null);
  const listItemRef = useRef(null);
  const isDraggingWithin = useIsDraggingWithin(listItemRef);
  const itemLabelPlaceholder = __("Add label\u2026");
  const ref = useRef();
  const linkUIref = useRef();
  const prevUrl = usePrevious(url);
  const isNewLink = useRef(!url);
  const {
    isAtMaxNesting,
    isTopLevelLink,
    isParentOfSelectedBlock,
    hasChildren,
    validateLinkStatus,
    parentBlockClientId
  } = useSelect(
    (select) => {
      const {
        getBlockCount,
        getBlockName,
        getBlockRootClientId,
        hasSelectedInnerBlock,
        getBlockParentsByBlockName,
        getSelectedBlockClientId
      } = select(blockEditorStore);
      const rootClientId = getBlockRootClientId(clientId);
      const parentBlockName = getBlockName(rootClientId);
      const isTopLevel = parentBlockName === "core/navigation";
      const selectedBlockClientId = getSelectedBlockClientId();
      const rootNavigationClientId = isTopLevel ? rootClientId : getBlockParentsByBlockName(
        clientId,
        "core/navigation"
      )[0];
      const parentBlockId = parentBlockName === "core/navigation-submenu" ? rootClientId : rootNavigationClientId;
      const enableLinkStatusValidation = selectedBlockClientId === rootNavigationClientId || hasSelectedInnerBlock(rootNavigationClientId, true);
      return {
        isAtMaxNesting: getBlockParentsByBlockName(clientId, NESTING_BLOCK_NAMES).length >= maxNestingLevel,
        isTopLevelLink: isTopLevel,
        isParentOfSelectedBlock: hasSelectedInnerBlock(
          clientId,
          true
        ),
        hasChildren: !!getBlockCount(clientId),
        validateLinkStatus: enableLinkStatusValidation,
        parentBlockClientId: parentBlockId
      };
    },
    [clientId, maxNestingLevel]
  );
  const { getBlocks } = useSelect(blockEditorStore);
  const {
    clearBinding,
    createBinding,
    hasUrlBinding,
    isBoundEntityAvailable
  } = useEntityBinding({
    clientId,
    attributes
  });
  const [isInvalid, isDraft] = useIsInvalidLink(
    kind,
    type,
    id,
    validateLinkStatus
  );
  const transformToSubmenu = useCallback(() => {
    let innerBlocks = getBlocks(clientId);
    if (innerBlocks.length === 0) {
      innerBlocks = [createBlock("core/navigation-link")];
      selectBlock(innerBlocks[0].clientId);
    }
    const newSubmenu = createBlock(
      "core/navigation-submenu",
      attributes,
      innerBlocks
    );
    replaceBlock(clientId, newSubmenu);
  }, [getBlocks, clientId, selectBlock, replaceBlock, attributes]);
  useEffect(() => {
    if (isNewLink.current && isSelected && !url) {
      selectBlock(parentBlockClientId);
    }
  }, []);
  useEffect(() => {
    if (hasChildren) {
      __unstableMarkNextChangeAsNotPersistent();
      transformToSubmenu();
    }
  }, [
    hasChildren,
    __unstableMarkNextChangeAsNotPersistent,
    transformToSubmenu
  ]);
  useEffect(() => {
    if (!prevUrl && url && isLinkOpen && isURL(prependHTTP(label)) && /^.+\.[a-z]+/.test(label)) {
      selectLabelText();
    }
  }, [prevUrl, url, isLinkOpen, label]);
  function selectLabelText() {
    ref.current.focus();
    const { ownerDocument } = ref.current;
    const { defaultView } = ownerDocument;
    const selection = defaultView.getSelection();
    const range = ownerDocument.createRange();
    range.selectNodeContents(ref.current);
    selection.removeAllRanges();
    selection.addRange(range);
  }
  function removeLink() {
    setAttributes({
      url: void 0,
      label: void 0,
      id: void 0,
      kind: void 0,
      type: void 0,
      opensInNewTab: false
    });
    setIsLinkOpen(false);
  }
  const {
    textColor,
    customTextColor,
    backgroundColor,
    customBackgroundColor
  } = getColors(context, !isTopLevelLink);
  function onKeyDown(event) {
    if (isKeyboardEvent.primary(event, "k")) {
      event.preventDefault();
      event.stopPropagation();
      setIsLinkOpen(true);
    }
  }
  const blockProps = useBlockProps({
    ref: useMergeRefs([setPopoverAnchor, listItemRef]),
    className: clsx("wp-block-navigation-item", {
      "is-editing": isSelected || isParentOfSelectedBlock,
      "is-dragging-within": isDraggingWithin,
      "has-link": !!url,
      "has-child": hasChildren,
      "has-text-color": !!textColor || !!customTextColor,
      [getColorClassName("color", textColor)]: !!textColor,
      "has-background": !!backgroundColor || customBackgroundColor,
      [getColorClassName("background-color", backgroundColor)]: !!backgroundColor
    }),
    style: {
      color: !textColor && customTextColor,
      backgroundColor: !backgroundColor && customBackgroundColor
    },
    onKeyDown
  });
  const innerBlocksProps = useInnerBlocksProps(
    {
      ...blockProps,
      className: "remove-outline"
      // Remove the outline from the inner blocks container.
    },
    {
      defaultBlock: DEFAULT_BLOCK,
      directInsert: true,
      renderAppender: false
    }
  );
  if (!url || isInvalid || isDraft || hasUrlBinding && !isBoundEntityAvailable) {
    blockProps.onClick = () => {
      setIsLinkOpen(true);
    };
  }
  const classes = clsx("wp-block-navigation-item__content", {
    "wp-block-navigation-link__placeholder": !url || isInvalid || isDraft || hasUrlBinding && !isBoundEntityAvailable
  });
  const missingText = getMissingText(type);
  const placeholderText = `(${isInvalid ? __("Invalid") : __("Draft")})`;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(BlockControls, { children: /* @__PURE__ */ jsxs(ToolbarGroup, { children: [
      /* @__PURE__ */ jsx(
        ToolbarButton,
        {
          name: "link",
          icon: linkIcon,
          title: __("Link"),
          shortcut: displayShortcut.primary("k"),
          onClick: () => {
            setIsLinkOpen(true);
          }
        }
      ),
      !isAtMaxNesting && /* @__PURE__ */ jsx(
        ToolbarButton,
        {
          name: "submenu",
          icon: addSubmenu,
          title: __("Add submenu"),
          onClick: transformToSubmenu
        }
      )
    ] }) }),
    /* @__PURE__ */ jsx(InspectorControls, { children: /* @__PURE__ */ jsx(
      Controls,
      {
        attributes,
        setAttributes,
        clientId
      }
    ) }),
    /* @__PURE__ */ jsxs("div", { ...blockProps, children: [
      /* @__PURE__ */ jsxs("a", { className: classes, children: [
        !url && !metadata?.bindings?.url ? /* @__PURE__ */ jsx("div", { className: "wp-block-navigation-link__placeholder-text", children: /* @__PURE__ */ jsx("span", { children: missingText }) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          !isInvalid && !isDraft && /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(
              RichText,
              {
                ref,
                identifier: "label",
                className: "wp-block-navigation-item__label",
                value: label,
                onChange: (labelValue) => setAttributes({
                  label: labelValue
                }),
                onMerge: mergeBlocks,
                onReplace,
                __unstableOnSplitAtEnd: () => insertBlocksAfter(
                  createBlock(
                    "core/navigation-link"
                  )
                ),
                "aria-label": __(
                  "Navigation link text"
                ),
                placeholder: itemLabelPlaceholder,
                withoutInteractiveFormatting: true
              }
            ),
            description && /* @__PURE__ */ jsx("span", { className: "wp-block-navigation-item__description", children: description })
          ] }),
          (isInvalid || isDraft) && /* @__PURE__ */ jsx(
            "div",
            {
              className: clsx(
                "wp-block-navigation-link__placeholder-text",
                "wp-block-navigation-link__label",
                {
                  "is-invalid": isInvalid,
                  "is-draft": isDraft
                }
              ),
              children: /* @__PURE__ */ jsx("span", {
                // Some attributes are stored in an escaped form. It's a legacy issue.
                // Ideally they would be stored in a raw, unescaped form.
                // Unescape is used here to "recover" the escaped characters
                // so they display without encoding.
                // See `updateAttributes` for more details.
                children: `${decodeEntities(label)} ${isInvalid || isDraft ? placeholderText : ""}`.trim()
              })
            }
          )
        ] }),
        isLinkOpen && /* @__PURE__ */ jsx(
          LinkUI,
          {
            ref: linkUIref,
            clientId,
            link: attributes,
            onClose: () => {
              setIsLinkOpen(false);
              if (!url && !hasUrlBinding) {
                onReplace([]);
              } else if (isNewLink.current) {
                selectBlock(clientId);
              }
            },
            anchor: popoverAnchor,
            onRemove: removeLink,
            onChange: (updatedValue) => {
              const {
                isEntityLink,
                attributes: updatedAttributes
              } = updateAttributes(
                updatedValue,
                setAttributes,
                attributes
              );
              if (isEntityLink) {
                createBinding(updatedAttributes);
              } else {
                clearBinding(updatedAttributes);
              }
            }
          }
        )
      ] }),
      /* @__PURE__ */ jsx("div", { ...innerBlocksProps })
    ] })
  ] });
}
export {
  NavigationLinkEdit as default
};
//# sourceMappingURL=edit.js.map
