"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 floating_prompt_input_exports = {};
__export(floating_prompt_input_exports, {
  FLOATING_PROMPT_INPUT_MODAL_ID: () => FLOATING_PROMPT_INPUT_MODAL_ID,
  FloatingPromptInput: () => FloatingPromptInput,
  PRESETS_WIDGETS_CREATE: () => PRESETS_WIDGETS_CREATE
});
module.exports = __toCommonJS(floating_prompt_input_exports);
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_next_schema = require("./../../ricos-schema/next-schema/index.js");
var import_floating_container = require("./../../_shared/floating-container.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_common = require("./common.js");
var import_do_prompt = require("./do-prompt.js");
var import_preset_bar = require("./preset-bar/preset-bar.js");
var import_use_handle_file_upload = require("./use-handle-file-upload.js");
var import_widget_type_selector = require("./widget-type-selector/widget-type-selector.js");
const FLOATING_PROMPT_INPUT_MODAL_ID = "FLOATING-PROMPT-INPUT";
const FloatingPromptInput = ({ nodeId, getColorPalette, ...props }) => {
  const { makeRequest } = (0, import_request_service_provider.useRequestService)();
  const {
    adapter: { tiptapEditor },
    getPublicCommands
  } = import_react.default.useContext(import_ricos_context.EditorContext);
  const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const ref = import_react.default.useRef(null);
  const modalService = (0, import_react.useContext)(import_ricos_context.ModalServiceContext);
  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 (ref.current) {
      ref.current.focus();
    }
  }, [ref.current]);
  if (!pmNodeAttrs) {
    console.error("FloatingPromptInput: pmNodeAttrs is undefined");
    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;
  const handleClose = () => {
    modalService.closeModal(FLOATING_PROMPT_INPUT_MODAL_ID);
    queueMicrotask(() => {
      getPublicCommands().deleteBlock(nodeId);
    });
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_floating_container.FloatingContainer,
    {
      ...props,
      state: "overlay",
      editorContainer: tiptapEditor.options.element,
      onClickOutside: (e) => {
        const popoverContent = e.target?.closest?.(
          '[data-hook*="popover-content"]'
        );
        if (popoverContent) {
          return;
        }
        handleClose();
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      SelectedPromptInputArea,
      {
        placeholder: t("HtmlPlugin_AiWidget_Input_Placeholder_Text"),
        ref,
        zIndex: 1e3,
        maxLength: 1e4,
        forceMultiline: true,
        dataHook: import_data_hooks.PROMPT_INPUT_AREA,
        value: promptText,
        onChange: (text) => {
          setPromptText(text);
        },
        onClose: handleClose,
        attachments: pmNodeAttrs?.state?.prompt?.fileRefs ?? [],
        onSubmit: async () => {
          modalService.closeModal(FLOATING_PROMPT_INPUT_MODAL_ID);
          const currentRequestId = (0, import_wix_rich_content_common.uuid)();
          const stateBeforeLoading = { ...pmNodeAttrs };
          tiptapEditor.commands.closeHistory();
          patchPmNodeAttrs(
            {
              state: {
                status: "LOADING",
                requestId: currentRequestId,
                prompt: {
                  text: promptText,
                  fileRefs: pmNodeAttrs.state?.prompt?.fileRefs ?? [],
                  selectedWidgetTypeId: pmNodeAttrs?.state?.prompt?.selectedWidgetTypeId
                }
              }
            },
            { skipHistory: true }
          );
          const colorPalette = isAiWidget ? getColorPalette?.() : void 0;
          const widgetPos = (0, import_helpers.findNodeById)(tiptapEditor.view.state.tr, nodeId)?.[0]?.pos;
          const documentContext = isAiWidget && widgetPos !== void 0 ? tiptapEditor.state.doc.textBetween(0, widgetPos, "\n\n", "\n\n").trim() || void 0 : void 0;
          const response = await (0, import_do_prompt.doPrompt)({
            documentContext,
            prompt: promptText,
            files: pmNodeAttrs?.state?.prompt?.fileRefs?.filter((file) => file.status === "ok")?.map((file) => ({
              fileId: file.file.url,
              name: file.file.name
            })),
            document: getPublicCommands().getContent(),
            selection: getPublicCommands().getSelectionSlice() ?? [],
            makeRequest,
            widgetType: t(
              import_common.WIDGET_TYPE_OPTIONS.find(
                (option) => option.id === pmNodeAttrs?.state?.prompt?.selectedWidgetTypeId
              )?.label ?? ""
            ),
            outputMode: isAiWidget ? "WIDGET" : void 0,
            colorPalette
          });
          const tr = tiptapEditor.view.state.tr;
          const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId);
          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" }
              });
            }
            const nodePos = nodeWithPos?.[0] ?? {};
            if (nodePos?.pos) {
              queueMicrotask(() => {
                tiptapEditor.commands.setNodeSelection(nodePos.pos);
              });
            }
          }
          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
              }
            });
          }
        },
        minHeight: isAiWidget ? "36px" : "170px",
        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) ?? [],
                selectedWidgetTypeId: pmNodeAttrs?.state?.prompt?.selectedWidgetTypeId
              }
            }
          });
        },
        fileUploadFn: async () => {
          await handleFileUpload(nodeId);
        },
        actionBarComponent: isAiWidget ? void 0 : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
          import_widget_type_selector.WidgetTypeSelector,
          {
            options: import_common.WIDGET_TYPE_OPTIONS,
            selectedId: pmNodeAttrs?.state?.prompt?.selectedWidgetTypeId,
            onSelect: (typeId) => {
              patchPmNodeAttrs({
                state: {
                  status: "INITIAL",
                  prompt: {
                    selectedWidgetTypeId: typeId,
                    text: pmNodeAttrs?.state?.prompt?.text ?? "",
                    fileRefs: pmNodeAttrs?.state?.prompt?.fileRefs ?? []
                  }
                }
              });
            },
            onRemove: () => {
              patchPmNodeAttrs({
                state: {
                  status: "INITIAL",
                  prompt: {
                    selectedWidgetTypeId: void 0,
                    text: pmNodeAttrs?.state?.prompt?.text ?? "",
                    fileRefs: pmNodeAttrs?.state?.prompt?.fileRefs ?? []
                  }
                }
              });
            }
          }
        )),
        presetBarComponent: isAiWidget ? /* @__PURE__ */ import_react.default.createElement(
          import_preset_bar.PresetList,
          {
            presets: PRESETS_WIDGETS_CREATE,
            onPresetSelect: (preset) => {
              if (pmNodeAttrs.state?.status === "LOADING") {
                return;
              }
              setPromptText(preset.prompt ?? "");
            }
          }
        ) : void 0
      }
    )
  );
};
const PRESETS_WIDGETS_CREATE = [
  {
    id: "recipe",
    label: "Recipe",
    prompt: "Write a detailed recipe for chocolate chip cookies including ingredients, step-by-step instructions, and baking tips.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.FoodInStockSmall, null)
  },
  {
    id: "writer-profile",
    label: "Writer profile",
    prompt: "Create a comprehensive writer profile page with biography, notable works, social links, and contact information.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.UserNameSmall, null)
  },
  {
    id: "table",
    label: "Table",
    prompt: "Create a well-formatted data table with headers, sample rows, and clear organization.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.DataCollectionSmall, null)
  },
  {
    id: "charts-graphs",
    label: "Charts / Graphs",
    prompt: "Create an interactive chart or graph with sample data, labels, and a legend.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.LineChartSmall, null)
  },
  {
    id: "interactive-map",
    label: "Interactive map",
    prompt: "Create an interactive map with markers, zoom functionality, and location information.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.MapSmall, null)
  },
  {
    id: "3d-visualization",
    label: "3D visualization",
    prompt: "Create an engaging 3D visualization with interactive controls and realistic rendering.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.LayersSmall, null)
  },
  {
    id: "countdown",
    label: "Countdown",
    prompt: "Create a countdown timer with customizable date/time, animated display, and completion message.",
    icon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.TimerSmall, null)
  }
];
//# sourceMappingURL=floating-prompt-input.js.map
