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);

// src/components/pisellFloorMapLayout/components/EditableItemLayer.tsx
var EditableItemLayer_exports = {};
__export(EditableItemLayer_exports, {
  EditableItemLayer: () => EditableItemLayer,
  default: () => EditableItemLayer_default
});
module.exports = __toCommonJS(EditableItemLayer_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_snap = require("../utils/snap");
var import_FloorMapEditQuickActions = require("./FloorMapEditQuickActions");
var import_EditableItemLayer = require("./EditableItemLayer.less");
function isSceneLayoutTransformLocked(item) {
  var _a;
  return Boolean((_a = item._sceneElement) == null ? void 0 : _a.layoutTransformLocked);
}
var PREFIX = "pisell-floor-map-layout";
var DRAG_THRESHOLD = 4;
var SELECTED_ITEM_STACK_Z = 1e6;
function getItemKey(item, index, rowKey) {
  if (!rowKey) return item.id;
  if (typeof rowKey === "string")
    return String(item[rowKey] ?? item.id);
  return rowKey(item, index);
}
function getShapeStyle(shape = "rect") {
  switch (shape) {
    case "circle":
      return { borderRadius: "50%" };
    case "triangle":
      return { clipPath: "polygon(50% 0%, 0% 100%, 100% 100%)" };
    default:
      return {};
  }
}
function EditableItemLayer(props) {
  const {
    items,
    renderItem,
    rowKey,
    cellSize,
    itemUnit = "pixel",
    itemGap = 0,
    contentWidth,
    contentHeight,
    contentOffsetX = 0,
    contentOffsetY = 0,
    selectedId,
    onSelect,
    onUpdateItem,
    snapStep = 0,
    scale = 1,
    onInteractionChange,
    getMergedItemWrapperStyle,
    className,
    editQuickBar
  } = props;
  const contentRef = (0, import_react.useRef)(null);
  const liveRectRef = (0, import_react.useRef)(null);
  const [interaction, setInteraction] = (0, import_react.useState)(null);
  const [liveRect, setLiveRect] = (0, import_react.useState)(null);
  const getItemStyle = (0, import_react.useCallback)(
    (item, index) => {
      const merged = item;
      const isPixel = itemUnit === "pixel";
      const g = itemGap ?? 0;
      let left;
      let top;
      let width;
      let height;
      if (isPixel) {
        width = item.width ?? cellSize;
        height = item.height ?? cellSize;
        left = item.x;
        top = item.y;
      } else {
        const w = item.width ?? 1;
        const h = item.height ?? 1;
        left = g > 0 ? item.x * (cellSize + g) + g : item.x * cellSize;
        top = g > 0 ? item.y * (cellSize + g) + g : item.y * cellSize;
        width = g > 0 ? w * cellSize + (w - 1) * g : w * cellSize;
        height = g > 0 ? h * cellSize + (h - 1) * g : h * cellSize;
      }
      if (liveRect && liveRect.id === item.id) {
        left = liveRect.x;
        top = liveRect.y;
        width = liveRect.width;
        height = liveRect.height;
      }
      return { left, top, width, height };
    },
    [itemUnit, cellSize, itemGap, liveRect]
  );
  const handlePointerDown = (0, import_react.useCallback)(
    (e, item, index) => {
      if (e.button !== 0) return;
      if (e.target.closest(`.${PREFIX}-editable-resize-handle`))
        return;
      const merged = item;
      if (isSceneLayoutTransformLocked(merged)) {
        return;
      }
      e.stopPropagation();
      e.preventDefault();
      onInteractionChange == null ? void 0 : onInteractionChange(true);
      const style = getItemStyle(item, index);
      setInteraction({
        type: "drag",
        itemId: item.id,
        startX: e.clientX,
        startY: e.clientY,
        itemX: style.left,
        itemY: style.top,
        itemW: style.width,
        itemH: style.height
      });
    },
    [getItemStyle, onInteractionChange]
  );
  const handleResizePointerDown = (0, import_react.useCallback)(
    (e, itemId, handle) => {
      if (e.button !== 0) return;
      const item = items.find((i) => i.id === itemId);
      if (!item) return;
      if (isSceneLayoutTransformLocked(item)) {
        return;
      }
      e.stopPropagation();
      e.preventDefault();
      onInteractionChange == null ? void 0 : onInteractionChange(true);
      const idx = items.indexOf(item);
      const style = getItemStyle(item, idx);
      setInteraction({
        type: "resize",
        itemId,
        handle,
        startX: e.clientX,
        startY: e.clientY,
        startW: style.width,
        startH: style.height,
        startItemX: style.left,
        startItemY: style.top
      });
    },
    [items, getItemStyle, onInteractionChange]
  );
  import_react.default.useEffect(() => {
    if (!interaction) return;
    const onMove = (e) => {
      if (interaction.type === "drag") {
        const dx = (e.clientX - interaction.startX) / scale;
        const dy = (e.clientY - interaction.startY) / scale;
        const next = {
          x: interaction.itemX + dx,
          y: interaction.itemY + dy,
          width: interaction.itemW,
          height: interaction.itemH
        };
        liveRectRef.current = next;
        setLiveRect({ id: interaction.itemId, ...next });
      } else {
        const dx = (e.clientX - interaction.startX) / scale;
        const dy = (e.clientY - interaction.startY) / scale;
        const { handle, startW, startH, startItemX, startItemY } = interaction;
        let w = startW;
        let h = startH;
        let x = startItemX;
        let y = startItemY;
        if (handle.includes("e")) w = Math.max(20, startW + dx);
        if (handle.includes("w")) {
          w = Math.max(20, startW - dx);
          x = startItemX + dx;
        }
        if (handle.includes("s")) h = Math.max(20, startH + dy);
        if (handle.includes("n")) {
          h = Math.max(20, startH - dy);
          y = startItemY + dy;
        }
        const next = { x, y, width: w, height: h };
        liveRectRef.current = next;
        setLiveRect({ id: interaction.itemId, ...next });
      }
    };
    const onUp = () => {
      const current = interaction;
      if (!current) return;
      const last = liveRectRef.current;
      onInteractionChange == null ? void 0 : onInteractionChange(false);
      setLiveRect(null);
      liveRectRef.current = null;
      setInteraction(null);
      if (current.type === "drag") {
        if (last && (Math.abs(last.x - current.itemX) > DRAG_THRESHOLD || Math.abs(last.y - current.itemY) > DRAG_THRESHOLD)) {
          const snapped = (0, import_snap.snapRect)(last.x, last.y, 0, 0, snapStep);
          onUpdateItem(current.itemId, {
            x: Math.round(snapped.x),
            y: Math.round(snapped.y)
          });
        }
      } else {
        if (last) {
          const snapped = (0, import_snap.snapRect)(
            last.x,
            last.y,
            last.width,
            last.height,
            snapStep
          );
          onUpdateItem(current.itemId, {
            x: Math.round(snapped.x),
            y: Math.round(snapped.y),
            width: Math.round(snapped.width),
            height: Math.round(snapped.height)
          });
        }
      }
    };
    const opts = { capture: true };
    document.addEventListener("pointermove", onMove, opts);
    document.addEventListener("pointerup", onUp, opts);
    document.addEventListener("pointercancel", onUp, opts);
    return () => {
      document.removeEventListener("pointermove", onMove, opts);
      document.removeEventListener("pointerup", onUp, opts);
      document.removeEventListener("pointercancel", onUp, opts);
    };
  }, [interaction, scale, snapStep, onUpdateItem, onInteractionChange]);
  const handleItemClick = (0, import_react.useCallback)(
    (e, item) => {
      if (interaction) return;
      e.stopPropagation();
      onSelect(item.id);
    },
    [interaction, onSelect]
  );
  const itemNodes = (0, import_react.useMemo)(() => {
    const sorted = [...items].sort((a, b) => (a.zIndex ?? 0) - (b.zIndex ?? 0));
    return sorted.map((item, index) => {
      const key = getItemKey(item, index, rowKey);
      const merged = item;
      const style = getItemStyle(item, index);
      const shapeStyle = getShapeStyle(item.shape);
      const isSelected = selectedId === item.id;
      const wrapperStyle = getMergedItemWrapperStyle == null ? void 0 : getMergedItemWrapperStyle(item, index);
      const baseZ = (wrapperStyle == null ? void 0 : wrapperStyle.zIndex) !== void 0 ? wrapperStyle.zIndex : item.zIndex ?? 0;
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          key,
          className: (0, import_classnames.default)(`${PREFIX}-editable-item`, {
            [`${PREFIX}-editable-item-selected`]: isSelected,
            [`${PREFIX}-editable-item-selected-lock`]: isSelected && isSceneLayoutTransformLocked(merged)
          }),
          style: {
            position: "absolute",
            left: style.left,
            top: style.top,
            width: style.width,
            height: style.height,
            boxSizing: "border-box",
            ...shapeStyle,
            ...wrapperStyle,
            zIndex: isSelected ? SELECTED_ITEM_STACK_Z + (item.zIndex ?? 0) : baseZ
          },
          onPointerDown: (e) => handlePointerDown(e, item, index),
          onClick: (e) => handleItemClick(e, item)
        },
        /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-editable-item-inner` }, renderItem(item, index, { viewportScale: scale })),
        isSelected && !isSceneLayoutTransformLocked(merged) && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, ["nw", "n", "ne", "e", "se", "s", "sw", "w"].map((h) => /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            key: h,
            className: (0, import_classnames.default)(
              `${PREFIX}-editable-resize-handle`,
              `${PREFIX}-editable-resize-handle-${h}`
            ),
            onPointerDown: (e) => handleResizePointerDown(e, item.id, h),
            style: { position: "absolute" }
          }
        ))),
        isSelected && editQuickBar ? /* @__PURE__ */ import_react.default.createElement(
          import_FloorMapEditQuickActions.FloorMapEditQuickActions,
          {
            labels: editQuickBar.labels,
            isLocked: editQuickBar.isLocked,
            onToggleLock: editQuickBar.onToggleLock,
            onDuplicate: editQuickBar.onDuplicate,
            onDelete: editQuickBar.onDelete
          }
        ) : null
      );
    });
  }, [
    items,
    renderItem,
    rowKey,
    getItemStyle,
    selectedId,
    handlePointerDown,
    handleItemClick,
    handleResizePointerDown,
    getMergedItemWrapperStyle,
    editQuickBar,
    scale
  ]);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: contentRef,
      className: (0, import_classnames.default)(`${PREFIX}-editable-item-layer`, className),
      style: {
        position: "absolute",
        left: 0,
        top: 0,
        width: contentWidth,
        height: contentHeight,
        minWidth: contentWidth,
        minHeight: contentHeight
      }
    },
    contentOffsetX !== 0 || contentOffsetY !== 0 ? /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          position: "absolute",
          left: 0,
          top: 0,
          width: contentWidth,
          height: contentHeight,
          transform: `translate(${contentOffsetX}px, ${contentOffsetY}px)`
        }
      },
      itemNodes
    ) : itemNodes
  );
}
var EditableItemLayer_default = EditableItemLayer;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  EditableItemLayer
});
