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/hooks/useFloorMapEditState.ts
var useFloorMapEditState_exports = {};
__export(useFloorMapEditState_exports, {
  useFloorMapEditState: () => useFloorMapEditState
});
module.exports = __toCommonJS(useFloorMapEditState_exports);
var import_react = require("react");
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils2 = require("../../translation/utils");
var import_floorMapConfigMerge = require("../utils/floorMapConfigMerge");
var import_floorMapStageDefaults = require("../utils/floorMapStageDefaults");
var import_useDraftConfigHistory = require("./useDraftConfigHistory");
var import_floorMapViewConfigDiff = require("../utils/floorMapViewConfigDiff");
var import_floorMapElementKindUtils = require("../utils/floorMapElementKindUtils");
var import_floorMapBuiltinShapes = require("../utils/floorMapBuiltinShapes");
var import_layoutMeasurements = require("../utils/layoutMeasurements");
var import_floorMapCanvasDisplay = require("../utils/floorMapCanvasDisplay");
var import_types = require("../types");
var IMAGE_PLACE_DEFAULT = { width: 400, height: 240 };
var BUILTIN_SHAPE_PLACE_DEFAULT = { width: 96, height: 96 };
var I18N_PLACEMENT_FALLBACK_IMAGE = "pisell-floor-map-layout.placement.fallback-image-name";
var GRID_VIS_STORAGE_PREFIX = "pisell-floor-map-layout.grid-visible";
function getGridVisStorageKey(canvasId) {
  return `${GRID_VIS_STORAGE_PREFIX}:${canvasId}`;
}
function readStoredGridVisible(canvasId) {
  try {
    const raw = localStorage.getItem(getGridVisStorageKey(canvasId));
    if (raw == null) return null;
    if (raw === "1") return true;
    if (raw === "0") return false;
    return null;
  } catch {
    return null;
  }
}
function writeStoredGridVisible(canvasId, visible) {
  try {
    localStorage.setItem(getGridVisStorageKey(canvasId), visible ? "1" : "0");
  } catch {
  }
}
var BATCH_PLACE_OFFSET = 16;
function newInstanceId() {
  return `elm_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
}
function duplicateBinding(elements, binding, exceptInstanceId) {
  return (elements ?? []).some(
    (e) => {
      var _a, _b;
      return e.instanceId !== exceptInstanceId && ((_a = e.dataBinding) == null ? void 0 : _a.dataSourceKey) === binding.dataSourceKey && ((_b = e.dataBinding) == null ? void 0 : _b.recordId) === binding.recordId;
    }
  );
}
function useFloorMapEditState(params) {
  var _a, _b, _c;
  const {
    floorMapConfigProp,
    isFloorMapView,
    itemsProp,
    cellSizeProp,
    dataSources,
    onSave,
    onDataSourceRecordSave,
    dataSourceFormColumns,
    dataSourceRecordForm,
    dataSourceLabels,
    layoutPrefix,
    contentOffsetRef,
    showDataSourceRecordFormBlock
  } = params;
  const engineCtx = (0, import_useEngineContext.default)();
  const engineLocale = ((_b = (_a = engineCtx == null ? void 0 : engineCtx.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "zh-CN";
  const draftHistory = (0, import_useDraftConfigHistory.useDraftConfigHistory)();
  const draftConfig = draftHistory.present;
  const commitDraft = draftHistory.commit;
  const replaceDraft = draftHistory.replace;
  const undoDraft = draftHistory.undo;
  const redoDraft = draftHistory.redo;
  const canUndo = draftHistory.canUndo;
  const canRedo = draftHistory.canRedo;
  const [currentCanvasId, setCurrentCanvasId] = (0, import_react.useState)(null);
  const [selectedId, setSelectedId] = (0, import_react.useState)(null);
  const [placeMode, setPlaceMode] = (0, import_react.useState)(null);
  const [saving, setSaving] = (0, import_react.useState)(false);
  const [savingRecord, setSavingRecord] = (0, import_react.useState)(false);
  const [savedBaselineConfig, setSavedBaselineConfig] = (0, import_react.useState)(null);
  const config = isFloorMapView ? draftConfig ?? floorMapConfigProp : null;
  const configRef = (0, import_react.useRef)(config);
  configRef.current = config;
  (0, import_react.useEffect)(() => {
    if (!floorMapConfigProp) return;
    const baseConfig = (0, import_floorMapViewConfigDiff.normalizeFloorMapViewConfigFromProp)(floorMapConfigProp);
    const nextConfig = {
      ...baseConfig,
      canvases: baseConfig.canvases.map((canvas) => {
        const stored = readStoredGridVisible(canvas.id);
        if (stored == null) return canvas;
        return {
          ...canvas,
          mapLayer: { ...canvas.mapLayer ?? {}, showGrid: stored }
        };
      })
    };
    replaceDraft(nextConfig);
    setSavedBaselineConfig(null);
    const enabled = nextConfig.canvases.filter((c) => c.enabled).sort((a, b) => a.order - b.order);
    setCurrentCanvasId(
      (prev) => {
        var _a2;
        return prev && enabled.some((c) => c.id === prev) ? prev : ((_a2 = enabled[0]) == null ? void 0 : _a2.id) ?? null;
      }
    );
  }, [floorMapConfigProp]);
  const isLayoutDirty = (0, import_react.useMemo)(() => {
    if (!isFloorMapView || !draftConfig || !floorMapConfigProp) return false;
    const baseline = savedBaselineConfig ?? (0, import_floorMapViewConfigDiff.normalizeFloorMapViewConfigFromProp)(floorMapConfigProp);
    return !(0, import_floorMapViewConfigDiff.floorMapViewConfigsEqual)(draftConfig, baseline);
  }, [isFloorMapView, draftConfig, floorMapConfigProp, savedBaselineConfig]);
  (0, import_react.useEffect)(() => {
    if (!selectedId || !draftConfig) return;
    const exists = (draftConfig.sceneElements ?? []).some(
      (e) => e.instanceId === selectedId
    );
    if (!exists) setSelectedId(null);
  }, [selectedId, draftConfig]);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (!draftConfig) return;
    if (!currentCanvasId) return;
    const stillUsable = draftConfig.canvases.some(
      (c) => c.id === currentCanvasId && c.enabled
    );
    if (stillUsable) return;
    const enabled = draftConfig.canvases.filter((c) => c.enabled).sort((a, b) => a.order - b.order);
    setCurrentCanvasId(((_a2 = enabled[0]) == null ? void 0 : _a2.id) ?? null);
  }, [currentCanvasId, draftConfig]);
  const handleAddCanvas = (0, import_react.useCallback)(() => {
    (0, import_floorMapCanvasDisplay.initFloorMapLayoutLocales)(engineLocale);
    const label = import_utils.locales.getText(
      "pisell-floor-map-layout.canvas-tabs.default-new-canvas-name"
    );
    const defaultName = (0, import_utils2.createTranslationText)(
      label,
      true
    );
    const newId = `floor_${Date.now()}`;
    const newCanvas = {
      id: newId,
      name: defaultName,
      order: 0,
      enabled: true
    };
    commitDraft((prev) => {
      if (!prev) return prev;
      const list = prev.canvases.filter((c) => c.enabled).sort((a, b) => a.order - b.order);
      newCanvas.order = list.length > 0 ? Math.max(...list.map((c) => c.order)) + 1 : 0;
      return { ...prev, canvases: [...prev.canvases, newCanvas] };
    });
    setCurrentCanvasId(newId);
  }, [engineLocale]);
  const handleRemoveCanvas = (0, import_react.useCallback)((canvasId) => {
    commitDraft((prev) => {
      if (!prev) return prev;
      const nextCanvases = prev.canvases.filter((c) => c.id !== canvasId);
      if (nextCanvases.length === 0) return prev;
      return {
        ...prev,
        canvases: nextCanvases,
        sceneElements: (prev.sceneElements ?? []).filter(
          (e) => e.canvasId !== canvasId
        )
      };
    });
    setCurrentCanvasId((prev) => {
      var _a2;
      if (prev !== canvasId) return prev;
      const cfg = configRef.current;
      if (!cfg) return prev;
      const enabled = cfg.canvases.filter((c) => c.id !== canvasId && c.enabled).sort((a, b) => a.order - b.order);
      return ((_a2 = enabled[0]) == null ? void 0 : _a2.id) ?? null;
    });
  }, []);
  const handleRenameCanvas = (0, import_react.useCallback)(
    (canvasId, name) => {
      if (typeof name === "string") {
        const trimmed = name.trim();
        if (!trimmed) return;
        commitDraft((prev) => {
          if (!prev) return prev;
          return {
            ...prev,
            canvases: prev.canvases.map(
              (c) => c.id === canvasId ? { ...c, name: trimmed, nameKey: void 0 } : c
            )
          };
        });
        return;
      }
      const hasAny = Object.values(name).some(
        (s) => typeof s === "string" && s.trim()
      );
      if (!hasAny) return;
      commitDraft((prev) => {
        if (!prev) return prev;
        return {
          ...prev,
          canvases: prev.canvases.map(
            (c) => c.id === canvasId ? { ...c, name, nameKey: void 0 } : c
          )
        };
      });
    },
    []
  );
  const mergedItems = (0, import_react.useMemo)(() => {
    if (!isFloorMapView || !config || !currentCanvasId) return [];
    return (0, import_floorMapConfigMerge.mergeCanvasItems)(
      currentCanvasId,
      config,
      cellSizeProp ?? import_layoutMeasurements.DEFAULT_CELL_SIZE
    );
  }, [isFloorMapView, config, currentCanvasId, cellSizeProp]);
  const items = isFloorMapView ? mergedItems : itemsProp;
  const updateDraftSceneElement = (0, import_react.useCallback)(
    (instanceId, patch) => {
      commitDraft((prev) => {
        if (!prev) return prev;
        const current = (prev.sceneElements ?? []).find(
          (e) => e.instanceId === instanceId
        );
        let normalized = { ...patch };
        const unlocking = patch.layoutTransformLocked === false;
        if ((current == null ? void 0 : current.layoutTransformLocked) && !unlocking) {
          const {
            x: _x,
            y: _y,
            zIndex: _z,
            width: _w,
            height: _h,
            ...rest
          } = normalized;
          normalized = rest;
        }
        if (normalized.x !== void 0) normalized.x = Math.round(normalized.x);
        if (normalized.y !== void 0) normalized.y = Math.round(normalized.y);
        if (normalized.width !== void 0)
          normalized.width = Math.round(normalized.width);
        if (normalized.height !== void 0)
          normalized.height = Math.round(normalized.height);
        const list = (prev.sceneElements ?? []).map(
          (e) => e.instanceId === instanceId ? { ...e, ...normalized } : e
        );
        return { ...prev, sceneElements: list };
      });
    },
    []
  );
  const handleUpdateItem = (0, import_react.useCallback)(
    (itemId, patch) => {
      updateDraftSceneElement(itemId, patch);
    },
    [updateDraftSceneElement]
  );
  const placeOverlayClass = `${layoutPrefix}-place-overlay`;
  const applyScenePlacementAtCoords = (0, import_react.useCallback)(
    (contentX, contentY, scene) => {
      var _a2, _b2;
      if (!config || !currentCanvasId) return false;
      const defaultPlacementWidth = 180;
      const defaultPlacementHeight = 120;
      const defaultDecoSize = 48;
      const kindConfig = (0, import_floorMapElementKindUtils.getElementKindConfig)(config, scene.elementKind);
      const policy = (0, import_floorMapElementKindUtils.resolveDataBindingPolicy)(kindConfig);
      const allKeys = Object.keys(dataSources ?? {});
      const allowedKeys = ((_a2 = kindConfig == null ? void 0 : kindConfig.allowedDataSourceKeys) == null ? void 0 : _a2.length) ? kindConfig.allowedDataSourceKeys.filter((k) => allKeys.includes(k)) : allKeys;
      const pickKey = scene.dataSourceKey ?? allowedKeys[0] ?? allKeys[0];
      const recordIdsToPlace = scene.recordIds && scene.recordIds.length > 0 ? scene.recordIds : scene.recordId ? [scene.recordId] : [];
      const isStage = scene.elementKind === import_types.FLOOR_MAP_STAGE_ELEMENT_KIND;
      const isImage = (0, import_floorMapElementKindUtils.isFloorMapImageElementKind)(scene.elementKind);
      const isBuiltinShape = (0, import_floorMapElementKindUtils.isFloorMapBuiltinShapeElementKind)(
        scene.elementKind
      );
      const initialBuiltinShapeKey = isBuiltinShape ? scene.builtinShapeKey ?? ((_b2 = import_floorMapBuiltinShapes.FLOOR_MAP_BUILTIN_SHAPES[0]) == null ? void 0 : _b2.key) : void 0;
      const builtinDef = isBuiltinShape ? (0, import_floorMapBuiltinShapes.getFloorMapBuiltinShapeDef)(initialBuiltinShapeKey) : void 0;
      const w = isImage ? IMAGE_PLACE_DEFAULT.width : isStage ? import_floorMapStageDefaults.STAGE_DECO_DEFAULT.width : isBuiltinShape ? (builtinDef == null ? void 0 : builtinDef.defaultSize.width) ?? BUILTIN_SHAPE_PLACE_DEFAULT.width : defaultPlacementWidth;
      const h = isImage ? IMAGE_PLACE_DEFAULT.height : isStage ? import_floorMapStageDefaults.STAGE_DECO_DEFAULT.height : isBuiltinShape ? (builtinDef == null ? void 0 : builtinDef.defaultSize.height) ?? BUILTIN_SHAPE_PLACE_DEFAULT.height : defaultPlacementHeight;
      const useDecoSize = policy === "none" && scene.elementKind !== import_types.FLOOR_MAP_STAGE_ELEMENT_KIND && !isImage && !isBuiltinShape;
      const buildOneElement = (dataBinding2, x, y, name) => ({
        instanceId: newInstanceId(),
        canvasId: currentCanvasId,
        x,
        y,
        name,
        /** 图片 / 内置图形通常作为底图与结构标记，默认下沉到普通业务图元下方 */
        zIndex: isImage || isBuiltinShape ? -5 : 0,
        width: useDecoSize ? defaultDecoSize : w,
        height: useDecoSize ? defaultDecoSize : h,
        elementKind: scene.elementKind,
        shape: isStage || isImage || isBuiltinShape ? "rect" : kindConfig == null ? void 0 : kindConfig.defaultShape,
        dataBinding: dataBinding2,
        ...isImage ? { imageUrl: "" } : {},
        ...isBuiltinShape ? { builtinShapeKey: initialBuiltinShapeKey } : {}
      });
      let dataBinding;
      if (policy !== "none" && pickKey) {
        const dsList = (dataSources == null ? void 0 : dataSources[pickKey]) ?? [];
        if (dsList.length === 0) {
          dataBinding = {
            dataSourceKey: pickKey,
            recordId: `new_${Date.now()}`
          };
        } else if (recordIdsToPlace.length === 0) {
          if (policy === "required") {
            import_antd.message.warning("请先在侧栏选择数据源与数据行，再落位");
            return false;
          }
        } else if (recordIdsToPlace.length === 1) {
          const rid = recordIdsToPlace[0];
          const record = dsList.find((r) => r.id === rid);
          if (!record) {
            import_antd.message.error("所选记录不存在，请重新选择数据行");
            return false;
          }
          const cand = {
            dataSourceKey: pickKey,
            recordId: rid
          };
          if (duplicateBinding(config.sceneElements, cand)) {
            import_antd.message.warning("该数据记录已在平面图中绑定，请勿重复添加");
            return false;
          }
          dataBinding = cand;
        } else {
          const newEls = [];
          let skippedDup = 0;
          let skippedMissing = 0;
          let placeIndex = 0;
          const seenInBatch = /* @__PURE__ */ new Set();
          recordIdsToPlace.forEach((rid) => {
            const record = dsList.find((r) => r.id === rid);
            if (!record) {
              skippedMissing += 1;
              return;
            }
            const cand = {
              dataSourceKey: pickKey,
              recordId: rid
            };
            if (seenInBatch.has(rid) || duplicateBinding(config.sceneElements, cand)) {
              skippedDup += 1;
              return;
            }
            seenInBatch.add(rid);
            const row = record;
            const placementName2 = String((row == null ? void 0 : row.name) ?? rid);
            newEls.push(
              buildOneElement(
                cand,
                contentX + placeIndex * BATCH_PLACE_OFFSET,
                contentY + placeIndex * BATCH_PLACE_OFFSET,
                placementName2
              )
            );
            placeIndex += 1;
          });
          if (skippedDup > 0) {
            import_antd.message.warning(`已跳过 ${skippedDup} 条已在平面图中绑定的记录`);
          }
          if (skippedMissing > 0) {
            import_antd.message.warning(`有 ${skippedMissing} 条记录不存在，已跳过`);
          }
          if (newEls.length === 0) {
            import_antd.message.warning("没有可落位的记录");
            return false;
          }
          commitDraft(
            (prev) => prev ? {
              ...prev,
              sceneElements: [...prev.sceneElements ?? [], ...newEls]
            } : prev
          );
          return true;
        }
      }
      const placementName = (() => {
        var _a3, _b3;
        if (isStage) return import_floorMapStageDefaults.STAGE_DECO_DEFAULT.name;
        if (isImage) return import_utils.locales.getText(I18N_PLACEMENT_FALLBACK_IMAGE);
        const db = dataBinding;
        const rid = recordIdsToPlace[0];
        if (db && rid) {
          const row = (_a3 = dataSources == null ? void 0 : dataSources[db.dataSourceKey]) == null ? void 0 : _a3.find(
            (r) => r.id === rid
          );
          return String((row == null ? void 0 : row.name) ?? rid);
        }
        return ((_b3 = kindConfig == null ? void 0 : kindConfig.defaultPresentation) == null ? void 0 : _b3.title) ?? "";
      })();
      const newEl = buildOneElement(
        dataBinding,
        contentX,
        contentY,
        placementName
      );
      commitDraft(
        (prev) => prev ? { ...prev, sceneElements: [...prev.sceneElements ?? [], newEl] } : prev
      );
      return true;
    },
    [config, currentCanvasId, dataSources]
  );
  const handleCanvasPlaceClick = (0, import_react.useCallback)(
    (e) => {
      if (!placeMode || placeMode.type !== "scene" || !config || !currentCanvasId)
        return;
      const target = e.target;
      if (!target.classList.contains(placeOverlayClass)) return;
      const { x: ox, y: oy } = contentOffsetRef.current;
      const contentX = Math.round(e.nativeEvent.offsetX - ox);
      const contentY = Math.round(e.nativeEvent.offsetY - oy);
      if (applyScenePlacementAtCoords(contentX, contentY, placeMode)) {
        setPlaceMode(null);
      }
    },
    [
      placeMode,
      config,
      currentCanvasId,
      applyScenePlacementAtCoords,
      placeOverlayClass
    ]
  );
  const placeSceneElementFromPaletteDrop = (0, import_react.useCallback)(
    (contentX, contentY, scene) => {
      if (applyScenePlacementAtCoords(contentX, contentY, scene)) {
        setPlaceMode(null);
      }
    },
    [applyScenePlacementAtCoords]
  );
  const handleSave = (0, import_react.useCallback)(() => {
    if (!draftConfig || !onSave) return;
    setSaving(true);
    try {
      onSave(draftConfig);
      setSavedBaselineConfig(draftConfig);
    } finally {
      setSaving(false);
    }
  }, [draftConfig, onSave]);
  const discardDraft = (0, import_react.useCallback)(() => {
    if (!floorMapConfigProp) {
      replaceDraft(null);
      setSavedBaselineConfig(null);
      return;
    }
    const baseConfig = (0, import_floorMapViewConfigDiff.normalizeFloorMapViewConfigFromProp)(floorMapConfigProp);
    const nextConfig = {
      ...baseConfig,
      canvases: baseConfig.canvases.map((canvas) => {
        const stored = readStoredGridVisible(canvas.id);
        if (stored == null) return canvas;
        return {
          ...canvas,
          mapLayer: { ...canvas.mapLayer ?? {}, showGrid: stored }
        };
      })
    };
    replaceDraft(nextConfig);
    setSavedBaselineConfig(null);
  }, [floorMapConfigProp, replaceDraft]);
  const toggleDraftCanvasShowGrid = (0, import_react.useCallback)(() => {
    commitDraft((prev) => {
      if (!prev || !currentCanvasId) return prev;
      return {
        ...prev,
        canvases: prev.canvases.map((c) => {
          var _a2;
          if (c.id !== currentCanvasId) return c;
          const nextShow = !Boolean((_a2 = c.mapLayer) == null ? void 0 : _a2.showGrid);
          writeStoredGridVisible(currentCanvasId, nextShow);
          return {
            ...c,
            mapLayer: { ...c.mapLayer, showGrid: nextShow }
          };
        })
      };
    });
  }, [currentCanvasId]);
  const handleEditPanelUpdate = (0, import_react.useCallback)(
    (patch) => {
      var _a2;
      if (!selectedId) return;
      const bindingPatch = patch.dataBinding;
      if ((bindingPatch == null ? void 0 : bindingPatch.dataSourceKey) && (bindingPatch == null ? void 0 : bindingPatch.recordId)) {
        const cand = bindingPatch;
        if (duplicateBinding((_a2 = configRef.current) == null ? void 0 : _a2.sceneElements, cand, selectedId)) {
          import_antd.message.warning("该数据记录已被其他图元绑定");
          return;
        }
      }
      updateDraftSceneElement(selectedId, patch);
    },
    [selectedId, updateDraftSceneElement]
  );
  const handleSaveRecord = (0, import_react.useCallback)(
    (dataSourceKey, id, newData) => {
      onDataSourceRecordSave == null ? void 0 : onDataSourceRecordSave(dataSourceKey, id, newData);
      setSavingRecord(true);
      setTimeout(() => setSavingRecord(false), 500);
    },
    [onDataSourceRecordSave]
  );
  const handleEditPanelDelete = (0, import_react.useCallback)(() => {
    if (!selectedId) return;
    commitDraft((prev) => {
      if (!prev) return prev;
      return {
        ...prev,
        sceneElements: (prev.sceneElements ?? []).filter(
          (e) => e.instanceId !== selectedId
        )
      };
    });
    setSelectedId(null);
  }, [selectedId]);
  const toggleSelectedLayoutLock = (0, import_react.useCallback)(() => {
    var _a2, _b2;
    if (!selectedId) return;
    const el = (_b2 = (_a2 = configRef.current) == null ? void 0 : _a2.sceneElements) == null ? void 0 : _b2.find(
      (e) => e.instanceId === selectedId
    );
    updateDraftSceneElement(selectedId, {
      layoutTransformLocked: !(el == null ? void 0 : el.layoutTransformLocked)
    });
  }, [selectedId, updateDraftSceneElement]);
  const duplicateSelectedElement = (0, import_react.useCallback)(() => {
    if (!selectedId) return;
    const prev = configRef.current;
    if (!prev) return;
    const el = (prev.sceneElements ?? []).find(
      (e) => e.instanceId === selectedId
    );
    if (!el) return;
    const newId = newInstanceId();
    const copy = {
      ...el,
      instanceId: newId,
      x: Math.round((el.x ?? 0) + BATCH_PLACE_OFFSET),
      y: Math.round((el.y ?? 0) + BATCH_PLACE_OFFSET),
      dataBinding: void 0,
      layoutTransformLocked: false
    };
    commitDraft({
      ...prev,
      sceneElements: [...prev.sceneElements ?? [], copy]
    });
    setSelectedId(newId);
  }, [selectedId]);
  const selectedItem = selectedId ? mergedItems.find((m) => m.id === selectedId) : null;
  const editPanelParams = selectedItem && config && selectedId && !((_c = selectedItem._sceneElement) == null ? void 0 : _c.layoutTransformLocked) ? {
    itemId: selectedId,
    sceneElement: selectedItem._sceneElement,
    onUpdate: handleEditPanelUpdate,
    onSaveRecord: onDataSourceRecordSave ? handleSaveRecord : void 0,
    onClose: () => setSelectedId(null),
    onDelete: config.canvasUi.canEdit ? handleEditPanelDelete : void 0,
    recordFormColumns: dataSourceFormColumns,
    dataSourceRecordForm,
    dataSourceLabels,
    layoutDraftDirty: isLayoutDirty,
    showDataSourceRecordFormBlock
  } : null;
  return {
    config,
    currentCanvasId,
    setCurrentCanvasId,
    selectedId,
    setSelectedId,
    placeMode,
    setPlaceMode,
    mergedItems,
    items,
    saving,
    savingRecord,
    handleAddCanvas,
    handleRemoveCanvas,
    handleRenameCanvas,
    handleUpdateItem,
    handleCanvasPlaceClick,
    handleSave,
    discardDraft,
    placeSceneElementFromPaletteDrop,
    editPanelParams,
    placeOverlayClass,
    isLayoutDirty,
    toggleDraftCanvasShowGrid,
    toggleSelectedLayoutLock,
    duplicateSelectedElement,
    deleteSelectedElement: handleEditPanelDelete,
    undoDraft,
    redoDraft,
    canUndo,
    canRedo
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useFloorMapEditState
});
