import classNames from "classnames";
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { RicosContext } from "./../../ricos-context/index.js";
import { PmNodeType } from "./../../_shared/pm-node-types.js";
import { SmartBlockShapePickerModal } from "../components/smart-block-shape-picker-modal.js";
import { SmartBlockView } from "../components/smart-block-view.js";
import { MAX_ITEMS } from "../consts.js";
import { DATA_HOOKS } from "../data-hooks.js";
import { pmBlockToViewModel } from "../utils/block-view-model.js";
import { resolveThemeSmartBlock } from "../utils/resolve-theme-smart-block.js";
import { SmartBlockEditorContext } from "../utils/smart-block-context.js";
import { openCellShapePicker } from "./open-cell-shape-picker.js";
import styles from "./smart-block-editor-scss.js";
import { useSmartBlockDrag } from "./use-smart-block-drag.js";
const SmartBlock = ({
  node,
  NodeViewContent,
  selected,
  editor,
  getPos,
  decorations
}) => {
  const { t, theme } = useContext(RicosContext) || {};
  const wrapperRef = useRef(null);
  const [hasFocusWithin, setHasFocusWithin] = useState(false);
  const { dropCursorPosition } = useSmartBlockDrag(wrapperRef, editor, node.attrs.id);
  const themeSmartBlock = useMemo(() => resolveThemeSmartBlock(theme), [theme]);
  const borderColorPreview = useMemo(() => {
    const spec = decorations?.find((deco) => deco.spec?.sbPreviewAttr === "borderColor")?.spec;
    if (!spec?.sbPreviewAttr) {
      return null;
    }
    return { color: spec.sbPreviewColor };
  }, [decorations]);
  const viewModel = useMemo(() => {
    const base = pmBlockToViewModel(node);
    if (!borderColorPreview) {
      return base;
    }
    return {
      ...base,
      blockBorder: { ...base.blockBorder, borderColor: borderColorPreview.color }
    };
  }, [node, borderColorPreview]);
  const handleCellShapeClick = useCallback(
    (cellId, event) => openCellShapePicker(editor, cellId, event.currentTarget),
    [editor]
  );
  const handleTriangleShapeClick = useCallback(
    (cellId, event) => {
      if (!editor) {
        return;
      }
      const smartBlockExt = editor.extensionManager.extensions.find(
        (ext) => ext.name === PmNodeType.SMART_BLOCK
      );
      const services = smartBlockExt?.options?.services;
      if (!services) {
        return;
      }
      services.modals.togglePluginPanel({
        id: DATA_HOOKS.CELL_SHAPE_PICKER,
        Component: SmartBlockShapePickerModal,
        componentProps: { cellId },
        isMobile: services.context.isMobile,
        positioning: {
          referenceElement: event.currentTarget,
          placement: "bottom"
        }
      });
    },
    [editor]
  );
  useEffect(() => {
    if (!editor || typeof getPos !== "function") {
      return;
    }
    const checkSelection = () => {
      const pos = getPos();
      if (typeof pos !== "number") {
        setHasFocusWithin(false);
        return;
      }
      const { from, to } = editor.state.selection;
      const nodeEnd = pos + node.nodeSize;
      setHasFocusWithin(from >= pos && to <= nodeEnd);
    };
    editor.on("selectionUpdate", checkSelection);
    editor.on("update", checkSelection);
    checkSelection();
    return () => {
      editor.off("selectionUpdate", checkSelection);
      editor.off("update", checkSelection);
    };
  }, [editor, getPos, node.nodeSize]);
  return /* @__PURE__ */ React.createElement(
    SmartBlockEditorContext.Provider,
    {
      value: useMemo(() => ({ onCellShapeClick: handleCellShapeClick }), [handleCellShapeClick])
    },
    /* @__PURE__ */ React.createElement(
      SmartBlockView,
      {
        viewModel,
        themeSmartBlock,
        outerRef: wrapperRef,
        outerClassName: classNames(styles.editorWrapper, {
          [styles.selected]: selected,
          [styles.focusWithin]: hasFocusWithin
        }),
        onTriangleShapeClick: handleTriangleShapeClick,
        contentSlot: (innerProps) => /* @__PURE__ */ React.createElement(NodeViewContent, { ...innerProps }),
        overlayChildren: /* @__PURE__ */ React.createElement(React.Fragment, null, dropCursorPosition !== null && /* @__PURE__ */ React.createElement(
          "div",
          {
            className: styles.dropCursor,
            style: {
              "--ricos-internal-sb-drop-cursor-position": `${dropCursorPosition.left}px`,
              "--ricos-internal-sb-drop-cursor-top": `${dropCursorPosition.top}px`,
              "--ricos-internal-sb-drop-cursor-height": `${dropCursorPosition.height}px`
            }
          }
        ), node.childCount < MAX_ITEMS && /* @__PURE__ */ React.createElement(
          "div",
          {
            contentEditable: false,
            className: styles.addCellBar,
            "data-hook": DATA_HOOKS.SMART_BLOCK_CELL_ADD_BUTTON
          },
          /* @__PURE__ */ React.createElement(
            "button",
            {
              type: "button",
              className: styles.addCellBarButton,
              onClick: () => editor.commands.addSmartBlockCell(node.attrs.id),
              "aria-label": t("SmartBlock_AddCell_AriaLabel")
            },
            /* @__PURE__ */ React.createElement(
              "svg",
              {
                xmlns: "http://www.w3.org/2000/svg",
                width: "18",
                height: "18",
                viewBox: "0 0 18 18"
              },
              /* @__PURE__ */ React.createElement(
                "path",
                {
                  fillRule: "evenodd",
                  d: "M10 9V5H9V9H5V10H9V14H10V10H14V9H10Z",
                  fill: "currentColor"
                }
              )
            )
          )
        ), /* @__PURE__ */ React.createElement("div", { contentEditable: false, className: styles.smartBlockHandleWrapper }, /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            className: styles.smartBlockHandle,
            "data-drag-handle": "",
            "data-smart-block-handle": "",
            "data-hook": DATA_HOOKS.SMART_BLOCK_HANDLE,
            onClick: () => {
              if (editor && typeof getPos === "function") {
                const pos = getPos();
                if (typeof pos === "number") {
                  editor.chain().setNodeSelection(pos).focus(void 0, { scrollIntoView: false }).run();
                }
              }
            }
          },
          /* @__PURE__ */ React.createElement(MoveIcon, null)
        )))
      }
    )
  );
};
const MoveIcon = () => /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 18 18", fill: "currentColor", width: "18", height: "18" }, /* @__PURE__ */ React.createElement("path", { d: "M10.85 13.461c.2.2.2.511 0 .712L9 16l-1.85-1.857a.487.487 0 0 1 0-.702c.2-.2.51-.2.71 0l.65.654V9.49H3.905l.654.65c.2.2.2.51 0 .71a.487.487 0 0 1-.702 0L2 9l1.857-1.85c.2-.2.511-.2.712 0 .2.2.2.51 0 .71l-.654.65H8.51V3.905l-.65.654c-.2.2-.51.2-.71 0a.487.487 0 0 1 0-.702L9 2l1.85 1.857c.2.2.2.511 0 .712-.2.2-.51.2-.71 0l-.65-.654V8.51h4.625l-.654-.65c-.2-.2-.2-.51 0-.71.2-.2.511-.2.712 0L16 9l-1.857 1.85a.487.487 0 0 1-.702 0c-.2-.2-.2-.51 0-.71l.654-.65H9.49v4.625l.65-.654c.2-.2.51-.2.71 0Z" }));
export {
  SmartBlock
};
//# sourceMappingURL=smart-block.js.map
