"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var smart_block_cell_exports = {};
__export(smart_block_cell_exports, {
  SmartBlockCell: () => SmartBlockCell
});
module.exports = __toCommonJS(smart_block_cell_exports);
var import_classnames = __toESM(require("classnames"));
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_pm_node_types = require("./../../_shared/pm-node-types.js");
var import_smart_block_cell_view = require("../components/smart-block-cell-view.js");
var import_consts = require("../consts.js");
var import_data_hooks = require("../data-hooks.js");
var import_cell_position = require("../utils/cell-position.js");
var import_cell_view_model = require("../utils/cell-view-model.js");
var import_get_joined_boxes_responsive_corner_flags = require("../utils/get-joined-boxes-responsive-corner-flags.js");
var import_resolve_theme_smart_block = require("../utils/resolve-theme-smart-block.js");
var import_smart_block_context = require("../utils/smart-block-context.js");
var import_open_cell_shape_picker = require("./open-cell-shape-picker.js");
var import_smart_block_editor_scss = __toESM(require("./smart-block-editor-scss.js"));
const SmartBlockCell = ({
  node,
  NodeViewContent,
  editor,
  getPos,
  selected,
  updateAttributes,
  decorations
}) => {
  const { theme } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const themeSmartBlock = (0, import_react.useMemo)(() => (0, import_resolve_theme_smart_block.resolveThemeSmartBlock)(theme), [theme]);
  const [, forceUpdate] = (0, import_react.useState)(0);
  const cellRef = (0, import_react.useRef)(null);
  const [hasFocusWithin, setHasFocusWithin] = (0, import_react.useState)(false);
  const attrs = node.attrs;
  (0, import_react.useEffect)(() => {
    if (!editor) {
      return;
    }
    const handleUpdate = () => {
      forceUpdate((n) => n + 1);
    };
    editor.on("update", handleUpdate);
    return () => {
      editor.off("update", handleUpdate);
    };
  }, [editor]);
  (0, import_react.useLayoutEffect)(() => {
    if (!editor) {
      return;
    }
    const syncPositionAttrs = () => {
      const cell = cellRef.current;
      if (!cell || typeof getPos !== "function") {
        return;
      }
      const pos = getPos();
      if (typeof pos !== "number") {
        return;
      }
      const cellId = cell.getAttribute("data-smart-block-cell");
      try {
        const resolvedNode = editor.state.doc.nodeAt(pos);
        if (!resolvedNode || resolvedNode.attrs.id !== cellId) {
          return;
        }
        const $pos = editor.state.doc.resolve(pos);
        const parent = $pos.parent;
        const total = parent.childCount;
        const index = $pos.index($pos.depth);
        const colSize = parent.attrs.columnSize ?? import_consts.SMART_BLOCK_DEFAULTS.columnSize;
        const posAttrs = (0, import_cell_position.getCellPositionDataAttrs)(index, total, colSize);
        for (const [key, val] of Object.entries(posAttrs)) {
          if (val === void 0) {
            cell.removeAttribute(key);
          } else {
            cell.setAttribute(key, val === true ? "" : String(val));
          }
        }
      } catch {
      }
    };
    editor.on("update", syncPositionAttrs);
    return () => {
      editor.off("update", syncPositionAttrs);
    };
  }, [editor, getPos]);
  (0, import_react.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;
      const isInside = from >= pos && to <= nodeEnd;
      setHasFocusWithin(isInside && !selected);
    };
    editor.on("selectionUpdate", checkSelection);
    checkSelection();
    return () => {
      editor.off("selectionUpdate", checkSelection);
    };
  }, [editor, getPos, node.nodeSize, selected]);
  const parentContext = (() => {
    const defaults = {
      cellIndex: 0,
      totalCells: 1,
      columnSize: import_consts.SMART_BLOCK_DEFAULTS.columnSize,
      orientation: "HORIZONTAL",
      isShapesMode: false,
      type: import_consts.SMART_BLOCK_DEFAULTS.type
    };
    if (!editor || typeof getPos !== "function") {
      return defaults;
    }
    const pos = getPos();
    if (typeof pos !== "number") {
      return defaults;
    }
    try {
      const $pos = editor.state.doc.resolve(pos);
      const parent = $pos.parent;
      const total = parent.childCount;
      const index = $pos.index($pos.depth);
      const type = parent.attrs.type ?? defaults.type;
      const columnSize = parent.attrs.columnSize ?? import_consts.SMART_BLOCK_DEFAULTS.columnSize;
      const orientation = parent.attrs.orientation ?? "HORIZONTAL";
      let hasAnyShape = false;
      parent.forEach((child) => {
        if (child.type.name === import_pm_node_types.PmNodeType.SMART_BLOCK_CELL && child.attrs.shape) {
          hasAnyShape = true;
        }
      });
      return {
        cellIndex: index,
        totalCells: total,
        type,
        columnSize,
        orientation,
        isShapesMode: hasAnyShape
      };
    } catch {
      return defaults;
    }
  })();
  const {
    cellIndex,
    totalCells,
    type: blockType,
    columnSize: blockColumnSize,
    orientation: blockOrientation,
    isShapesMode
  } = parentContext;
  const colorPreview = (0, import_react.useMemo)(() => {
    const spec = decorations?.find((deco) => deco.spec?.sbPreviewAttr)?.spec;
    if (!spec?.sbPreviewAttr) {
      return null;
    }
    return {
      attr: spec.sbPreviewAttr,
      color: spec.sbPreviewColor
    };
  }, [decorations]);
  const viewModel = (0, import_react.useMemo)(() => {
    const base = (0, import_cell_view_model.pmCellToViewModel)(node, {
      type: blockType,
      cellIndex,
      totalCells,
      columnSize: blockColumnSize,
      orientation: blockOrientation,
      isShapesMode
    });
    if (!colorPreview) {
      return base;
    }
    if (colorPreview.attr === "shapeColor") {
      return { ...base, shapeColor: colorPreview.color };
    }
    return {
      ...base,
      cellColors: { ...base.cellColors, [colorPreview.attr]: colorPreview.color }
    };
  }, [
    node,
    blockType,
    cellIndex,
    totalCells,
    blockColumnSize,
    blockOrientation,
    isShapesMode,
    colorPreview
  ]);
  const joinedCornerFlags = (0, import_react.useMemo)(() => {
    if (blockType !== "SOLID_JOINED_BOXES") {
      return void 0;
    }
    return (0, import_get_joined_boxes_responsive_corner_flags.getJoinedBoxesResponsiveCornerFlags)({
      cellIndex,
      totalCells,
      columnsPerRow: (0, import_cell_position.getColumnsPerRow)(blockColumnSize),
      responsiveColumnsPerRow: (0, import_cell_position.getResponsiveColumnsPerRow)(blockColumnSize)
    });
  }, [blockType, cellIndex, totalCells, blockColumnSize]);
  const handleAddShapeClick = (0, import_react.useCallback)(
    (event) => (0, import_open_cell_shape_picker.openCellShapePicker)(editor, attrs.id, event.currentTarget),
    [editor, attrs.id]
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_smart_block_context.SmartBlockCellEditorContext.Provider,
    {
      value: (0, import_react.useMemo)(
        () => ({
          onLabelChange: (label) => updateAttributes({ label }),
          onShapeClick: handleAddShapeClick
        }),
        [updateAttributes, handleAddShapeClick]
      )
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_smart_block_cell_view.SmartBlockCellView,
      {
        viewModel,
        themeSmartBlock,
        outerRef: cellRef,
        outerClassName: (0, import_classnames.default)(import_smart_block_editor_scss.default.editorCell, {
          [import_smart_block_editor_scss.default.cellSelected]: selected,
          [import_smart_block_editor_scss.default.cellFocusWithin]: hasFocusWithin
        }),
        extraAttrs: joinedCornerFlags,
        contentSlot: (contentProps) => /* @__PURE__ */ import_react.default.createElement(NodeViewContent, { ...contentProps }),
        overlayChildren: /* @__PURE__ */ import_react.default.createElement("div", { contentEditable: false, className: import_smart_block_editor_scss.default.cellHandleWrapper }, /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            role: "button",
            tabIndex: 0,
            draggable: true,
            className: import_smart_block_editor_scss.default.cellDragHandle,
            "data-drag-handle": "",
            "data-smart-block-cell-handle": "",
            "data-hook": import_data_hooks.DATA_HOOKS.SMART_BLOCK_CELL_HANDLE,
            onClick: () => {
              const cellId = cellRef.current?.getAttribute("data-smart-block-cell");
              if (cellId && editor) {
                editor.chain().selectSmartBlockCell(cellId).run();
              }
            },
            onKeyDown: (event) => {
              if (event.key !== "Enter" && event.key !== " ") {
                return;
              }
              event.preventDefault();
              const cellId = cellRef.current?.getAttribute("data-smart-block-cell");
              if (cellId && editor) {
                editor.chain().selectSmartBlockCell(cellId).run();
              }
            }
          },
          /* @__PURE__ */ import_react.default.createElement(ThreeDotsIcon, null)
        ))
      }
    )
  );
};
const ThreeDotsIcon = () => /* @__PURE__ */ import_react.default.createElement("svg", { viewBox: "0 0 18 18", fill: "currentColor", width: "18", height: "18" }, /* @__PURE__ */ import_react.default.createElement("path", { d: "M4,8 L6,8 L6,10 L4,10 L4,8 Z M8,8 L10,8 L10,10 L8,10 L8,8 Z M12,8 L14,8 L14,10 L12,10 L12,8 Z" }));
//# sourceMappingURL=smart-block-cell.js.map
