"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 ricos_assistant_widget_exports = {};
__export(ricos_assistant_widget_exports, {
  RicosWidget: () => RicosWidget
});
module.exports = __toCommonJS(ricos_assistant_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_assistant_error_descriptor = require("./assistant-error-descriptor.js");
var import_assistant_timeline = require("./assistant-timeline.js");
var import_runtime_store = require("./runtime-store.js");
const logError = (message, error, details) => {
  console.error("[ricos-assistant-widget]", message, {
    ...details,
    error
  });
};
const StopButton = ({ onCancel, t }) => {
  return /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Button,
    {
      size: "small",
      priority: "secondary",
      skin: "standard",
      prefixIcon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.StopFilledSmall, null),
      onClick: onCancel
    },
    t("Widget_Button_Stop")
  );
};
const useInvocationState = (invocationId) => {
  const [state, setState] = import_react.default.useState(
    () => (0, import_runtime_store.getInvocation)(invocationId)
  );
  import_react.default.useEffect(() => {
    setState((0, import_runtime_store.getInvocation)(invocationId));
    return (0, import_runtime_store.subscribeToInvocation)(invocationId, setState);
  }, [invocationId]);
  return state;
};
const getStartupTasks = (invocationState, t) => {
  if (invocationState?.assetMode !== "create") {
    return [];
  }
  const status = invocationState.phase === "creatingAsset" ? "inProgress" : invocationState.phase === "startupFailed" && !("assetId" in invocationState) ? "error" : "success";
  return [
    {
      message: t("Widget_Message_CreatingAsset"),
      status
    }
  ];
};
const useRuntimeEffects = (aiState, assetId, generationId, invocationId, isLastMessage, isRetry, hasContentStarted, platform, config, context) => {
  const currentState = aiState?.state;
  const runtimeStateType = currentState?.type;
  const endGenerationIfNeeded = import_react.default.useCallback(() => {
    if (!generationId || (0, import_runtime_store.hasInvocationEffect)(invocationId, "generationEnded")) {
      return;
    }
    (0, import_runtime_store.setInvocationEffect)(invocationId, "generationEnded");
    platform.endAiGeneration({ generationId, assetId });
  }, [assetId, generationId, invocationId, platform]);
  const releaseLoader = import_react.default.useCallback(() => {
    if (!(0, import_runtime_store.hasInvocationEffect)(invocationId, "loaderReleased")) {
      (0, import_runtime_store.setInvocationEffect)(invocationId, "loaderReleased");
      (0, import_runtime_store.clearAssetWaitingState)(assetId);
    }
    endGenerationIfNeeded();
  }, [assetId, endGenerationIfNeeded, invocationId]);
  import_react.default.useEffect(() => {
    if (!(isLastMessage || isRetry)) {
      return;
    }
    if (currentState?.type && currentState.type !== "typing") {
      (0, import_runtime_store.setAssetWidgetStatus)(assetId, currentState.type);
    }
    switch (currentState?.type) {
      case "pending":
        config.setCanSend?.(false);
        break;
      case "streaming":
        if (hasContentStarted) {
          releaseLoader();
        } else {
          endGenerationIfNeeded();
        }
        break;
      case "closed": {
        config.setCanSend?.(true);
        if ((0, import_runtime_store.hasInvocationEffect)(invocationId, "terminalMessageSent")) {
          break;
        }
        (0, import_runtime_store.setInvocationEffect)(invocationId, "terminalMessageSent");
        releaseLoader();
        const summary = currentState.messages.find(
          (message) => message.type === "text" && message.subtype === "summary"
        );
        const explanation = currentState.messages.find(
          (message) => message.type === "text" && message.subtype === "explain"
        );
        if (summary) {
          context.send?.(`<HIDDEN>Summary of performed changes: ${summary.text}</HIDDEN>`);
        } else if (explanation) {
          context.send?.(`<HIDDEN>No changes performed. Explanation: ${explanation.text}</HIDDEN>`);
        } else {
          context.send?.("<HIDDEN>Request completed</HIDDEN>");
        }
        break;
      }
      case "error": {
        config.setCanSend?.(true);
        if ((0, import_runtime_store.hasInvocationEffect)(invocationId, "terminalMessageSent")) {
          break;
        }
        (0, import_runtime_store.setInvocationEffect)(invocationId, "terminalMessageSent");
        releaseLoader();
        const errorDescriptor = (0, import_assistant_error_descriptor.getAssistantErrorDescriptor)({
          applicationErrorCode: currentState.error.applicationErrorCode,
          message: currentState.error.message,
          t: platform.t
        });
        if (errorDescriptor.shouldOpenPaywall) {
          platform.openPaywallModal();
        }
        context.send?.(errorDescriptor.hiddenMessage);
        break;
      }
      default:
        break;
    }
  }, [
    assetId,
    config,
    context,
    endGenerationIfNeeded,
    hasContentStarted,
    invocationId,
    isLastMessage,
    isRetry,
    platform,
    releaseLoader,
    runtimeStateType
  ]);
};
const RicosWidget = ({ platform, ...props }) => {
  const [currentInvocationId, setCurrentInvocationId] = import_react.default.useState(props.data.messageId);
  const invocationState = useInvocationState(currentInvocationId);
  const { t } = platform;
  const initialTasks = getStartupTasks(invocationState, t);
  const assetId = (invocationState && "assetId" in invocationState ? invocationState.assetId : void 0) ?? props.data.assetId;
  const editorRef = assetId ? (0, import_runtime_store.getAssetEditorRef)(assetId) : void 0;
  const hideWidget = !invocationState;
  const isStartupFailed = invocationState?.phase === "startupFailed";
  const isPending = !hideWidget && !isStartupFailed && (!invocationState || invocationState.phase === "initializing" || invocationState.phase === "waitingForEditor" || !editorRef || !assetId);
  import_react.default.useEffect(() => {
    setCurrentInvocationId(props.data.messageId);
  }, [props.data.messageId]);
  const handleRetry = import_react.default.useCallback(() => {
    void platform.retryInvocation(currentInvocationId).then((newInvocationId) => {
      setCurrentInvocationId(newInvocationId);
    }).catch((error) => {
      logError("retry failed", error, {
        currentInvocationId,
        assetId
      });
    });
  }, [assetId, currentInvocationId, platform]);
  if (hideWidget) {
    return null;
  }
  if (isStartupFailed) {
    const errorMessage = invocationState?.error?.message;
    return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": "error" }, /* @__PURE__ */ import_react.default.createElement(
      import_assistant_timeline.MessageTimeline,
      {
        title: t("Widget_Title_Error"),
        subtitle: t("Widget_Subtitle_Error"),
        tasks: [
          ...initialTasks,
          {
            message: errorMessage ?? t("Widget_Subtitle_Error"),
            status: "error",
            description: errorMessage ? [errorMessage] : void 0
          }
        ],
        onRetry: handleRetry,
        t
      }
    ));
  }
  if (isPending || !assetId || !editorRef) {
    return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": "pending" }, /* @__PURE__ */ import_react.default.createElement(
      import_assistant_timeline.MessageTimeline,
      {
        title: t("Widget_Title_Pending"),
        subtitle: t("Widget_Subtitle_Pending"),
        tasks: initialTasks,
        isLoading: initialTasks.length === 0,
        t
      }
    ));
  }
  return /* @__PURE__ */ import_react.default.createElement(
    RicosWidgetSession,
    {
      ...props,
      platform,
      data: { ...props.data, assetId },
      generationId: invocationState && "generationId" in invocationState ? invocationState.generationId : void 0,
      initialTasks,
      invocationId: currentInvocationId,
      isRetry: currentInvocationId !== props.data.messageId,
      onRetry: handleRetry,
      editorRef
    }
  );
};
const TOOL_LABELS = {
  web_search: "Researching",
  web_scrape: "Reading web page",
  image_search: "Looking for images",
  image_generation: "Generating image",
  analyze_resource: "Analyzing",
  read_wix_blog_post: "Reading blog post",
  read_wix_event: "Reading event",
  read_wix_stores_product: "Reading product",
  read_wix_booking_service: "Reading booking service",
  generate_theme: "Generating theme"
};
const isRecord = (value) => {
  return typeof value === "object" && value !== null;
};
const getToolDescription = (m) => {
  const toolName = m.text.toLowerCase();
  const label = TOOL_LABELS[toolName] || m.text;
  const params = isRecord(m.toolParameters) ? m.toolParameters : void 0;
  if (!params) {
    return label;
  }
  const getRequestValues = (key) => Array.isArray(params.requests) ? params.requests.reduce((values, request) => {
    if (isRecord(request) && typeof request[key] === "string") {
      values.push(request[key]);
    }
    return values;
  }, []) : [];
  let summary;
  switch (toolName) {
    case "web_search":
      summary = getRequestValues("query").join(", ") || void 0;
      break;
    case "image_search":
      summary = typeof params.searchTerm === "string" ? params.searchTerm : void 0;
      break;
    case "image_generation":
      summary = typeof params.prompt === "string" ? params.prompt : void 0;
      break;
    case "web_scrape":
      summary = typeof params.url === "string" ? params.url : void 0;
      break;
    case "analyze_resource":
      summary = getRequestValues("prompt").join(", ") || void 0;
      break;
  }
  return summary ? `${label}: ${summary}` : label;
};
const buildResearchingTask = (textMessages, status, t) => {
  const descriptions = textMessages.filter((m) => m.subtype === "tool").map(getToolDescription);
  if (descriptions.length === 0) {
    return null;
  }
  return {
    id: "researching",
    message: t("Widget_Timeline_Step_GatheringInformation"),
    description: descriptions,
    isToolDescription: status === "inProgress",
    status
  };
};
const RicosWidgetSession = ({
  platform,
  initialTasks = [],
  generationId,
  invocationId,
  isRetry,
  editorRef,
  ...props
}) => {
  const { t } = platform;
  const assetId = props.data.assetId;
  const isLastMessage = props.config.messageIndex === (props.config.messages?.length ?? 0) - 1;
  const aiState = editorRef.useInlineAiState(invocationId);
  const runtimeMessages = aiState?.state && "messages" in aiState.state ? aiState.state.messages : [];
  const hasContentStarted = aiState?.state?.type === "streaming" && runtimeMessages.some((m) => m.type === "insert" || m.type === "replace");
  useRuntimeEffects(
    aiState,
    assetId,
    generationId,
    invocationId,
    isLastMessage,
    isRetry,
    hasContentStarted,
    platform,
    props.config,
    props.context
  );
  if (!aiState?.state) {
    return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": "pending" }, /* @__PURE__ */ import_react.default.createElement(
      import_assistant_timeline.MessageTimeline,
      {
        title: t("Widget_Title_Pending"),
        subtitle: t("Widget_Subtitle_Pending"),
        tasks: initialTasks,
        isLoading: initialTasks.length === 0,
        t
      }
    ));
  }
  const textMessages = "messages" in aiState.state ? aiState.state.messages.filter((m) => m.type === "text") : [];
  const summaryMessage = textMessages.find((m) => m.subtype === "summary") ?? textMessages.find((m) => m.subtype === "explain") ?? textMessages.find((m) => m.subtype === "error");
  const baseTasks = [
    {
      message: t("Widget_Timeline_Step_Executing"),
      description: [props.data.prompt],
      status: "pending"
    },
    {
      message: t("Widget_Timeline_Step_GeneratingResponse"),
      status: "pending"
    },
    {
      message: t("Widget_Timeline_Step_Summary"),
      status: "pending"
    }
  ];
  const onCancel = () => aiState.stop({ headless: true });
  switch (aiState.state.type) {
    case "pending": {
      const tasksWithStatus = [{ ...baseTasks[0], status: "inProgress" }];
      return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": "pending" }, /* @__PURE__ */ import_react.default.createElement(
        import_assistant_timeline.MessageTimeline,
        {
          title: t("Widget_Title_Editing"),
          subtitle: t("Widget_Subtitle_ExecutingPrompt"),
          tasks: [...initialTasks, ...tasksWithStatus],
          footer: /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget-stop-button" }, /* @__PURE__ */ import_react.default.createElement(StopButton, { onCancel, t })),
          t
        }
      ));
    }
    case "streaming": {
      const researchingTask = hasContentStarted ? buildResearchingTask(textMessages, "success", t) : buildResearchingTask(textMessages, "inProgress", t);
      const tasksWithStatus = hasContentStarted ? [
        {
          ...baseTasks[0],
          status: "success"
        },
        ...researchingTask ? [researchingTask] : [],
        {
          ...baseTasks[1],
          status: !summaryMessage ? "inProgress" : summaryMessage.subtype === "error" ? "error" : "success",
          applicationErrorCode: summaryMessage?.subtype === "error" ? "AI_GENERATED_ERROR" : void 0,
          description: summaryMessage?.subtype === "error" ? [summaryMessage.text] : void 0
        },
        ...summaryMessage ? [
          {
            ...baseTasks[2],
            status: "inProgress",
            description: summaryMessage.text ? [summaryMessage.text] : void 0
          }
        ] : []
      ] : [
        {
          ...baseTasks[0],
          status: researchingTask ? "success" : "inProgress"
        },
        ...researchingTask ? [researchingTask] : []
      ];
      return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": "streaming" }, /* @__PURE__ */ import_react.default.createElement(
        import_assistant_timeline.MessageTimeline,
        {
          title: t("Widget_Title_Editing"),
          subtitle: hasContentStarted ? t("Widget_Subtitle_ImplementingChanges") : t("Widget_Subtitle_ExecutingPrompt"),
          tasks: [...initialTasks, ...tasksWithStatus],
          footer: /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget-stop-button" }, /* @__PURE__ */ import_react.default.createElement(StopButton, { onCancel, t })),
          t
        }
      ));
    }
    case "preview":
    case "closed": {
      const researchingTask = buildResearchingTask(textMessages, "success", t);
      const tasksWithStatus = [
        {
          ...baseTasks[0],
          status: "success"
        },
        ...researchingTask ? [researchingTask] : [],
        {
          ...baseTasks[1],
          status: "success"
        },
        {
          ...baseTasks[2],
          status: "success",
          description: summaryMessage?.text ? [summaryMessage.text] : void 0
        }
      ];
      return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": aiState.state.type }, /* @__PURE__ */ import_react.default.createElement(
        import_assistant_timeline.MessageTimeline,
        {
          title: t("Widget_Title_Editing"),
          subtitle: t("Widget_Subtitle_Completed"),
          tasks: [...initialTasks, ...tasksWithStatus],
          t
        }
      ));
    }
    case "error":
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          "data-hook": "ricos-widget",
          "data-state": "error",
          "data-error-code": aiState.state.error.applicationErrorCode
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_assistant_timeline.MessageTimeline,
          {
            title: t("Widget_Title_Editing"),
            subtitle: t("Widget_Subtitle_Error"),
            tasks: [
              ...initialTasks,
              {
                message: aiState.state.error.message,
                status: "error",
                applicationErrorCode: aiState.state.error.applicationErrorCode,
                description: [aiState.state.error.message]
              }
            ],
            onRetry: props.onRetry,
            t
          }
        )
      );
    default:
      return /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": "ricos-widget", "data-state": "unknown" }, t("Widget_Message_UnknownState"));
  }
};
//# sourceMappingURL=ricos-assistant-widget.js.map
