"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 ai_widget_exports = {};
__export(ai_widget_exports, {
  AiWidget: () => AiWidget,
  PRESETS: () => PRESETS,
  getModalId: () => getModalId
});
module.exports = __toCommonJS(ai_widget_exports);
var import_design_system = require("@wix/design-system");
var import_wix_ui_icons_common = require("@wix/wix-ui-icons-common");
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_selection_context = require("./../../ricos-context/selection-context.js");
var import_modal_service_provider = require("./../../ricos-modals/modal-service-provider.js");
var import_next_schema = require("./../../ricos-schema/next-schema/index.js");
var import_is_only_node_selected = require("./../../_shared/is-only-node-selected.js");
var import_log_invariant = require("./../../_shared/log-invariant.js");
var import_node_styles = require("./../../_shared/node-styles.js");
var import_prompt_input_area = require("./../../_shared/prompt-input-area/prompt-input-area.js");
var import_request_service_provider = require("./../../_shared/request-service-provider/request-service-provider.js");
var import_use_node_attrs = require("./../../_shared/use-node-attrs.js");
var import_wix_rich_content_common = require("./../../wix-rich-content-common/index.js");
var import_helpers = require("./../../tiptap-editor/helpers/index.js");
var import_data_hooks = require("../data-hooks.js");
var import_html_converter = require("../html-converter.js");
var import_ai_widget_scss = __toESM(require("./ai-widget-scss.js"));
var import_do_prompt = require("./do-prompt.js");
var import_error_icon = require("./error-icon.js");
var import_floating_container = require("./floating-container.js");
var import_loader = require("./loader.js");
var import_open_floating_prompt_input = require("./open-floating-prompt-input.js");
var import_preset_bar = require("./preset-bar/preset-bar.js");
var import_use_handle_file_upload = require("./use-handle-file-upload.js");
const FIX_WIDGET_PROMPT = "Widget is broken. Analyze the HTML, find issues and fix them.";
const getModalId = (nodeId) => `FLOATING-PROMPT-INPUT-AI-WIDGET-${nodeId}`;
const AiWidget = (props) => {
  const { htmlNode, children, isFloatingPromptOpen, getColorPalette, htmlAiGeneration } = props;
  const zIndexService = import_react.default.useContext(import_ricos_context.ZIndexContext);
  const { patchPmNodeAttrs, pmNodeAttrs } = (0, import_use_node_attrs.useNodeAttrs)(htmlNode.attrs.id, "HTML");
  const { makeRequest } = (0, import_request_service_provider.useRequestService)();
  const {
    adapter: { tiptapEditor: editor },
    getPublicCommands
  } = import_react.default.useContext(import_ricos_context.EditorContext);
  const modals = (0, import_modal_service_provider.useModalService)();
  const [aiWidgetContainerRef, setAiWidgetContainerRef] = (0, import_react.useState)(null);
  const selection = (0, import_selection_context.useSelection)();
  (0, import_react.useEffect)(() => {
    const isWidgetSelected = (0, import_is_only_node_selected.isOnlyNodeSelected)(editor.state, htmlNode.attrs.id);
    const nodeId = htmlNode.attrs.id;
    if (!modals.isModalOpen(getModalId(nodeId)) && isWidgetSelected) {
      modals.openModal({
        id: getModalId(nodeId),
        Component: FloatingPromptInput,
        componentProps: {
          nodeId,
          onSubmit: handleSubmit,
          getColorPalette
        },
        type: "exclusive",
        layout: "manual",
        positioning: {
          referenceElement: aiWidgetContainerRef,
          placement: "top"
        }
      });
      return;
    }
    if (modals.isModalOpen(getModalId(nodeId)) && !isWidgetSelected) {
      modals.closeModal(getModalId(nodeId));
    }
    return () => {
      if (modals.isModalOpen(getModalId(nodeId))) {
        modals.closeModal(getModalId(nodeId));
      }
    };
  }, [selection, modals]);
  const handleSubmit = import_react.default.useCallback(
    async ({ text, attachments }) => {
      const currentRequestId = (0, import_wix_rich_content_common.uuid)();
      const isAiWidget = pmNodeAttrs?.source === import_next_schema.HTMLData_Source.AI_WIDGET;
      if (isAiWidget && htmlAiGeneration?.canProceed) {
        const canProceed = await htmlAiGeneration.canProceed();
        if (!canProceed) {
          return;
        }
      }
      const stateBeforeLoading = { ...pmNodeAttrs };
      editor.commands.closeHistory();
      patchPmNodeAttrs?.(
        {
          state: {
            status: "LOADING",
            requestId: currentRequestId,
            prompt: { text, fileRefs: attachments }
          }
        },
        { skipHistory: true }
      );
      const currentDocument = getPublicCommands().getContent();
      const ricosNode = import_html_converter.htmlConverter.fromPm.convert(htmlNode.toJSON());
      const widgetPos = (0, import_helpers.findNodeById)(editor.view.state.tr, htmlNode.attrs.id)?.[0]?.pos;
      const documentContext = isAiWidget && widgetPos !== void 0 ? editor.state.doc.textBetween(0, widgetPos, "\n\n", "\n\n").trim() || void 0 : void 0;
      const response = await (0, import_do_prompt.doPrompt)({
        documentContext,
        prompt: text,
        document: currentDocument,
        selection: ricosNode ? [ricosNode] : [],
        files: attachments.filter((file) => file.status === "ok").map((file) => ({
          fileId: file.file.url,
          name: file.file.name
        })),
        makeRequest,
        widgetType: void 0,
        outputMode: isAiWidget ? "WIDGET" : void 0,
        colorPalette: isAiWidget ? getColorPalette?.() : void 0,
        onRequestFailed: isAiWidget ? htmlAiGeneration?.onRequestFailed : void 0
      });
      const tr = editor.view.state.tr;
      const nodeWithPos = (0, import_helpers.findNodeById)(tr, pmNodeAttrs?.id ?? "");
      const { node } = nodeWithPos?.[0] ?? {};
      if (response.type === "SUCCESS" && node?.attrs?.state?.status === "LOADING" && node?.attrs?.state?.requestId === currentRequestId) {
        patchPmNodeAttrs?.(
          {
            ...stateBeforeLoading
          },
          { skipHistory: true }
        );
        if ("widgetId" in response) {
          patchPmNodeAttrs?.({
            widgetId: response.widgetId,
            containerData: response.containerData,
            state: { status: "SUCCESS" }
          });
        } else if ("html" in response) {
          patchPmNodeAttrs?.({
            html: response.html,
            containerData: response.containerData,
            state: { status: "SUCCESS" }
          });
        }
      }
      if (response.type === "ERROR" && node?.attrs?.state?.status === "LOADING" && node?.attrs?.state?.requestId === currentRequestId) {
        patchPmNodeAttrs?.(
          {
            ...stateBeforeLoading
          },
          { skipHistory: true }
        );
        patchPmNodeAttrs?.({
          state: {
            status: "ERROR",
            error: response.error,
            prompt: node?.attrs?.state?.prompt
          }
        });
      }
    },
    [
      patchPmNodeAttrs,
      pmNodeAttrs?.state,
      pmNodeAttrs?.source,
      makeRequest,
      htmlNode,
      getPublicCommands,
      htmlAiGeneration
    ]
  );
  const handleCancel = import_react.default.useCallback(() => {
    patchPmNodeAttrs?.({ state: { status: "SUCCESS", prompt: pmNodeAttrs?.state?.prompt } });
  }, [patchPmNodeAttrs, pmNodeAttrs?.state?.prompt]);
  if (!pmNodeAttrs) {
    (0, import_log_invariant.logInvariant)(new Error("AI Widget: pmNodeAttrs is undefined"));
    return null;
  }
  const hasContent = pmNodeAttrs.html || pmNodeAttrs.widgetId;
  if (!hasContent) {
    if (pmNodeAttrs.state?.status === "ERROR") {
      return /* @__PURE__ */ import_react.default.createElement(
        ErrorDisplay,
        {
          onRetry: () => {
            handleSubmit({
              text: pmNodeAttrs?.state?.prompt?.text ?? "",
              attachments: pmNodeAttrs?.state?.prompt?.fileRefs ?? []
            });
          },
          onNewPrompt: () => {
            patchPmNodeAttrs({
              state: {
                status: "INITIAL"
              }
            });
            (0, import_open_floating_prompt_input.openFloatingPromptInput)({
              nodeId: pmNodeAttrs.id,
              editor,
              modals
            });
          }
        }
      );
    }
    if (pmNodeAttrs.state?.status === "LOADING") {
      return /* @__PURE__ */ import_react.default.createElement(
        LoadingDisplay,
        {
          onStop: () => {
            patchPmNodeAttrs({ state: { status: "INITIAL", prompt: pmNodeAttrs?.state?.prompt } });
            (0, import_open_floating_prompt_input.openFloatingPromptInput)({
              nodeId: pmNodeAttrs.id,
              editor,
              modals
            });
          }
        }
      );
    }
    (0, import_log_invariant.logInvariant)(new Error("AI Widget: pmNodeAttrs.html is undefined"));
    return null;
  }
  return (
    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: isFloatingPromptOpen ? import_ai_widget_scss.default.wrapper : void 0,
        style: {
          width: "100%",
          zIndex: isFloatingPromptOpen ? zIndexService.getZIndex("TOOLBAR") - 1 : 1
        },
        onClick: () => {
          const nodeId = pmNodeAttrs.id;
          if (!modals.isModalOpen(getModalId(nodeId))) {
            modals.openModal({
              id: getModalId(nodeId),
              Component: FloatingPromptInput,
              componentProps: {
                nodeId,
                onSubmit: handleSubmit,
                getColorPalette
              },
              type: "exclusive",
              layout: "manual",
              positioning: {
                referenceElement: aiWidgetContainerRef,
                placement: "top"
              }
            });
            return;
          }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          "data-hook": import_data_hooks.AI_WIDGET_HTML_VIEWER,
          "data-node-id": pmNodeAttrs.id,
          ref: setAiWidgetContainerRef,
          className: (0, import_node_styles.getPluginFocusClassNames)(isFloatingPromptOpen)
        },
        pmNodeAttrs.state?.status === "LOADING" ? /* @__PURE__ */ import_react.default.createElement(LoadingDisplay, { onStop: handleCancel, isIterating: true }) : pmNodeAttrs.state?.status === "ERROR" ? /* @__PURE__ */ import_react.default.createElement(
          ErrorDisplay,
          {
            onRetry: () => {
              handleSubmit({
                text: pmNodeAttrs.state?.prompt?.text ?? "",
                attachments: pmNodeAttrs?.state?.prompt?.fileRefs ?? []
              });
            }
          }
        ) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, children)
      )
    )
  );
};
const FloatingPromptInput = (props) => {
  const { onSubmit, nodeId } = props;
  const { t, lastInteraction } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const promptInputAreaRef = (0, import_react.useRef)(null);
  const modals = (0, import_modal_service_provider.useModalService)();
  const handleFileUpload = (0, import_use_handle_file_upload.useHandleFileUpload)();
  const { patchPmNodeAttrs, pmNodeAttrs } = (0, import_use_node_attrs.useNodeAttrs)(nodeId, "HTML");
  const [promptText, setPromptText] = import_react.default.useState(
    pmNodeAttrs?.state?.prompt?.text ?? ""
  );
  (0, import_react.useEffect)(() => {
    if (lastInteraction === "mouse" && promptInputAreaRef.current) {
      promptInputAreaRef.current.focus();
    }
  }, [lastInteraction, promptInputAreaRef.current]);
  const handleCancel = import_react.default.useCallback(() => {
    if (!pmNodeAttrs) {
      return;
    }
    patchPmNodeAttrs({ state: { status: "SUCCESS", prompt: pmNodeAttrs?.state?.prompt } });
  }, [patchPmNodeAttrs, pmNodeAttrs?.state?.prompt]);
  const handleClickOutside = import_react.default.useCallback(
    (e) => {
      if (!pmNodeAttrs) {
        return;
      }
      const target = e?.target;
      const aiWidgetElement = target?.closest((0, import_wix_rich_content_common.dataHook)(import_data_hooks.AI_WIDGET_HTML_VIEWER));
      if (e && aiWidgetElement?.getAttribute("data-node-id") === pmNodeAttrs.id) {
        return;
      }
      modals.closeModal(getModalId(pmNodeAttrs.id));
    },
    [modals, pmNodeAttrs?.id]
  );
  if (!pmNodeAttrs) {
    return null;
  }
  const isAiWidget = pmNodeAttrs.source === import_next_schema.HTMLData_Source.AI_WIDGET;
  const SelectedPromptInputArea = isAiWidget ? import_prompt_input_area.WidgetPromptInputArea : import_prompt_input_area.PromptInputArea;
  return /* @__PURE__ */ import_react.default.createElement(import_floating_container.FloatingContainer, { ...props, onClickOutside: handleClickOutside }, ({ middlewareData, placement }) => /* @__PURE__ */ import_react.default.createElement(
    SelectedPromptInputArea,
    {
      placeholder: t("HtmlPlugin_AiWidget_Input_Placeholder_Text"),
      ref: promptInputAreaRef,
      maxLength: 1e4,
      zIndex: 1e3,
      forceMultiline: true,
      dataHook: import_data_hooks.PROMPT_INPUT_AREA,
      readonly: pmNodeAttrs.state?.status === "LOADING",
      busy: pmNodeAttrs.state?.status === "LOADING",
      busyValue: pmNodeAttrs.state?.prompt?.text === FIX_WIDGET_PROMPT ? "" : pmNodeAttrs.state?.prompt?.text ?? "",
      value: promptText,
      attachments: pmNodeAttrs.state?.status === "SUCCESS" || pmNodeAttrs.state?.status === "LOADING" ? pmNodeAttrs?.state?.prompt?.fileRefs ?? [] : [],
      onChange: (text) => {
        setPromptText(text);
      },
      onSubmit: () => {
        setPromptText("");
        onSubmit({ text: promptText, attachments: pmNodeAttrs?.state?.prompt?.fileRefs ?? [] });
      },
      onCancel: handleCancel,
      onClose: handleClickOutside,
      minHeight: isAiWidget ? "36px" : "60px",
      style: middlewareData.shift?.y ? {
        borderRadius: 0,
        borderBottom: "1px solid rgba(0, 6, 36, 0.1)",
        boxShadow: "0 0 8px 0 rgba(0, 6, 36, 0.1), 0 6px 6px 0 rgba(0, 6, 36, 0.05)"
      } : placement === "top" ? {
        borderBottomRightRadius: 0,
        borderBottomLeftRadius: 0,
        borderBottom: "none"
      } : {
        borderTopRightRadius: 0,
        borderTopLeftRadius: 0,
        borderTop: "none"
      },
      className: import_ai_widget_scss.default.promptInputArea,
      hasSelectedNode: true,
      fileUploadFn: async () => {
        await handleFileUpload(nodeId);
      },
      onRemoveAttachment: (id) => {
        patchPmNodeAttrs({
          // @ts-expect-error
          state: {
            ...pmNodeAttrs?.state,
            prompt: {
              text: pmNodeAttrs?.state?.prompt?.text ?? "",
              fileRefs: pmNodeAttrs?.state?.prompt?.fileRefs?.filter((file) => file.id !== id) ?? []
            }
          }
        });
      },
      presetBarComponent: isAiWidget ? /* @__PURE__ */ import_react.default.createElement(
        import_preset_bar.PresetList,
        {
          presets: PRESETS,
          onPresetSelect: (preset) => {
            if (pmNodeAttrs.state?.status === "LOADING") {
              return;
            }
            setPromptText(preset.prompt ?? "");
          }
        }
      ) : /* @__PURE__ */ import_react.default.createElement(
        import_preset_bar.PresetBar,
        {
          presets: PRESETS,
          onPresetSelect: (preset) => {
            if (pmNodeAttrs.state?.status === "LOADING") {
              return;
            }
            if (preset.id === import_preset_bar.FIX_BUTTON_PRESET.id) {
              setPromptText("");
              onSubmit({
                text: FIX_WIDGET_PROMPT,
                attachments: pmNodeAttrs?.state?.prompt?.fileRefs ?? [],
                shouldFixWidget: true
              });
              return;
            }
            setPromptText(preset.prompt ?? "");
          },
          showFixButton: true
        }
      )
    }
  ));
};
const ErrorDisplay = ({ onRetry, onNewPrompt }) => {
  const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { padding: "48px", direction: "vertical", align: "center", height: "100%", width: "100%" }, /* @__PURE__ */ import_react.default.createElement(import_error_icon.ErrorIcon, null), /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Box,
    {
      direction: "vertical",
      width: "100%",
      align: "center",
      gap: "4px",
      marginTop: "30px",
      marginBottom: "24px"
    },
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Heading, { size: "large" }, t("HtmlPlugin_AiWidget_Error_Message_Title")),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Text, { size: "small", weight: "thin" }, t("HtmlPlugin_AiWidget_Error_Message_Subtitle"))
  ), /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { gap: "24px", align: "center", verticalAlign: "middle" }, onNewPrompt && /* @__PURE__ */ import_react.default.createElement(import_design_system.TextButton, { prefixIcon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.SparklesFilled, null), onClick: onNewPrompt }, t("HtmlPlugin_AiWidget_Error_NewPromptButton")), /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Button,
    {
      priority: "secondary",
      skin: "ai",
      prefixIcon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.RegenerateSparkle, null),
      onClick: onRetry
    },
    t("HtmlPlugin_AiWidget_Error_RetryButton")
  ))));
};
const LoadingDisplay = ({ onStop, isIterating }) => {
  const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  return /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { padding: "48px", direction: "vertical", align: "center", height: "100%", width: "100%" }, /* @__PURE__ */ import_react.default.createElement(import_loader.Loader, null), /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Box,
    {
      direction: "vertical",
      width: "100%",
      align: "center",
      gap: "4px",
      marginTop: "30px",
      marginBottom: "24px"
    },
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Heading, { size: "large" }, isIterating ? t("HtmlPlugin_AiWidget_Loading_Iterating_Title") : t("HtmlPlugin_AiWidget_Loading_Building_Title")),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Text, { size: "small", weight: "thin" }, isIterating ? t("HtmlPlugin_AiWidget_Loading_Iterating_Subtitle") : t("HtmlPlugin_AiWidget_Loading_Building_Subtitle"))
  ), !isIterating && /* @__PURE__ */ import_react.default.createElement(import_design_system.Button, { priority: "secondary", prefixIcon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.StopFilled, null), onClick: onStop }, t("HtmlPlugin_AiWidget_StopButton")));
};
const PRESETS = [
  {
    id: "preset-1",
    label: "More professional",
    prompt: "Refine tone, layout, and typography for a cleaner, more polished look."
  },
  {
    id: "preset-2",
    label: "More playful",
    prompt: "Introduce brighter colors, rounded shapes, or fun micro-interactions."
  },
  {
    id: "preset-3",
    label: "Hover effects",
    prompt: "Suggest subtle transitions or animations on hover."
  },
  {
    id: "preset-4",
    label: "Improve readability",
    prompt: "Enhance text contrast, spacing, and font legibility."
  },
  {
    id: "preset-5",
    label: "Prettier",
    prompt: "Improve overall visual appeal with a more polished design."
  }
];
//# sourceMappingURL=ai-widget.js.map
