/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 hidden_popup_kanban_exports = {};
__export(hidden_popup_kanban_exports, {
  KANBAN_BLOCK_POPUP_PROP_KEYS: () => KANBAN_BLOCK_POPUP_PROP_KEYS,
  KANBAN_CARD_POPUP_PROP_KEYS: () => KANBAN_CARD_POPUP_PROP_KEYS,
  KANBAN_POPUP_ACTION_KEYS: () => KANBAN_POPUP_ACTION_KEYS,
  KANBAN_POPUP_ACTION_UID_SUFFIX_BY_KEY: () => KANBAN_POPUP_ACTION_UID_SUFFIX_BY_KEY,
  buildKanbanInitialItemProps: () => buildKanbanInitialItemProps,
  buildKanbanInitialItemStepParams: () => buildKanbanInitialItemStepParams,
  buildKanbanInitialStepParams: () => buildKanbanInitialStepParams,
  buildKanbanPopupOpenView: () => buildKanbanPopupOpenView,
  ensureKanbanBlockPopupHosts: () => ensureKanbanBlockPopupHosts,
  getKanbanBlockResourceInit: () => getKanbanBlockResourceInit,
  getKanbanInitialPopupSettings: () => getKanbanInitialPopupSettings,
  getKanbanInitialPopupSettingsFromProps: () => getKanbanInitialPopupSettingsFromProps,
  getKanbanPopupActionUid: () => getKanbanPopupActionUid,
  getKanbanPopupActionUse: () => getKanbanPopupActionUse,
  getKanbanPopupStoredSettings: () => getKanbanPopupStoredSettings,
  mergeKanbanPopupSettings: () => mergeKanbanPopupSettings,
  normalizeKanbanPopupConfigureValue: () => normalizeKanbanPopupConfigureValue,
  normalizeKanbanPopupSettings: () => normalizeKanbanPopupSettings,
  projectKanbanBlockPopupHosts: () => projectKanbanBlockPopupHosts,
  projectKanbanBlockPopupHostsInTree: () => projectKanbanBlockPopupHostsInTree,
  replaceKanbanStoredPopupSettings: () => replaceKanbanStoredPopupSettings,
  resolveKanbanInitialPopupOverride: () => resolveKanbanInitialPopupOverride,
  stripKanbanPopupTargetSettingsForResourceChange: () => stripKanbanPopupTargetSettingsForResourceChange
});
module.exports = __toCommonJS(hidden_popup_kanban_exports);
var import_lodash = __toESM(require("lodash"));
var import_default_action_popup = require("./default-action-popup");
var import_service_utils = require("./service-utils");
var import_hidden_popup_contract = require("./hidden-popup-contract");
const KANBAN_POPUP_ACTION_UID_SUFFIX_BY_KEY = {
  quickCreateAction: "-quick-create-action",
  cardViewAction: "-card-view-action"
};
const KANBAN_POPUP_ACTION_KEYS = Object.keys(KANBAN_POPUP_ACTION_UID_SUFFIX_BY_KEY);
const KANBAN_BLOCK_POPUP_PROP_KEYS = [
  "popupMode",
  "popupSize",
  "popupTemplateUid",
  "popupPageModelClass",
  "popupTargetUid",
  "quickCreatePopupSettings"
];
const KANBAN_CARD_POPUP_PROP_KEYS = [
  "openMode",
  "popupSize",
  "popupTemplateUid",
  "pageModelClass",
  "popupTargetUid",
  "cardPopupSettings"
];
const KANBAN_POPUP_PATCH_PATH_BY_ACTION = {
  quickCreateAction: ["kanbanSettings", "popup"],
  cardViewAction: ["cardSettings", "popup"]
};
const KANBAN_POPUP_LOCAL_CONTENT_KEYS = ["blocks", "layout", "saveAsTemplate", "defaultType"];
function normalizeKanbanPopupSettings(actionKey, popupSettings, blockUid) {
  const actionUid = blockUid && actionKey ? getKanbanPopupActionUid(blockUid, actionKey) : void 0;
  return (0, import_hidden_popup_contract.normalizeHiddenPopupSettings)(popupSettings, {
    invalidUids: [blockUid, actionUid],
    preserveApplyBlueprintDefaults: true
  });
}
function stripKanbanPopupLocalContentSettings(popupSettings) {
  if (!import_lodash.default.isPlainObject(popupSettings)) {
    return popupSettings;
  }
  return import_lodash.default.omit(import_lodash.default.cloneDeep(popupSettings), KANBAN_POPUP_LOCAL_CONTENT_KEYS);
}
function hasKanbanPopupLocalContent(popupSettings) {
  return (0, import_default_action_popup.hasFlowSurfaceInlinePopupBlocks)(popupSettings) || !import_lodash.default.isUndefined(popupSettings == null ? void 0 : popupSettings.layout);
}
async function removeKanbanPopupHostLocalContent(runtime, actionUid, transaction) {
  var _a, _b;
  const actionNode = await runtime.repository.findModelById(actionUid, {
    transaction,
    includeAsyncNode: true
  });
  const popupPageUid = String(((_b = (0, import_service_utils.getSingleNodeSubModel)((_a = actionNode == null ? void 0 : actionNode.subModels) == null ? void 0 : _a.page)) == null ? void 0 : _b.uid) || "").trim();
  if (!popupPageUid) {
    return actionNode;
  }
  await runtime.removeNodeTreeWithBindings(popupPageUid, transaction);
  return runtime.repository.findModelById(actionUid, {
    transaction,
    includeAsyncNode: true
  });
}
function getKanbanInitialPopupSettings(actionKey, settings, blockUid) {
  const primaryKey = actionKey === "quickCreateAction" ? "quickCreatePopup" : "cardPopup";
  const legacyKey = actionKey === "quickCreateAction" ? "quickCreatePopupSettings" : "cardPopupSettings";
  const popupSettings = import_lodash.default.isPlainObject(settings == null ? void 0 : settings[primaryKey]) ? settings == null ? void 0 : settings[primaryKey] : import_lodash.default.isPlainObject(settings == null ? void 0 : settings[legacyKey]) ? settings == null ? void 0 : settings[legacyKey] : void 0;
  if (!import_lodash.default.isPlainObject(popupSettings)) {
    return void 0;
  }
  const normalized = normalizeKanbanPopupSettings(actionKey, popupSettings, blockUid);
  const persistable = stripKanbanPopupLocalContentSettings(normalized);
  return Object.keys(persistable || {}).length ? persistable : void 0;
}
function getKanbanInitialPopupSettingsFromProps(actionKey, props, blockUid) {
  if (!import_lodash.default.isPlainObject(props)) {
    return void 0;
  }
  const rawSettings = actionKey === "quickCreateAction" ? (0, import_service_utils.buildDefinedPayload)({
    mode: props.popupMode,
    size: props.popupSize,
    popupTemplateUid: props.popupTemplateUid,
    pageModelClass: props.popupPageModelClass,
    uid: props.popupTargetUid
  }) : (0, import_service_utils.buildDefinedPayload)({
    mode: props.cardOpenMode,
    size: props.cardPopupSize,
    popupTemplateUid: props.cardPopupTemplateUid,
    pageModelClass: props.cardPopupPageModelClass,
    uid: props.cardPopupTargetUid
  });
  const normalized = normalizeKanbanPopupSettings(actionKey, rawSettings, blockUid);
  const persistable = stripKanbanPopupLocalContentSettings(normalized);
  return Object.keys(persistable || {}).length ? persistable : void 0;
}
function getKanbanPopupActionUse(actionKey) {
  return actionKey === "quickCreateAction" ? "KanbanQuickCreateActionModel" : "KanbanCardViewActionModel";
}
function getKanbanPopupActionUid(kanbanUid, actionKey) {
  return `${kanbanUid}${KANBAN_POPUP_ACTION_UID_SUFFIX_BY_KEY[actionKey]}`;
}
function getKanbanBlockResourceInit(blockNode) {
  const resourceInit = import_lodash.default.cloneDeep(import_lodash.default.get(blockNode, ["stepParams", "resourceSettings", "init"]) || {});
  if (resourceInit.collectionName && !resourceInit.dataSourceKey) {
    resourceInit.dataSourceKey = "main";
  }
  return resourceInit;
}
function buildKanbanInitialStepParams(input) {
  var _a, _b, _c, _d;
  const nextStepParams = import_lodash.default.cloneDeep(input.stepParams || {});
  const initialQuickCreateEnabled = import_lodash.default.isBoolean((_a = input.settings) == null ? void 0 : _a.quickCreateEnabled) ? (_b = input.settings) == null ? void 0 : _b.quickCreateEnabled : import_lodash.default.isBoolean((_c = input.props) == null ? void 0 : _c.quickCreateEnabled) ? (_d = input.props) == null ? void 0 : _d.quickCreateEnabled : void 0;
  if (import_lodash.default.isBoolean(initialQuickCreateEnabled) && !import_lodash.default.has(nextStepParams, ["kanbanSettings", "quickCreate"])) {
    import_lodash.default.set(nextStepParams, ["kanbanSettings", "quickCreate"], {
      quickCreateEnabled: initialQuickCreateEnabled
    });
  }
  const quickCreatePopup = import_lodash.default.has(nextStepParams, ["kanbanSettings", "popup"]) ? import_lodash.default.get(nextStepParams, ["kanbanSettings", "popup"]) : getKanbanInitialPopupSettings("quickCreateAction", input.settings) || getKanbanInitialPopupSettings("quickCreateAction", input.props) || getKanbanInitialPopupSettingsFromProps("quickCreateAction", input.props);
  if (import_lodash.default.isPlainObject(quickCreatePopup)) {
    import_lodash.default.set(nextStepParams, ["kanbanSettings", "popup"], import_lodash.default.cloneDeep(quickCreatePopup));
  }
  const cardPopup = import_lodash.default.has(nextStepParams, ["cardSettings", "popup"]) ? import_lodash.default.get(nextStepParams, ["cardSettings", "popup"]) : getKanbanInitialPopupSettings("cardViewAction", input.settings) || getKanbanInitialPopupSettings("cardViewAction", input.props) || getKanbanInitialPopupSettingsFromProps("cardViewAction", input.props);
  if (import_lodash.default.isPlainObject(cardPopup)) {
    import_lodash.default.set(nextStepParams, ["cardSettings", "popup"], import_lodash.default.cloneDeep(cardPopup));
  }
  return nextStepParams;
}
function buildKanbanInitialItemProps(input) {
  var _a, _b, _c, _d;
  const enableCardClick = import_lodash.default.isBoolean((_a = input.settings) == null ? void 0 : _a.enableCardClick) ? (_b = input.settings) == null ? void 0 : _b.enableCardClick : import_lodash.default.isBoolean((_c = input.props) == null ? void 0 : _c.enableCardClick) ? (_d = input.props) == null ? void 0 : _d.enableCardClick : void 0;
  return (0, import_service_utils.buildDefinedPayload)({
    ...import_lodash.default.isBoolean(enableCardClick) ? { enableCardClick } : {}
  });
}
function buildKanbanInitialItemStepParams(input) {
  var _a, _b, _c, _d;
  const nextStepParams = import_lodash.default.cloneDeep(input.stepParams || {});
  const enableCardClick = import_lodash.default.isBoolean((_a = input.settings) == null ? void 0 : _a.enableCardClick) ? (_b = input.settings) == null ? void 0 : _b.enableCardClick : import_lodash.default.isBoolean((_c = input.props) == null ? void 0 : _c.enableCardClick) ? (_d = input.props) == null ? void 0 : _d.enableCardClick : void 0;
  if (import_lodash.default.isBoolean(enableCardClick) && !import_lodash.default.has(nextStepParams, ["cardSettings", "click"])) {
    import_lodash.default.set(nextStepParams, ["cardSettings", "click"], {
      enableCardClick
    });
  }
  const cardPopup = import_lodash.default.has(nextStepParams, ["cardSettings", "popup"]) ? import_lodash.default.get(nextStepParams, ["cardSettings", "popup"]) : getKanbanInitialPopupSettings("cardViewAction", input.settings) || getKanbanInitialPopupSettings("cardViewAction", input.props) || getKanbanInitialPopupSettingsFromProps("cardViewAction", input.props);
  if (import_lodash.default.isPlainObject(cardPopup)) {
    import_lodash.default.set(nextStepParams, ["cardSettings", "popup"], import_lodash.default.cloneDeep(cardPopup));
  }
  return nextStepParams;
}
function getKanbanPopupStoredSettings(blockNode, actionKey) {
  var _a;
  const itemNode = (0, import_service_utils.getSingleNodeSubModel)((_a = blockNode == null ? void 0 : blockNode.subModels) == null ? void 0 : _a.item);
  const rawPopupSettings = (() => {
    var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
    if (actionKey === "quickCreateAction") {
      if (import_lodash.default.has(blockNode, ["stepParams", "kanbanSettings", "popup"])) {
        const settings = import_lodash.default.get(blockNode, ["stepParams", "kanbanSettings", "popup"]);
        return import_lodash.default.isPlainObject(settings) ? settings : {};
      }
      return (0, import_service_utils.buildDefinedPayload)({
        mode: (_a2 = blockNode == null ? void 0 : blockNode.props) == null ? void 0 : _a2.popupMode,
        size: (_b = blockNode == null ? void 0 : blockNode.props) == null ? void 0 : _b.popupSize,
        popupTemplateUid: (_c = blockNode == null ? void 0 : blockNode.props) == null ? void 0 : _c.popupTemplateUid,
        pageModelClass: (_d = blockNode == null ? void 0 : blockNode.props) == null ? void 0 : _d.popupPageModelClass,
        uid: (_e = blockNode == null ? void 0 : blockNode.props) == null ? void 0 : _e.popupTargetUid
      });
    }
    if (import_lodash.default.has(itemNode, ["stepParams", "cardSettings", "popup"])) {
      const settings = import_lodash.default.get(itemNode, ["stepParams", "cardSettings", "popup"]);
      return import_lodash.default.isPlainObject(settings) ? settings : {};
    }
    return (0, import_service_utils.buildDefinedPayload)({
      mode: (_f = itemNode == null ? void 0 : itemNode.props) == null ? void 0 : _f.openMode,
      size: (_g = itemNode == null ? void 0 : itemNode.props) == null ? void 0 : _g.popupSize,
      popupTemplateUid: (_h = itemNode == null ? void 0 : itemNode.props) == null ? void 0 : _h.popupTemplateUid,
      pageModelClass: (_i = itemNode == null ? void 0 : itemNode.props) == null ? void 0 : _i.pageModelClass,
      uid: (_j = itemNode == null ? void 0 : itemNode.props) == null ? void 0 : _j.popupTargetUid
    });
  })();
  return normalizeKanbanPopupSettings(actionKey, rawPopupSettings, blockNode == null ? void 0 : blockNode.uid);
}
function buildKanbanPopupOpenView(input) {
  const actionUid = getKanbanPopupActionUid(input.blockNode.uid, input.actionKey);
  const resourceInit = input.resourceInit || getKanbanBlockResourceInit(input.blockNode);
  return (0, import_hidden_popup_contract.buildHiddenPopupOpenView)({
    actionUid,
    resourceInit,
    popupSettings: input.popupSettings ? input.popupSettings : getKanbanPopupStoredSettings(input.blockNode, input.actionKey),
    normalizePopupSettings: (popupSettings) => normalizeKanbanPopupSettings(input.actionKey, popupSettings, input.blockNode.uid)
  });
}
async function normalizeKanbanPopupConfigureValue(input) {
  if (import_lodash.default.isUndefined(input.value)) {
    return void 0;
  }
  if (import_lodash.default.isNull(input.value)) {
    return {};
  }
  const actionUid = getKanbanPopupActionUid(input.blockUid, input.actionKey);
  const normalized = await input.normalizeOpenView(input.actionName, input.value, {
    transaction: input.transaction,
    popupTemplateHostUid: actionUid,
    popupActionContext: {
      hasCurrentRecord: input.actionKey === "cardViewAction"
    }
  });
  return normalizeKanbanPopupSettings(
    input.actionKey,
    {
      ...normalized || {},
      ...import_lodash.default.isPlainObject(input.value) && input.value.tryTemplate === false ? { tryTemplate: false } : {}
    },
    input.blockUid
  );
}
function resolveKanbanInitialPopupOverride(settings, primaryKey, legacyKey) {
  if (!import_lodash.default.isPlainObject(settings)) {
    return void 0;
  }
  if (import_lodash.default.isPlainObject(settings[primaryKey])) {
    return settings[primaryKey];
  }
  if (import_lodash.default.isPlainObject(settings[legacyKey])) {
    return settings[legacyKey];
  }
  return void 0;
}
function mergeKanbanPopupSettings(actionKey, current, value, blockUid) {
  if (!import_lodash.default.isPlainObject(value)) {
    return {};
  }
  const currentBase = import_lodash.default.isPlainObject(current) && (0, import_hidden_popup_contract.hasExplicitHiddenPopupTargetSettings)(value) ? import_lodash.default.pick(import_lodash.default.cloneDeep(current), import_hidden_popup_contract.HIDDEN_POPUP_DISPLAY_KEYS) : current;
  const merged = import_lodash.default.isPlainObject(currentBase) ? { ...import_lodash.default.cloneDeep(currentBase), ...import_lodash.default.cloneDeep(value) } : value;
  return normalizeKanbanPopupSettings(actionKey, merged, blockUid);
}
function stripKanbanPopupTargetSettingsForResourceChange(actionKey, popupSettings, blockUid) {
  return normalizeKanbanPopupSettings(
    actionKey,
    (0, import_hidden_popup_contract.stripHiddenPopupTargetSettings)(popupSettings, { disableTemplateAutoBind: true }),
    blockUid
  );
}
async function replaceKanbanStoredPopupSettings(runtime, blockNode, actionKey, popupSettings, transaction) {
  var _a;
  const targetNode = actionKey === "quickCreateAction" ? blockNode : (0, import_service_utils.getSingleNodeSubModel)((_a = blockNode == null ? void 0 : blockNode.subModels) == null ? void 0 : _a.item);
  if (!(targetNode == null ? void 0 : targetNode.uid)) {
    return;
  }
  const path = KANBAN_POPUP_PATCH_PATH_BY_ACTION[actionKey];
  const nextStepParams = import_lodash.default.cloneDeep(targetNode.stepParams || {});
  if (Object.keys(popupSettings || {}).length) {
    import_lodash.default.set(nextStepParams, path, import_lodash.default.cloneDeep(popupSettings));
  } else {
    (0, import_hidden_popup_contract.unsetHiddenPopupPayloadPathAndPruneEmptyParents)(nextStepParams, path);
  }
  if (import_lodash.default.isEqual(nextStepParams, targetNode.stepParams || {})) {
    return;
  }
  await runtime.repository.patch(
    {
      uid: targetNode.uid,
      stepParams: nextStepParams
    },
    { transaction }
  );
  targetNode.stepParams = nextStepParams;
}
async function persistKanbanPopupSettingsFromOpenView(runtime, blockNode, actionKey, openView, popupSettings, transaction) {
  const storedSettings = (0, import_hidden_popup_contract.buildPersistedHiddenPopupSettingsFromOpenView)({
    openView,
    popupSettings,
    expectedHostUid: getKanbanPopupActionUid(blockNode.uid, actionKey),
    normalizePopupSettings: (settings) => normalizeKanbanPopupSettings(actionKey, settings, blockNode == null ? void 0 : blockNode.uid)
  });
  await replaceKanbanStoredPopupSettings(runtime, blockNode, actionKey, storedSettings, transaction);
}
function mergeKanbanPopupDisplaySettings(actionKey, openView, popupSettings, fallbackOpenView, options = {}) {
  return (0, import_hidden_popup_contract.mergeHiddenPopupDisplaySettings)({
    openView,
    popupSettings,
    fallbackOpenView,
    normalizePopupSettings: (settings) => normalizeKanbanPopupSettings(actionKey, settings),
    preserveOpenViewDisplay: options.preserveOpenViewDisplay,
    preserveOpenViewDisplayFallback: options.preserveOpenViewDisplayFallback
  });
}
async function buildKanbanPopupOpenViewWithTemplate(runtime, input) {
  var _a, _b;
  const actionUid = getKanbanPopupActionUid(input.blockNode.uid, input.actionKey);
  const openView = buildKanbanPopupOpenView(input);
  return runtime.buildPopupOpenViewWithTemplate({
    actionName: `kanban ${input.actionKey}`,
    actionUid,
    openView,
    popupSettings: input.popupSettings,
    existingHost: (0, import_service_utils.getSingleNodeSubModel)((_b = (_a = input.blockNode) == null ? void 0 : _a.subModels) == null ? void 0 : _b[input.actionKey]),
    transaction: input.transaction,
    hasCurrentRecord: input.actionKey === "cardViewAction",
    normalizePopupSettings: (popupSettings) => normalizeKanbanPopupSettings(input.actionKey, popupSettings, input.blockNode.uid),
    mergeDisplaySettings: (nextOpenView, popupSettings, fallbackOpenView) => mergeKanbanPopupDisplaySettings(input.actionKey, nextOpenView, popupSettings, fallbackOpenView)
  });
}
async function resolveKanbanPopupOpenViewWithFallback(runtime, input) {
  const baseOpenView = buildKanbanPopupOpenView(input);
  const openView = await buildKanbanPopupOpenViewWithTemplate(runtime, input);
  return mergeKanbanPopupDisplaySettings(input.actionKey, openView, input.popupSettings, baseOpenView);
}
async function ensureKanbanPopupHostDefaultContent(runtime, input) {
  return runtime.ensurePopupHostDefaultContent({
    actionName: `kanban ${input.actionKey}`,
    actionUid: input.actionUid,
    popupSettings: input.popupSettings,
    transaction: input.transaction,
    hasCurrentRecord: input.actionKey === "cardViewAction",
    mergeDisplaySettings: (openView, popupSettings, fallbackOpenView) => mergeKanbanPopupDisplaySettings(input.actionKey, openView, popupSettings, fallbackOpenView)
  });
}
async function ensureKanbanBlockPopupHosts(runtime, blockNode, transaction, popupSettingsOverrides, options = {}) {
  var _a, _b;
  if (!(blockNode == null ? void 0 : blockNode.uid) || blockNode.use !== "KanbanBlockModel") {
    return blockNode;
  }
  const resourceInit = getKanbanBlockResourceInit(blockNode);
  let changed = false;
  for (const actionKey of KANBAN_POPUP_ACTION_KEYS) {
    let existing = (0, import_service_utils.getSingleNodeSubModel)((_a = blockNode.subModels) == null ? void 0 : _a[actionKey]);
    const expectedUid = getKanbanPopupActionUid(blockNode.uid, actionKey);
    const expectedUse = getKanbanPopupActionUse(actionKey);
    const popupSettingsOverride = (0, import_hidden_popup_contract.resolveHiddenPopupSettingsOverride)(popupSettingsOverrides, actionKey);
    const popupSettings = popupSettingsOverride ?? getKanbanPopupStoredSettings(blockNode, actionKey);
    const explicitPopupSettingsProvided = !!popupSettingsOverrides && Object.prototype.hasOwnProperty.call(popupSettingsOverrides, actionKey);
    const seedOpenView = buildKanbanPopupOpenView({
      blockNode,
      actionKey,
      resourceInit,
      popupSettings
    });
    const displayFallbackOpenView = ((_b = options.displayFallbackOpenViews) == null ? void 0 : _b[actionKey]) || seedOpenView;
    const shouldReplaceExisting = (existing == null ? void 0 : existing.uid) && existing.uid !== expectedUid;
    if (!(existing == null ? void 0 : existing.uid) || shouldReplaceExisting || existing.use !== expectedUse) {
      if (shouldReplaceExisting) {
        await runtime.removeNodeTreeWithBindings(existing.uid, transaction);
      }
      await runtime.repository.upsertModel(
        {
          parentId: blockNode.uid,
          subKey: actionKey,
          subType: "object",
          ...(existing == null ? void 0 : existing.uid) === expectedUid ? import_lodash.default.cloneDeep(existing) : {},
          uid: expectedUid,
          use: expectedUse,
          stepParams: (0, import_hidden_popup_contract.buildHiddenPopupActionStepParams)(
            (existing == null ? void 0 : existing.uid) === expectedUid ? existing.stepParams : {},
            seedOpenView
          )
        },
        { transaction }
      );
      existing = await runtime.repository.findModelById(expectedUid, {
        transaction,
        includeAsyncNode: true
      });
      if (String((seedOpenView == null ? void 0 : seedOpenView.popupTemplateUid) || "").trim()) {
        await runtime.clearFlowTemplateUsagesForNodeTree(expectedUid, transaction);
        await runtime.syncFlowTemplateUsagesForNodeTree(expectedUid, transaction);
      }
      changed = true;
    }
    const hasLocalPopupContent = (0, import_hidden_popup_contract.hiddenPopupHostHasLocalContent)(existing);
    const currentOpenView = (0, import_hidden_popup_contract.resolveHiddenPopupHostOpenView)(existing);
    const normalizedCurrentOpenView = normalizeKanbanPopupSettings(actionKey, currentOpenView, blockNode.uid);
    const popupOpenViewTransition = await (0, import_hidden_popup_contract.resolveHiddenPopupOpenViewTransitionWithCandidate)({
      existing,
      expectedUid,
      expectedUse,
      popupSettings,
      seedOpenView,
      currentOpenView,
      normalizedCurrentOpenView,
      displayFallbackOpenView,
      allowResourceMismatchRebuild: explicitPopupSettingsProvided,
      mergeDisplaySettings: (openView2, popupSettings2, fallbackOpenView, mergeOptions) => mergeKanbanPopupDisplaySettings(actionKey, openView2, popupSettings2, fallbackOpenView, mergeOptions),
      resolveCandidateOpenView: () => resolveKanbanPopupOpenViewWithFallback(runtime, {
        blockNode,
        actionKey,
        resourceInit,
        popupSettings,
        transaction
      })
    });
    const { openView } = popupOpenViewTransition;
    const shouldUpsert = !(existing == null ? void 0 : existing.uid) || existing.use !== expectedUse || !hasLocalPopupContent && !import_lodash.default.isEqual(currentOpenView, openView) || explicitPopupSettingsProvided && !import_lodash.default.isEqual(currentOpenView, openView);
    if (shouldUpsert) {
      if ((existing == null ? void 0 : existing.uid) && existing.uid === expectedUid && !import_lodash.default.isEqual(currentOpenView, openView)) {
        await runtime.reconcilePopupOpenViewTransition(expectedUid, currentOpenView, openView, transaction);
      }
      const shouldRefreshTemplateUsages = !import_lodash.default.isEqual(currentOpenView, openView);
      const nextActionNode = {
        ...(existing == null ? void 0 : existing.uid) && existing.uid === expectedUid ? import_lodash.default.cloneDeep(existing) : {},
        uid: expectedUid,
        use: expectedUse,
        stepParams: (0, import_hidden_popup_contract.buildHiddenPopupActionStepParams)(
          (existing == null ? void 0 : existing.uid) === expectedUid ? existing.stepParams : {},
          openView
        )
      };
      await runtime.repository.upsertModel(
        {
          parentId: blockNode.uid,
          subKey: actionKey,
          subType: "object",
          ...nextActionNode
        },
        { transaction }
      );
      if (shouldRefreshTemplateUsages || String((openView == null ? void 0 : openView.popupTemplateUid) || "").trim()) {
        await runtime.clearFlowTemplateUsagesForNodeTree(expectedUid, transaction);
        if (String((openView == null ? void 0 : openView.popupTemplateUid) || "").trim()) {
          await runtime.syncFlowTemplateUsagesForNodeTree(expectedUid, transaction);
        }
      }
      changed = true;
    }
    let completedLocalContent = false;
    if (explicitPopupSettingsProvided && hasKanbanPopupLocalContent(popupSettings) && runtime.applyPopupHostLocalContent) {
      await runtime.applyPopupHostLocalContent({
        actionName: `kanban ${actionKey}`,
        actionUid: expectedUid,
        popupSettings,
        transaction,
        hasCurrentRecord: actionKey === "cardViewAction"
      });
      existing = await runtime.repository.findModelById(expectedUid, {
        transaction,
        includeAsyncNode: true
      });
      completedLocalContent = true;
    } else if (explicitPopupSettingsProvided && !hasKanbanPopupLocalContent(popupSettings) && (0, import_hidden_popup_contract.buildImplicitHiddenPopupDefaultContent)(popupSettings)) {
      const localContentHost = await runtime.repository.findModelById(expectedUid, {
        transaction,
        includeAsyncNode: true
      });
      if ((0, import_hidden_popup_contract.hiddenPopupHostHasLocalContent)(localContentHost)) {
        existing = await removeKanbanPopupHostLocalContent(runtime, expectedUid, transaction);
        changed = true;
      } else {
        existing = localContentHost;
      }
    }
    const completedDefaultContent = completedLocalContent ? false : await ensureKanbanPopupHostDefaultContent(runtime, {
      actionKey,
      actionUid: expectedUid,
      popupSettings,
      transaction
    });
    if (completedDefaultContent) {
      existing = await runtime.repository.findModelById(expectedUid, {
        transaction,
        includeAsyncNode: true
      });
    }
    const finalOpenView = completedDefaultContent || completedLocalContent ? (0, import_hidden_popup_contract.resolveHiddenPopupHostOpenView)(existing) : openView;
    await persistKanbanPopupSettingsFromOpenView(
      runtime,
      blockNode,
      actionKey,
      finalOpenView,
      popupSettings,
      transaction
    );
    if (existing == null ? void 0 : existing.uid) {
      blockNode.subModels = {
        ...blockNode.subModels || {},
        [actionKey]: existing
      };
    }
    changed = completedDefaultContent || completedLocalContent || changed;
  }
  if (!changed) {
    return blockNode;
  }
  const refreshed = await runtime.repository.findModelById(blockNode.uid, {
    transaction,
    includeAsyncNode: true
  });
  if (refreshed == null ? void 0 : refreshed.uid) {
    return refreshed;
  }
  return blockNode;
}
function projectKanbanBlockPopupHosts(node) {
  var _a;
  if (!node || typeof node !== "object") {
    return node;
  }
  const current = node;
  if (!(current == null ? void 0 : current.uid) || current.use !== "KanbanBlockModel") {
    return node;
  }
  const resourceInit = getKanbanBlockResourceInit(current);
  let nextSubModels = current.subModels;
  let changed = false;
  for (const actionKey of KANBAN_POPUP_ACTION_KEYS) {
    const existing = (0, import_service_utils.getSingleNodeSubModel)((_a = current.subModels) == null ? void 0 : _a[actionKey]);
    const expectedUid = getKanbanPopupActionUid(current.uid, actionKey);
    const expectedUse = getKanbanPopupActionUse(actionKey);
    const popupSettings = getKanbanPopupStoredSettings(current, actionKey);
    const persistedOpenView = (0, import_hidden_popup_contract.resolveHiddenPopupHostOpenView)(existing);
    const seedOpenView = buildKanbanPopupOpenView({
      blockNode: current,
      actionKey,
      resourceInit,
      popupSettings
    });
    const currentOpenView = (0, import_hidden_popup_contract.resolveHiddenPopupHostOpenView)(existing);
    const normalizedCurrentOpenView = normalizeKanbanPopupSettings(actionKey, currentOpenView, current.uid);
    const { openView } = (0, import_hidden_popup_contract.resolveHiddenPopupOpenViewTransition)({
      existing,
      expectedUid,
      expectedUse,
      popupSettings,
      seedOpenView,
      candidateOpenView: seedOpenView,
      currentOpenView,
      normalizedCurrentOpenView,
      preservedOpenView: persistedOpenView,
      resourceMismatchDisplayFallbackOpenView: (0, import_hidden_popup_contract.buildHiddenPopupResourceMismatchDisplayFallbackOpenView)({
        normalizedCurrentOpenView,
        resourceInit,
        popupSettings,
        stripPopupTargetSettingsForResourceChange: (popupSettings2) => stripKanbanPopupTargetSettingsForResourceChange(actionKey, popupSettings2, current.uid),
        buildOpenView: ({ resourceInit: resourceInit2, popupSettings: popupSettings2 }) => buildKanbanPopupOpenView({
          blockNode: current,
          actionKey,
          resourceInit: resourceInit2,
          popupSettings: popupSettings2
        })
      }),
      allowResourceMismatchRebuild: true,
      mergeDisplaySettings: (openView2, popupSettings2, fallbackOpenView, mergeOptions) => mergeKanbanPopupDisplaySettings(actionKey, openView2, popupSettings2, fallbackOpenView, mergeOptions)
    });
    if ((existing == null ? void 0 : existing.uid) === expectedUid && existing.use === expectedUse && import_lodash.default.isEqual(currentOpenView, openView)) {
      continue;
    }
    const nextActionNode = {
      ...(existing == null ? void 0 : existing.uid) === expectedUid ? import_lodash.default.cloneDeep(existing) : {},
      uid: expectedUid,
      use: expectedUse,
      stepParams: (0, import_hidden_popup_contract.buildHiddenPopupActionStepParams)((existing == null ? void 0 : existing.uid) === expectedUid ? existing.stepParams : {}, openView)
    };
    if (!changed) {
      nextSubModels = {
        ...current.subModels || {}
      };
      changed = true;
    }
    nextSubModels[actionKey] = nextActionNode;
  }
  if (!changed) {
    return node;
  }
  return {
    ...current,
    subModels: nextSubModels
  };
}
function projectKanbanBlockPopupHostsInTree(node) {
  if (!node || typeof node !== "object") {
    return node;
  }
  let current = projectKanbanBlockPopupHosts(node);
  let nextSubModels = current == null ? void 0 : current.subModels;
  let changed = current !== node;
  if (!nextSubModels || typeof nextSubModels !== "object") {
    return current;
  }
  for (const [subKey, value] of Object.entries(nextSubModels)) {
    if (Array.isArray(value)) {
      const nextItems = [];
      let itemsChanged = false;
      for (const item of value) {
        const nextItem = projectKanbanBlockPopupHostsInTree(item);
        nextItems.push(nextItem);
        itemsChanged = itemsChanged || nextItem !== item;
      }
      if (!itemsChanged) {
        continue;
      }
      if (!changed) {
        current = {
          ...current,
          subModels: {
            ...nextSubModels
          }
        };
        nextSubModels = current.subModels;
        changed = true;
      }
      nextSubModels[subKey] = nextItems;
      continue;
    }
    const nextValue = projectKanbanBlockPopupHostsInTree(value);
    if (nextValue === value) {
      continue;
    }
    if (!changed) {
      current = {
        ...current,
        subModels: {
          ...nextSubModels
        }
      };
      nextSubModels = current.subModels;
      changed = true;
    }
    nextSubModels[subKey] = nextValue;
  }
  return current;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  KANBAN_BLOCK_POPUP_PROP_KEYS,
  KANBAN_CARD_POPUP_PROP_KEYS,
  KANBAN_POPUP_ACTION_KEYS,
  KANBAN_POPUP_ACTION_UID_SUFFIX_BY_KEY,
  buildKanbanInitialItemProps,
  buildKanbanInitialItemStepParams,
  buildKanbanInitialStepParams,
  buildKanbanPopupOpenView,
  ensureKanbanBlockPopupHosts,
  getKanbanBlockResourceInit,
  getKanbanInitialPopupSettings,
  getKanbanInitialPopupSettingsFromProps,
  getKanbanPopupActionUid,
  getKanbanPopupActionUse,
  getKanbanPopupStoredSettings,
  mergeKanbanPopupSettings,
  normalizeKanbanPopupConfigureValue,
  normalizeKanbanPopupSettings,
  projectKanbanBlockPopupHosts,
  projectKanbanBlockPopupHostsInTree,
  replaceKanbanStoredPopupSettings,
  resolveKanbanInitialPopupOverride,
  stripKanbanPopupTargetSettingsForResourceChange
});
