import classNames from "classnames";
import React, { Suspense, useContext, useEffect, useRef, useState } from "react";
import { toggleQuickActionsModal } from "./../../ricos-common-plugins/quick-actions/toggle-quick-actions-modal/toggle-quick-actions-modal.js";
import {
  EMOJI_TYPE,
  TIPTAP_COLLAPSIBLE_ITEM_TITLE_TYPE,
  TIPTAP_COLLAPSIBLE_ITEM_TYPE,
  TIPTAP_COLLAPSIBLE_LIST_TYPE
} from "./../../ricos-content/index.js";
import {
  EditorContext,
  EditorQueryContext,
  ModalServiceContext,
  PluginsEventsContext,
  RicosContext
} from "./../../ricos-context/index.js";
import { Node_Type } from "./../../ricos-schema/next-schema/index.js";
import { findParentNodeClosestToPos } from "./../../tiptap/index.js";
import { ExpandCollapseButton } from "../components/expand-collapse-button.js";
import { NewPairButton } from "../components/new-pair-button.js";
import {
  COLLAPSIBLE_LIST_ITEM,
  COLLAPSIBLE_LIST_ITEM_BODY,
  COLLAPSIBLE_LIST_ITEM_TITLE,
  ROOT
} from "../data-hooks.js";
import { DndIcon } from "../icons/index.js";
import collapsibleListStyles from "../statics/styles/collapsible-list-component-scss.js";
import collapsibleListItemStyles from "../statics/styles/collapsible-list-pair-scss.js";
import { isInCollapsibleList } from "./utils.js";
const FloatingAddPluginMenu = React.lazy(() => import("./lazy-floating-add-plugin-menu.js"));
const preventFocusJumpToFirstNode = (event) => {
  event.preventDefault();
  event.stopPropagation();
};
const CollapsibleList = ({
  editor,
  node,
  NodeViewContent,
  componentData,
  getPos
}) => {
  const { t, languageDir } = useContext(RicosContext);
  const editorQuery = useContext(EditorQueryContext);
  const pluginsEvents = useContext(PluginsEventsContext);
  const { isNodeSelected } = editorQuery.query;
  const styles = collapsibleListStyles;
  const pos = getPos();
  const [isCollapsibleListSelected, setIsCollapsibleListSelected] = useState(
    isNodeSelected(node.attrs.id)
  );
  const direction = componentData?.direction || languageDir;
  useEffect(() => {
    editor.on("selectionUpdate", handleSelectionUpdate);
    return () => {
      editor.off("selectionUpdate", handleSelectionUpdate);
    };
  }, []);
  useEffect(() => {
    if (!isCollapsibleListSelected) {
      pluginsEvents?.publishPluginLayoutShift({ nodeId: node.attrs.id });
    }
  }, [isCollapsibleListSelected]);
  const handleSelectionUpdate = () => {
    setIsCollapsibleListSelected(isNodeSelected(node.attrs.id));
  };
  const addNewPair = (e) => {
    e.preventDefault();
    e.stopPropagation();
    editor.commands.addCollapsibleListItem(pos + node.nodeSize);
  };
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: classNames(styles[direction.toLowerCase()], styles.listDimensions),
      "data-hook": ROOT
    },
    /* @__PURE__ */ React.createElement(NodeViewContent, { className: classNames(styles[direction.toLowerCase()], styles.item) }),
    isCollapsibleListSelected && /* @__PURE__ */ React.createElement(
      NewPairButton,
      {
        onClick: addNewPair,
        label: t("CollapsibleList_ShownText_Add_Placeholder")
      }
    )
  );
};
const CollapsibleListItem = ({ editor, node, NodeViewContent }) => {
  const styles = collapsibleListItemStyles;
  const { t, languageDir } = useContext(RicosContext);
  const {
    adapter: { tiptapEditor }
  } = useContext(EditorContext);
  const $pos = editor.state.selection.$to;
  const inCollapsibleList = isInCollapsibleList($pos, node.attrs.id);
  const isExpanded = !!node.attrs.isExpanded;
  const toggleCollapsibleItem = () => {
    tiptapEditor.chain().focus().toggleCollapsibleItem(node.attrs.id);
  };
  const [mouseDown, setMouseDown] = useState(false);
  const dir = findParentNodeClosestToPos($pos, (node2) => node2.type.name === TIPTAP_COLLAPSIBLE_LIST_TYPE)?.node?.attrs?.direction || languageDir.toUpperCase();
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: styles.itemContainer,
      "data-hook": `${COLLAPSIBLE_LIST_ITEM} ${isExpanded ? "expanded" : "collapsed"}`
    },
    inCollapsibleList && // oxlint-disable-next-line jsx-a11y/no-static-element-interactions
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: classNames(styles.dndIcon, styles[dir], mouseDown && styles.mouseDown),
        draggable: "true",
        contentEditable: "false",
        "data-drag-handle": true,
        onDragEnd: () => setMouseDown(false),
        onMouseUp: () => setMouseDown(false),
        onMouseDown: () => setMouseDown(true)
      },
      /* @__PURE__ */ React.createElement(DndIcon, null)
    ),
    /* @__PURE__ */ React.createElement("div", { className: styles.expandIcon }, /* @__PURE__ */ React.createElement(
      ExpandCollapseButton,
      {
        isExpanded,
        onClick: toggleCollapsibleItem,
        ariaLabel: isExpanded ? t("CollapsibleListPlugin_ExpandButton_AriaLabel") : t("CollapsibleListPlugin_CollapseButton_AriaLabel")
      }
    )),
    /* @__PURE__ */ React.createElement(NodeViewContent, { className: collapsibleListItemStyles.innerEditor })
  );
};
const CollapsibleListItemTitle = ({ NodeViewContent }) => {
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: classNames(
        collapsibleListItemStyles.container,
        collapsibleListItemStyles.titleContainer
      )
    },
    /* @__PURE__ */ React.createElement(
      NodeViewContent,
      {
        contentEditable: "true",
        className: collapsibleListItemStyles.innerEditor,
        "data-hook": COLLAPSIBLE_LIST_ITEM_TITLE
      }
    )
  );
};
const CollapsibleListItemBody = ({
  NodeViewContent,
  editor,
  getPos,
  node
}) => {
  const $pos = editor.view.state.doc.resolve(getPos());
  const { languageDir, environment } = useContext(RicosContext);
  const modalService = useContext(ModalServiceContext) || {};
  const editorQuery = useContext(EditorQueryContext);
  const floatingAddPluginMenuWrapperRef = useRef(null);
  const isExpanded = findParentNodeClosestToPos(
    $pos,
    (node2) => node2.type.name === TIPTAP_COLLAPSIBLE_ITEM_TYPE
  )?.node?.attrs?.isExpanded;
  const isFloatingMenuVisible = React.useCallback(() => {
    if (environment === "wixel") {
      return false;
    }
    const selectionContainsTitle = (() => {
      const nodes = editorQuery.selection().doc?.children?.[0]?.descendants(
        (node2) => node2.type() === TIPTAP_COLLAPSIBLE_ITEM_TITLE_TYPE
      );
      return nodes?.length > 0;
    })();
    const isCurrentNodeChildIsSingleTextBlock = (() => editorQuery.query.isChildSingleTextBlock(node.attrs.id))();
    return !selectionContainsTitle && isCurrentNodeChildIsSingleTextBlock;
  }, [node]);
  const dir = findParentNodeClosestToPos(
    $pos,
    (node2) => node2.type.name === TIPTAP_COLLAPSIBLE_LIST_TYPE
  )?.node?.attrs?.direction?.toLowerCase() || languageDir;
  return isExpanded ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Suspense, { fallback: /* @__PURE__ */ React.createElement("div", null) }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: collapsibleListItemStyles.floatingAddPluginMenuWrapper,
      ref: floatingAddPluginMenuWrapperRef,
      onClick: preventFocusJumpToFirstNode,
      onMouseDown: preventFocusJumpToFirstNode,
      onKeyDown: preventFocusJumpToFirstNode
    },
    /* @__PURE__ */ React.createElement(
      FloatingAddPluginMenu,
      {
        dir,
        supportedButtonIds: supportedPluginTypes,
        isVisible: isFloatingMenuVisible,
        nodeId: node.attrs.id,
        onClick: () => {
          toggleQuickActionsModal({
            modalService,
            referenceElement: floatingAddPluginMenuWrapperRef.current,
            isMobile: false,
            supportedPlugins: supportedPluginTypes
          });
        }
      }
    )
  )), /* @__PURE__ */ React.createElement("div", { className: collapsibleListItemStyles.container }, /* @__PURE__ */ React.createElement(
    NodeViewContent,
    {
      contentEditable: "true",
      className: collapsibleListItemStyles.innerEditor,
      "data-hook": COLLAPSIBLE_LIST_ITEM_BODY
    }
  ))) : null;
};
const supportedPluginTypes = [
  `${Node_Type.AUDIO}.audio`,
  `${Node_Type.AUDIO}.soundCloud`,
  `${Node_Type.AUDIO}.spotify`,
  Node_Type.FILE,
  Node_Type.IMAGE,
  Node_Type.GALLERY,
  `${Node_Type.VIDEO}.video`,
  `${Node_Type.VIDEO}.youTube`,
  Node_Type.GIF,
  Node_Type.DIVIDER,
  EMOJI_TYPE,
  Node_Type.CODE_BLOCK,
  `${Node_Type.APP_EMBED}.event`,
  `${Node_Type.APP_EMBED}.booking`,
  `${Node_Type.APP_EMBED}.product`,
  `${Node_Type.LINK_PREVIEW}.instagram`,
  `${Node_Type.LINK_PREVIEW}.twitter`,
  `${Node_Type.LINK_PREVIEW}.pinterest`,
  `${Node_Type.LINK_PREVIEW}.facebook`,
  `${Node_Type.LINK_PREVIEW}.tiktok`
];
export {
  CollapsibleList,
  CollapsibleListItem,
  CollapsibleListItemBody,
  CollapsibleListItemTitle
};
//# sourceMappingURL=component.js.map
