"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 modal_exports = {};
__export(modal_exports, {
  AiModalNg: () => AiModalNg,
  INLINE_AI_MODAL_ID: () => INLINE_AI_MODAL_ID,
  StreamingCursor: () => StreamingCursor
});
module.exports = __toCommonJS(modal_exports);
var import_react_dom = require("@floating-ui/react-dom");
var import_design_system = require("@wix/design-system");
var import_plugin_image_viewer_global = require("@wix/ricos/css/plugin-image-viewer.global.inject");
var import_ricos_viewer_global = require("@wix/ricos/css/ricos-viewer.global.inject");
var import_wix_ui_icons_common = require("@wix/wix-ui-icons-common");
var import_lodash = __toESM(require("lodash"));
var import_react = __toESM(require("react"));
var import_react_dom2 = __toESM(require("react-dom"));
var import_types = require("./../ricos-content/truncateContent/types.js");
var import_editor_context = require("./../ricos-context/editor-context.js");
var import_ricos_context = require("./../ricos-context/index.js");
var import_ricos_context2 = require("./../ricos-context/ricos-context.js");
var import_v1 = require("./../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_ricos_viewer_next = require("./../ricos-viewer-next/index.js");
var import_floating_container = require("./../_shared/floating-container.js");
var import_handle_file_upload = require("./../_shared/handle-file-upload.js");
var import_log_invariant = require("./../_shared/log-invariant.js");
var import_prompt_input_area = require("./../_shared/prompt-input-area/prompt-input-area.js");
var import_quick_start_viewer_plugins = require("./../_shared/quick-start-viewer-plugins/quick-start-viewer-plugins.js");
var import_wix_instance_context = require("./../_shared/request-service-provider/wix-instance-context.js");
var import_some_editor_props_context = require("./../_shared/some-editor-props-context.js");
var import_uncreachable = require("./../_shared/uncreachable.js");
var import_viewer = require("./../plugin-card/viewer.js");
var import_toolbar_boundary = require("./../toolbars-v3/toolbar-boundary.js");
var import_cursor_context = require("./cursor-context.js");
var import_data_hooks = require("./data-hooks.js");
var import_error_boundary = require("./error-boundary.js");
var import_execute_prompt = require("./execute-prompt.js");
var import_html_placeholder = require("./html-placeholder.js");
var import_image_placeholder = require("./image-placeholder.js");
var import_inline_ai_context_provider = require("./inline-ai-context-provider.js");
var import_modal_scss = __toESM(require("./modal-scss.js"));
var import_pager_api = require("./pager-api.js");
var import_pager = require("./pager.js");
var import_pending_widget_placeholder = require("./pending-widget-placeholder.js");
var import_spinner = require("./spinner.js");
var import_types2 = require("./types.js");
const useActivePageFormat = (cardPluginConfig) => {
  const { adapter } = (0, import_react.useContext)(import_editor_context.EditorContext);
  const storage = adapter?.tiptapEditor?.storage?.[import_v1.Node_Type.CARD];
  const [format, setFormat] = import_react.default.useState(
    () => storage?.activePageFormat?.name ?? cardPluginConfig?.initialPageFormat
  );
  import_react.default.useEffect(() => {
    if (!storage?.onPageFormatChange) {
      return;
    }
    const update = () => setFormat(storage.activePageFormat?.name);
    storage.onPageFormatChange.add(update);
    return () => {
      storage.onPageFormatChange.delete(update);
    };
  }, [storage]);
  return format;
};
const INLINE_AI_MODAL_ID = "inline-ai";
const defaultState = {
  type: "typing",
  value: ""
};
const AiModalNg = import_react.default.forwardRef((props, _ref) => {
  const [_invocationId] = import_react.default.useState(() => crypto.randomUUID());
  const invocationId = props.invocationId ?? _invocationId;
  const { adapter } = (0, import_react.useContext)(import_editor_context.EditorContext);
  const { t } = (0, import_react.useContext)(import_ricos_context2.RicosContext) || {};
  const { uploadService } = (0, import_react.useContext)(import_ricos_context.UploadContext) || {};
  const devService = (0, import_ricos_context.useDevService)();
  const wixInstance = (0, import_wix_instance_context.useWixInstanceService)();
  const editorProps = (0, import_some_editor_props_context.useEditorProps)();
  const editorPlugins = (0, import_react.useContext)(import_ricos_context.PluginsContext);
  const pluginConfig = editorPlugins?.getConfig(import_types2.INLINE_AI_PLUGIN_TYPE);
  const { state, setState, stop } = (0, import_inline_ai_context_provider.useInlineAiState)(invocationId, defaultState);
  const executePrompt = (0, import_execute_prompt.useExecutePrompt)(pluginConfig.aiProjectId, pluginConfig.useWixelWidgets);
  const SelectedPromptInputArea = pluginConfig?.useWixelWidgets ? import_prompt_input_area.WidgetPromptInputArea : import_prompt_input_area.PromptInputArea;
  import_react.default.useEffect(() => {
    if (state.type === "closed") {
      modalService.closeModal(INLINE_AI_MODAL_ID);
      const actionableMessageCount = state.messages.filter(
        (m) => m.type === "insert" || m.type === "replace"
      ).length;
      const shouldEnablePreviewMode = actionableMessageCount > 1;
      const accepted = state.messages.filter(messageIsAcceptable).sort(orderInsertsFirst).map((m) => {
        const position = m.aiRegion ?? (m.type === "insert" ? { type: "afterNode", id: m.after || void 0 } : {
          type: "range",
          from: m.from,
          to: m.to,
          originalNodesRef: m.originalNodesRef
        });
        return { nodes: m.nodes, position };
      });
      queueMicrotask(() => {
        if (shouldEnablePreviewMode) {
          const storedMessages = state.messages;
          const storedChunks = state.chunks;
          const storedPrompt = state.prompt;
          adapter.tiptapEditor.commands.pushActionItem(() => {
            queueMicrotask(() => {
              const isModalOpen = modalService.isModalOpen(INLINE_AI_MODAL_ID);
              if (isModalOpen) {
                adapter.tiptapEditor.commands.removeAllAiRegions();
                modalService.closeModal(INLINE_AI_MODAL_ID);
                setState({
                  type: "closed",
                  messages: storedMessages,
                  chunks: storedChunks,
                  prompt: storedPrompt
                });
              } else {
                adapter.tiptapEditor.commands.undo();
              }
            });
          });
          adapter.tiptapEditor.commands.acceptRegions(accepted);
          adapter.tiptapEditor.commands.removeAllAiRegions();
          adapter.tiptapEditor.commands.pushActionItem(() => {
            queueMicrotask(() => {
              adapter.tiptapEditor.commands.undo();
              setState({
                type: "preview",
                // Clear aiRegion so useAiRegions creates fresh overlays
                messages: storedMessages.map((m) => {
                  if (m.type === "insert" || m.type === "replace") {
                    const { aiRegion, ...rest } = m;
                    return rest;
                  }
                  return m;
                }),
                activeMessageIndex: storedMessages.findLastIndex((m) => m.type !== "text"),
                chunks: storedChunks,
                prompt: storedPrompt
              });
              modalService.openModal({
                id: INLINE_AI_MODAL_ID,
                Component: AiModalNg,
                componentProps: {
                  invocationId,
                  onThemeChange: props.onThemeChange,
                  getCurrentTheme: props.getCurrentTheme
                },
                type: "exclusive",
                layout: "manual",
                positioning: {
                  referenceElement: getFakeReferenceElement(adapter.tiptapEditor),
                  placement: "bottom"
                },
                returnFocusToEditor: false
              });
            });
          });
        } else {
          adapter.tiptapEditor.commands.acceptRegions(accepted);
          adapter.tiptapEditor.commands.removeAllAiRegions();
        }
      });
      props.onDone?.({ type: "done" });
    }
    if (state.type === "error") {
      if (props.headless) {
        modalService.closeModal(INLINE_AI_MODAL_ID);
      }
      adapter.tiptapEditor.commands.removeAllAiRegions();
      props.onDone?.({ type: "error" });
    }
    if (state.type === "typing") {
      queueMicrotask(() => {
        adapter.tiptapEditor.commands.removeAllAiRegions();
      });
    }
  }, [state.type]);
  const ref = import_react.default.useRef(null);
  const { getPublicCommands } = (0, import_react.useContext)(import_editor_context.EditorContext);
  const modalService = (0, import_react.useContext)(import_ricos_context.ModalServiceContext);
  import_react.default.useEffect(() => {
    if (state.type === "typing") {
      if (ref.current) {
        ref.current.focus();
      }
    }
  }, [state.type, ref.current]);
  const tiptapEditor = adapter.tiptapEditor;
  switch (state.type) {
    case "typing": {
      const attachments = state.attachments ?? [];
      const hasFileUpload = Boolean(uploadService);
      const handleFileUploadFn = async () => {
        if (!uploadService) {
          return;
        }
        await (0, import_handle_file_upload.handleFileUpload)({
          pluginId: "inline-ai",
          services: {
            uploadService,
            devService,
            wixInstance,
            editorProps,
            modals: modalService
          },
          callbacks: {
            onLoadingStart: (attachment) => {
              setState((s) => {
                if (s.type !== "typing") {
                  return s;
                }
                return {
                  ...s,
                  attachments: [...s.attachments ?? [], attachment]
                };
              });
            },
            onSuccess: (attachmentId, attachment) => {
              setState((s) => {
                if (s.type !== "typing") {
                  return s;
                }
                const existingAttachment = (s.attachments ?? []).find((a) => a.id === attachmentId);
                return {
                  ...s,
                  attachments: existingAttachment ? (s.attachments ?? []).map((a) => a.id === attachmentId ? attachment : a) : [...s.attachments ?? [], attachment]
                };
              });
            },
            onError: (attachmentId, attachment) => {
              setState((s) => {
                if (s.type !== "typing") {
                  return s;
                }
                const existingAttachment = (s.attachments ?? []).find((a) => a.id === attachmentId);
                if (!existingAttachment) {
                  return s;
                }
                const errorAttachment = {
                  id: attachmentId,
                  status: "error",
                  file: existingAttachment.file,
                  error: attachment.error
                };
                return {
                  ...s,
                  attachments: (s.attachments ?? []).map(
                    (a) => a.id === attachmentId ? errorAttachment : a
                  )
                };
              });
            }
          }
        });
      };
      return /* @__PURE__ */ import_react.default.createElement(
        import_floating_container.FloatingContainer,
        {
          ...props,
          state: "overlay",
          editorContainer: tiptapEditor.options.element,
          onClickOutside: () => setState(toClosed)
        },
        /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": import_data_hooks.INLINE_AI_MODAL_ROOT }, /* @__PURE__ */ import_react.default.createElement(
          SelectedPromptInputArea,
          {
            ref,
            dataHook: "inline-ai-prompt-input",
            onChange: (x) => setState((prev) => ({
              type: "typing",
              value: x,
              attachments: "attachments" in prev ? prev.attachments : []
            })),
            onSubmit: () => {
              const selection = getPublicCommands().getSelectionSlice() ?? [];
              const uploadedFiles = attachments.filter((a) => a.status === "ok").map((a) => ({
                fileUrl: a.file.url,
                mimeType: a.file.type
              })) ?? [];
              const interceptResult = props.interceptInlinePrompt?.(
                state.value,
                selection,
                uploadedFiles,
                invocationId
              );
              if (interceptResult === "replace") {
                return;
              }
              if (interceptResult === "stop") {
                setState(toClosed);
                modalService.closeModal(INLINE_AI_MODAL_ID);
                return;
              }
              if (!executePrompt) {
                (0, import_log_invariant.logInvariant)(new Error("Inline AI service not available"));
                return;
              }
              executePrompt({
                document: getPublicCommands().getContent(),
                prompt: state.value,
                selection,
                getCurrentTheme: props.getCurrentTheme,
                invocationId,
                onThemeChange: props.onThemeChange,
                files: attachments.filter((a) => a.status === "ok").map((a) => ({
                  fileUrl: a.file.url,
                  mimeType: a.file.type,
                  fileName: a.file.name ?? ""
                })) ?? []
              });
            },
            onCancel: () => {
            },
            value: state.value,
            zIndex: 1e3,
            maxLength: 1e3,
            attachments,
            onRemoveAttachment: (id) => {
              setState((s) => {
                if (s.type !== "typing") {
                  return s;
                }
                return {
                  ...s,
                  attachments: (s.attachments ?? []).filter((a) => a.id !== id)
                };
              });
            },
            fileUploadFn: hasFileUpload ? handleFileUploadFn : void 0
          }
        ))
      );
    }
    case "pending":
      if (props.headless) {
        return null;
      }
      return /* @__PURE__ */ import_react.default.createElement(
        import_floating_container.FloatingContainer,
        {
          ...props,
          state: "top",
          editorContainer: tiptapEditor.options.element,
          onClickOutside: () => {
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              display: "flex",
              justifyContent: "center",
              alignItems: "center"
            }
          },
          /* @__PURE__ */ import_react.default.createElement(import_spinner.Spinner, { onClick: () => stop({ headless: props.headless ?? false }) })
        )
      );
    case "streaming": {
      const aiMessages = state.messages;
      return /* @__PURE__ */ import_react.default.createElement(
        import_floating_container.FloatingContainer,
        {
          ...props,
          state: "top",
          editorContainer: tiptapEditor.options.element,
          onClickOutside: () => {
          }
        },
        !props.headless && /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              display: "flex",
              justifyContent: "center",
              alignItems: "center"
            }
          },
          /* @__PURE__ */ import_react.default.createElement(import_spinner.Spinner, { onClick: () => stop({ headless: props.headless ?? false }) })
        ),
        /* @__PURE__ */ import_react.default.createElement(
          AiRegionStreams,
          {
            closeModal: () => setState(toClosed),
            headless: props.headless,
            completed: false,
            aiMessages,
            activeMessageIndex: aiMessages.findLastIndex((m) => m.type !== "text"),
            setActiveMessageIndex: () => {
            },
            setAiMessages: (action) => {
              setState((s) => {
                if (s.type === "streaming") {
                  return {
                    ...s,
                    messages: typeof action === "function" ? action(s.messages) : action
                  };
                } else {
                  return s;
                }
              });
            },
            onAcceptAll: () => setState(toClosed),
            onRejectAll: () => setState(toRejected),
            t,
            generatingLabel: props.generatingLabel
          }
        )
      );
    }
    case "preview": {
      const aiMessages = state.messages;
      const textFromTextResponse = aiMessages.filter((m) => m.type === "text").map((m) => m.text).join("\n");
      const noActionMessages = !aiMessages.length || aiMessages.every((m) => m.type === "text");
      if (noActionMessages && props.headless) {
        return null;
      }
      if (noActionMessages) {
        return /* @__PURE__ */ import_react.default.createElement(
          import_floating_container.FloatingContainer,
          {
            ...props,
            state: "top",
            editorContainer: tiptapEditor.options.element,
            onClickOutside: () => setState(toClosed)
          },
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: import_modal_scss.default.textResponseContainer,
              "data-hook": import_data_hooks.INLINE_AI_TEXT_RESPONSE_CONTAINER
            },
            textFromTextResponse,
            /* @__PURE__ */ import_react.default.createElement(
              import_design_system.CloseButton,
              {
                size: "medium",
                className: import_modal_scss.default.closeButton,
                onClick: () => setState(toClosed)
              }
            )
          )
        );
      }
      return /* @__PURE__ */ import_react.default.createElement(
        import_floating_container.FloatingContainer,
        {
          ...props,
          state: "top",
          editorContainer: tiptapEditor.options.element,
          onClickOutside: (e) => {
            if (e.target instanceof Element && e.target.closest(".ProseMirror")) {
              setState(toClosed);
            }
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          AiRegionStreams,
          {
            closeModal: () => setState(toClosed),
            headless: false,
            completed: true,
            aiMessages,
            activeMessageIndex: state.activeMessageIndex,
            setActiveMessageIndex: (index) => {
              setState((s) => {
                if (s.type !== "preview") {
                  return s;
                }
                return { ...s, activeMessageIndex: index };
              });
            },
            setAiMessages: (action) => {
              setState((s) => {
                if (s.type === "preview") {
                  return {
                    ...s,
                    messages: typeof action === "function" ? action(s.messages) : action
                  };
                } else {
                  return s;
                }
              });
            },
            onAcceptAll: () => setState(toClosed),
            onRejectAll: () => setState(toRejected),
            t,
            generatingLabel: props.generatingLabel
          }
        )
      );
    }
    case "error": {
      if (props.headless) {
        return null;
      }
      return /* @__PURE__ */ import_react.default.createElement(
        import_floating_container.FloatingContainer,
        {
          ...props,
          state: "top",
          editorContainer: tiptapEditor.options.element,
          onClickOutside: () => setState(toClosed)
        },
        /* @__PURE__ */ import_react.default.createElement("div", { className: import_modal_scss.default.errorResponseContainer, "data-hook": import_data_hooks.INLINE_AI_ERROR_CONTAINER }, state.error.message, /* @__PURE__ */ import_react.default.createElement(
          import_design_system.CloseButton,
          {
            size: "medium",
            className: import_modal_scss.default.closeButton,
            onClick: () => setState({ type: "typing", value: state.prompt })
          }
        ))
      );
    }
    case "closed": {
      return null;
    }
    default: {
      (0, import_log_invariant.logInvariant)((0, import_uncreachable.unreachable)(state));
      return /* @__PURE__ */ import_react.default.createElement("div", null);
    }
  }
});
const StreamingCursor = () => {
  const cursorCtx = (0, import_react.useContext)(import_cursor_context.CursorContext);
  const isVisible = cursorCtx?.cursorState.showCursor ?? false;
  const label = cursorCtx?.cursorState.label;
  const cursorAnchorRef = cursorCtx?.cursorAnchorRef ?? null;
  const boundary = (0, import_toolbar_boundary.useToolbarBoundary)();
  const zIndexService = (0, import_react.useContext)(import_ricos_context.ZIndexContext);
  const referenceElement = (0, import_react.useMemo)(
    () => ({
      getBoundingClientRect: () => {
        const anchor = cursorAnchorRef?.current;
        if (!anchor) {
          return new DOMRect(0, 0, 0, 0);
        }
        const anchorRect = anchor.getBoundingClientRect();
        return new DOMRect(anchorRect.left, anchorRect.top, 0, anchorRect.height);
      }
    }),
    [cursorAnchorRef, isVisible]
  );
  const {
    x,
    y,
    refs: { setReference, setFloating },
    strategy,
    middlewareData
  } = (0, import_react_dom.useFloating)({
    placement: "right-start",
    middleware: [
      // Hide when reference element is gone or escaped boundary
      (0, import_react_dom.hide)({ strategy: "referenceHidden" }),
      ...boundary ? [(0, import_react_dom.hide)({ strategy: "escaped", boundary })] : []
    ],
    whileElementsMounted: (referenceEl, floatingEl, update) => (0, import_react_dom.autoUpdate)(referenceEl, floatingEl, update, {
      animationFrame: true
    })
  });
  (0, import_react.useEffect)(() => {
    setReference(referenceElement);
  }, [setReference, referenceElement]);
  const isHidden = !isVisible || middlewareData.hide?.referenceHidden || middlewareData.hide?.escaped || x === null && y === null;
  return /* @__PURE__ */ import_react.default.createElement(
    "span",
    {
      ref: setFloating,
      className: import_modal_scss.default.streamingCursor,
      "data-hook": import_data_hooks.INLINE_AI_STREAMING_CURSOR,
      style: {
        position: strategy,
        left: x ?? 0,
        top: y ?? 0,
        pointerEvents: "none",
        display: isHidden ? "none" : "block",
        zIndex: zIndexService?.getZIndex("DIALOG") ?? 10
      }
    },
    label && /* @__PURE__ */ import_react.default.createElement("span", { className: import_modal_scss.default.streamingCursorFlag, "data-hook": import_data_hooks.INLINE_AI_STREAMING_CURSOR_FLAG }, label)
  );
};
const getCardIndexOffset = (editor, message) => {
  if (!editor) {
    return 0;
  }
  const doc = editor.state.doc;
  const targetId = message.type === "replace" ? message.from : message.after;
  if (!targetId) {
    return 0;
  }
  let offset = 0;
  let found = false;
  doc.descendants((node, _pos) => {
    if (found) {
      return false;
    }
    if (node.attrs.id === targetId) {
      found = true;
      if (message.type === "insert" && node.type.name === "CARD") {
        offset++;
      }
      return false;
    }
    if (node.type.name === "CARD") {
      offset++;
      return false;
    }
  });
  return offset;
};
const getReplacedCardCount = (editor, message) => {
  if (!editor) {
    return 0;
  }
  const doc = editor.state.doc;
  let count = 0;
  let inRange = false;
  doc.descendants((node, _pos) => {
    if (node.attrs.id === message.from) {
      inRange = true;
    }
    if (inRange && node.type.name === "CARD") {
      count++;
    }
    if (node.attrs.id === message.to) {
      inRange = false;
      return false;
    }
  });
  return count;
};
const AiRegionStreams = ({
  closeModal,
  aiMessages,
  setAiMessages,
  completed,
  headless,
  activeMessageIndex,
  setActiveMessageIndex,
  onAcceptAll,
  onRejectAll,
  t,
  generatingLabel
}) => {
  useAiRegions(aiMessages, setAiMessages);
  const { adapter } = (0, import_react.useContext)(import_editor_context.EditorContext);
  const tiptapEditor = adapter?.tiptapEditor;
  const editorPlugins = (0, import_react.useContext)(import_ricos_context.PluginsContext);
  const cardPluginConfig = editorPlugins?.getConfig(import_v1.Node_Type.CARD);
  const activePageFormat = useActivePageFormat(cardPluginConfig);
  import_react.default.useEffect(() => {
    const storage = tiptapEditor?.storage?.[import_v1.Node_Type.CARD];
    if (!storage) {
      return;
    }
    const insertions = aiMessages.filter(
      (m) => m.type !== "text" && m.type !== "theme" && !m.viewBefore
    ).map((m) => {
      const newCardCount = m.nodes.filter((n) => n.type === import_v1.Node_Type.CARD).length;
      const replacedCardCount = m.type === "replace" ? getReplacedCardCount(tiptapEditor, m) : 0;
      const netCount = newCardCount - replacedCardCount;
      if (netCount === 0) {
        return null;
      }
      const afterCardIndex = getCardIndexOffset(tiptapEditor, m);
      return { afterCardIndex, count: netCount };
    }).filter((v) => v !== null);
    storage.pendingCardInsertions = insertions;
    storage.onPendingCardInsertionsChange.forEach((cb) => cb());
    return () => {
      storage.pendingCardInsertions = [];
      storage.onPendingCardInsertionsChange.forEach((cb) => cb());
    };
  }, [aiMessages, tiptapEditor]);
  const aiMessagesRef = import_react.default.useRef(aiMessages);
  aiMessagesRef.current = aiMessages;
  const lastStreamingMessageIndex = import_react.default.useMemo(() => {
    if (completed) {
      return -1;
    }
    for (let i = aiMessages.length - 1; i >= 0; i--) {
      const msg = aiMessages[i];
      if (msg && msg.type !== "text" && msg.type !== "theme" && !msg.completed) {
        return i;
      }
    }
    return -1;
  }, [aiMessages, completed]);
  const showCursor = !completed && lastStreamingMessageIndex !== -1;
  const cursorCtx = (0, import_react.useContext)(import_cursor_context.CursorContext);
  const resolvedLabel = generatingLabel !== void 0 ? generatingLabel : t("InlineAi_Generating");
  import_react.default.useEffect(() => {
    cursorCtx?.setCursorState({ showCursor, label: resolvedLabel });
    return () => {
      cursorCtx?.setCursorState({ showCursor: false, label: null });
    };
  }, [showCursor, resolvedLabel]);
  const actionableMessageCount = aiMessages.filter((m) => m.type !== "text").length;
  const activeMessage = aiMessages[activeMessageIndex];
  const pagerAPI = (0, import_pager_api.getPagerAPI)(
    aiMessages,
    activeMessageIndex,
    setActiveMessageIndex,
    setAiMessages
  );
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: import_modal_scss.default.bottomContainer }, completed && activeMessage && !headless && /* @__PURE__ */ import_react.default.createElement("div", { className: import_modal_scss.default.bottomControls }, actionableMessageCount > 1 && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_pager.Pager,
    {
      current: activeMessageIndex,
      total: actionableMessageCount,
      onPrev: () => {
        pagerAPI.onPrev();
      },
      onNext: () => {
        pagerAPI.onNext();
      }
    }
  ), /* @__PURE__ */ import_react.default.createElement(VerticalDivider, null), /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Button,
    {
      className: "ai-region-button",
      size: "small",
      priority: "secondary",
      prefixIcon: activeMessage.viewBefore ? /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.RedoSmall, null) : /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.UndoSmall, null),
      onClick: () => {
        pagerAPI.toggleUndo();
      },
      dataHook: import_data_hooks.INLINE_AI_BEFORE_AFTER_BUTTON
    },
    activeMessage.viewBefore ? t("InlineAi_After") : t("InlineAi_Before")
  )), /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Button,
    {
      className: "ai-region-button",
      size: "small",
      priority: "secondary",
      onClick: onAcceptAll,
      dataHook: import_data_hooks.INLINE_AI_ACCEPT_ALL_BUTTON
    },
    t("InlineAi_AcceptAll")
  ), /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Button,
    {
      className: "ai-region-button",
      size: "small",
      priority: "secondary",
      onClick: onRejectAll,
      dataHook: import_data_hooks.INLINE_AI_REJECT_ALL_BUTTON
    },
    t("InlineAi_RejectAll")
  )), aiMessages.map((message, index) => {
    if (!message) {
      return null;
    }
    if (message.type === "text" || message.type === "theme") {
      return null;
    }
    if (!message.aiRegion) {
      return null;
    }
    const overlay = message.aiRegion.overlay;
    if (!overlay) {
      return null;
    }
    return import_react_dom2.default.createPortal(
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "ricos-ai-region-viewer",
          style: { position: "relative" },
          "data-hook": `${import_data_hooks.INLINE_AI_AI_REGION_VIEWER}${completed ? ` ${import_data_hooks.INLINE_AI_AI_REGION_COMPLETED}` : ""}`
        },
        /* @__PURE__ */ import_react.default.createElement(
          Viewer,
          {
            nodes: !message.viewBefore ? message.nodes : message.type === "replace" ? message.originalNodesRef.current || [] : [],
            isRoot: message.isRootLevel,
            isStreaming: !completed,
            isCompleted: !!message.completed,
            isActive: activeMessageIndex === index && pagerAPI.total > 1,
            onHover: () => {
              if (!completed) {
                return;
              }
              if (activeMessageIndex !== index) {
                setActiveMessageIndex(index);
              }
            },
            onClick: () => {
              if (!completed) {
                return;
              }
              closeModal();
            },
            cardPluginConfig,
            activePageFormat,
            cardIndexOffset: getCardIndexOffset(tiptapEditor, message)
          }
        ),
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              display: "flex",
              gap: "8px",
              marginTop: "8px",
              position: "absolute",
              left: "0",
              right: "0",
              zIndex: 1e3
            }
          }
        )
      ),
      overlay
    );
  })));
};
const useAiRegions = (aiMessages, setAiMessages) => {
  const commands = (0, import_react.useContext)(import_editor_context.EditorContext).adapter.tiptapEditor.commands;
  import_react.default.useEffect(() => {
    const aiMessagesWithoutRegions = aiMessages.filter(
      (m) => m.type !== "text" && m.type !== "theme" && !m.aiRegion
    );
    if (aiMessagesWithoutRegions.length === 0) {
      return;
    }
    setAiMessages((aiMessages2) => {
      const newRegions = [];
      const newAiMessages = aiMessages2.map((m) => {
        if (m.type === "text" || m.type === "theme" || m.aiRegion) {
          return m;
        }
        if (m.type === "insert") {
          const aiRegion = {
            type: "afterNode",
            id: m.after || void 0,
            overlay: document.createElement("div")
          };
          newRegions.push(aiRegion);
          return { ...m, aiRegion };
        }
        if (m.type === "replace") {
          const aiRegion = {
            type: "range",
            from: m.from,
            to: m.to,
            overlay: document.createElement("div"),
            originalNodesRef: m.originalNodesRef
          };
          newRegions.push(aiRegion);
          return { ...m, aiRegion };
        }
        (0, import_log_invariant.logInvariant)((0, import_uncreachable.unreachable)(m));
        return m;
      });
      newRegions.length && commands.addAiRegions(newRegions);
      return newAiMessages;
    });
  }, [aiMessages, setAiMessages]);
};
const patchCollapsibleListsDuringStreaming = (nodes) => {
  return nodes.map((node) => {
    if (node.type === "COLLAPSIBLE_LIST") {
      return {
        ...node,
        collapsibleListData: {
          ...node.collapsibleListData,
          initialExpandedItems: import_v1.CollapsibleListData_InitialExpandedItems.ALL
        },
        nodes: node.nodes ? patchCollapsibleListsDuringStreaming(node.nodes) : node.nodes
      };
    }
    if (node.type === "COLLAPSIBLE_ITEM") {
      const children = node.nodes ?? [];
      const hasTitle = children.some((child) => child.type === "COLLAPSIBLE_ITEM_TITLE");
      const hasBody = children.some((child) => child.type === "COLLAPSIBLE_ITEM_BODY");
      if (hasTitle && !hasBody) {
        const emptyBody = {
          type: "COLLAPSIBLE_ITEM_BODY",
          id: `${node.id}-body`,
          nodes: [
            {
              type: "PARAGRAPH",
              id: `${node.id}-body-p`,
              nodes: []
            }
          ]
        };
        return {
          ...node,
          nodes: [...patchCollapsibleListsDuringStreaming(children), emptyBody]
        };
      }
      return {
        ...node,
        nodes: children.length > 0 ? patchCollapsibleListsDuringStreaming(children) : children
      };
    }
    if (node.nodes && node.nodes.length > 0) {
      return {
        ...node,
        nodes: patchCollapsibleListsDuringStreaming(node.nodes)
      };
    }
    return node;
  });
};
const Viewer = import_react.default.memo(
  ({
    nodes,
    isStreaming,
    isCompleted,
    isActive,
    onClick,
    onHover,
    isRoot,
    onContainerRef,
    cardPluginConfig,
    activePageFormat,
    cardIndexOffset
  }) => {
    const containerRef = import_react.default.useRef(null);
    import_react.default.useEffect(() => {
      (0, import_ricos_viewer_global.injectCss)();
      (0, import_plugin_image_viewer_global.injectCss)();
    }, []);
    import_react.default.useEffect(() => {
      onContainerRef?.(containerRef.current);
      return () => onContainerRef?.(null);
    }, [onContainerRef]);
    const nodesWithCursor = isStreaming && !isCompleted ? appendNodeToLastNonEmptyTextContainer(nodes, {
      type: "CURSOR"
    }).nodes : nodes;
    const nodesWithPatchedCollapsibleLists = isStreaming && !isCompleted ? patchCollapsibleListsDuringStreaming(nodesWithCursor) : nodesWithCursor;
    const content = { nodes: nodesWithPatchedCollapsibleLists };
    const { theme } = import_react.default.useContext(import_ricos_context2.RicosContext);
    const helpers = (0, import_some_editor_props_context.useEditorProp)((p) => p.helpers);
    const instance = (0, import_some_editor_props_context.useEditorProp)((p) => p.instance);
    return /* @__PURE__ */ import_react.default.createElement(import_error_boundary.ErrorBoundary, { retryProp: content }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        ref: containerRef,
        style: {
          // backgroundColor: isActive ? '#A8CAFF' : '#E7F0FF',
          background: !isStreaming ? isActive ? bgActive : bgDefault : void 0,
          position: "relative"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_ricos_viewer_next.RicosViewer,
        {
          theme: {
            ...theme,
            customStyles: import_lodash.default.omit(theme.customStyles, "container"),
            breakout: isRoot ? theme?.breakout : void 0
          },
          plugins: [
            {
              config: {},
              type: "html_placeholder",
              // @ts-ignore
              nodeViewRenderers: {
                EXTERNAL: Placeholder
              }
            },
            {
              config: {},
              type: "cursor_placeholder",
              // @ts-ignore - CURSOR is a custom node type for inline AI streaming
              nodeViewRenderers: { CURSOR: CursorPlaceholder }
            },
            ...(0, import_quick_start_viewer_plugins.quickStartViewerPlugins)(),
            (0, import_viewer.pluginCardViewer)({
              mode: "editor",
              renderCardHeader: cardPluginConfig.renderCardHeader,
              pageFormat: activePageFormat,
              cardIndexOffset
            })
          ],
          content,
          helpers,
          instance
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          className: "ai-region-button",
          "data-hook": import_data_hooks.INLINE_AI_AI_REGION_ACCEPT_BUTTON,
          style: {
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            opacity: 0,
            zIndex: 10,
            cursor: "wait"
          },
          onClick,
          onMouseEnter: onHover
        }
      )
    ));
  }
);
const appendNodeToLastNonEmptyTextContainer = (nodes, appendedNode) => {
  for (let i = nodes.length - 1; i >= 0; i--) {
    const node = nodes[i];
    if (!node) {
      continue;
    }
    if ((0, import_types.isTextContainer)(node.type)) {
      if (node.nodes?.length) {
        return {
          nodes: [
            ...nodes.slice(0, i),
            {
              ...node,
              nodes: [...node.nodes ?? [], appendedNode]
            },
            ...nodes.slice(i + 1)
          ],
          appended: true
        };
      }
      continue;
    }
    if (node.nodes?.length) {
      const result = appendNodeToLastNonEmptyTextContainer(node.nodes, appendedNode);
      if (result.appended) {
        return {
          nodes: [
            ...nodes.slice(0, i),
            { ...node, nodes: result.nodes },
            ...nodes.slice(i + 1)
          ],
          appended: true
        };
      }
    }
  }
  return { nodes, appended: false };
};
const CursorPlaceholder = () => {
  const cursorAnchorRef = import_react.default.useContext(import_cursor_context.CursorContext)?.cursorAnchorRef ?? null;
  return /* @__PURE__ */ import_react.default.createElement(
    "span",
    {
      ref: cursorAnchorRef,
      style: {
        display: "inline-block",
        width: 0,
        height: "1em",
        // Inherits the font size of the parent, matching line height
        verticalAlign: "middle"
      }
    }
  );
};
const messageIsAcceptable = (m) => (m.type === "insert" || m.type === "replace") && !m.viewBefore;
const VerticalDivider = () => /* @__PURE__ */ import_react.default.createElement(
  "div",
  {
    style: {
      width: "1px",
      backgroundColor: "#DFE5EB",
      height: "100%"
    }
  }
);
const Placeholder = ({ node, nodeIndex, NodeViewContainer }) => {
  const innerNode = node.externalData;
  return /* @__PURE__ */ import_react.default.createElement(NodeViewContainer, { node: innerNode, nodeIndex }, innerNode.type === "HTML" ? /* @__PURE__ */ import_react.default.createElement(import_html_placeholder.HtmlPlaceholder, { node: innerNode }) : innerNode.type === "IMAGE" ? /* @__PURE__ */ import_react.default.createElement(import_image_placeholder.ImagePlaceholder, { node: innerNode }) : /* @__PURE__ */ import_react.default.createElement(import_pending_widget_placeholder.PendingWidgetPlaceholder, { node }));
};
const orderInsertsFirst = (a, b) => {
  if (a.type === b.type) {
    return 0;
  }
  return a.type === "insert" ? -1 : 1;
};
const getFakeReferenceElement = (editor) => {
  const { view } = editor;
  const { from, to } = view.state.selection;
  const getRect = () => {
    if (from === to) {
      const coords = view.coordsAtPos(from);
      return new DOMRect(coords.left, coords.top, 0, coords.bottom - coords.top);
    }
    const start = view.coordsAtPos(from);
    const end = view.coordsAtPos(to);
    return new DOMRect(
      Math.min(start.left, end.left),
      start.top,
      Math.abs(end.left - start.left),
      end.bottom - start.top
    );
  };
  return {
    getBoundingClientRect: getRect,
    focus: () => view.focus()
  };
};
const toClosed = (s) => s.type === "closed" ? s : {
  type: "closed",
  messages: "messages" in s ? s.messages : [],
  chunks: "chunks" in s ? s.chunks : [],
  prompt: "prompt" in s ? s.prompt : ""
};
const toRejected = (s) => {
  if (s.type === "closed") {
    return s;
  }
  const messages = "messages" in s ? s.messages : [];
  const rejectedMessages = messages.map((m) => {
    if (m.type === "insert" || m.type === "replace") {
      return { ...m, viewBefore: true };
    }
    return m;
  });
  return {
    type: "closed",
    messages: rejectedMessages,
    chunks: "chunks" in s ? s.chunks : [],
    prompt: "prompt" in s ? s.prompt : ""
  };
};
const bgActive = "hsla(0, 10%, 80%, 0.6)";
const bgDefault = "hsla(0, 10%, 80%, 0.4)";
//# sourceMappingURL=modal.js.map
