"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 insert_modal_exports = {};
__export(insert_modal_exports, {
  InsertModal: () => InsertModal
});
module.exports = __toCommonJS(insert_modal_exports);
var import_design_system = require("@wix/design-system");
var import_lodash = __toESM(require("lodash"));
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_bi_context_provider = require("./../../_shared/bi-context-provider/bi-context-provider.js");
var import_uncreachable = require("./../../_shared/uncreachable.js");
var import_wix_rich_content_common = require("./../../wix-rich-content-common/index.js");
var import_utils = require("./../utils.js");
var import_ui_components = require("./../../ui-components/index.js");
var import_constants = require("../constants.js");
var import_data_hooks = require("../data-hooks.js");
var import_fetch_vertical_embed_data = require("../services/fetch-vertical-embed-data.js");
var import_items_list = require("../toolbar/items-list.js");
var import_types = require("../types.js");
const InsertModal = ({ componentData, nodeId, modalId }) => {
  const { t, isMobile } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const { getPublicCommands } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  const modalService = (0, import_react.useContext)(import_ricos_context.ModalServiceContext) || {};
  const pluginsEvents = (0, import_react.useContext)(import_ricos_context.PluginsEventsContext);
  const { fetchVerticalEmbedItems } = (0, import_fetch_vertical_embed_data.useVerticalEmbedRequestService)();
  const logBi = (0, import_bi_context_provider.useBiNext)({ modalId, pluginId: "verticalEmbed", nodeId });
  const containerEl = (0, import_ui_components.usePanelContainerElement)();
  const contentType = import_constants.contentTypeMap[componentData.type];
  const [state, setState] = (0, import_react.useState)({
    status: "LOADING",
    searchText: "",
    requestId: (0, import_wix_rich_content_common.uuid)()
  });
  (0, import_react.useEffect)(() => {
    fetchEmbedItems("");
  }, []);
  const fetchEmbedItems = import_lodash.default.debounce((inputString = "") => {
    const requestId = (0, import_wix_rich_content_common.uuid)();
    setState(() => ({
      status: "LOADING",
      searchText: inputString,
      requestId
    }));
    (async () => {
      try {
        const verticalApiType = (0, import_utils.getLowerCaseAppEmbedType)(componentData.type);
        const items = (0, import_utils.isTypeAppEmbed)(componentData.type) ? await fetchVerticalEmbedItems(verticalApiType, inputString) : [];
        setState((prev) => {
          if (prev.status === "LOADING" && prev.requestId !== requestId) {
            return prev;
          }
          return {
            status: "READY",
            items: items ?? [],
            selectedItem: void 0,
            searchText: inputString,
            showSelectionError: false
          };
        });
      } catch (e) {
        console.error("Failed to load products", e);
        setState((prev) => {
          if (prev.status === "LOADING" && prev.requestId !== requestId) {
            return prev;
          }
          return {
            status: "READY",
            items: [],
            selectedItem: void 0,
            searchText: inputString,
            showSelectionError: false
          };
        });
      }
    })();
  }, 300);
  const closeModal = () => modalService.closeModal(modalId);
  const onSave = () => {
    pluginsEvents.publishPluginPopoverClick?.({
      pluginId: import_types.VERTICAL_EMBED_TYPE,
      buttonName: import_wix_rich_content_common.MEDIA_POPOVERS_BUTTONS_NAMES_BI.embed
    });
    if (state.status !== "READY" || !state.selectedItem) {
      setState((prev) => ({ ...prev, showSelectionError: true }));
      return;
    }
    const embedData = (0, import_utils.toAppEmbedData)(state.selectedItem, componentData, t);
    insertEmbedNode(embedData);
    closeModal();
  };
  const insertEmbedNode = (verticalEmbed) => {
    const publicCommands = getPublicCommands();
    setTimeout(
      () => nodeId ? publicCommands?.setBlock(nodeId, import_types.VERTICAL_EMBED_TYPE, {
        ...verticalEmbed,
        error: false,
        loading: false
      }) : publicCommands?.insertBlockWithBlankLines(import_types.VERTICAL_EMBED_TYPE, verticalEmbed),
      50
    );
    closeModal();
  };
  if (!componentData) {
    return null;
  }
  return /* @__PURE__ */ import_react.default.createElement(
    import_ui_components.Panel,
    {
      height: isMobile ? "100%" : "540px",
      closeButtonProps: { onClick: closeModal },
      dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_MODAL
    },
    /* @__PURE__ */ import_react.default.createElement(import_ui_components.PanelHeader, { title: t(`Embed_Vertical_${contentType}_Title`) }),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { padding: "SP3" }, /* @__PURE__ */ import_react.default.createElement(
      import_design_system.Search,
      {
        size: "small",
        value: state.searchText,
        onChange: (e) => {
          fetchEmbedItems(e.target.value);
          logBi({
            dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_SEARCH_INPUT,
            value: e.target.value
          });
        },
        onClear: () => fetchEmbedItems(""),
        placeholder: t(`Embed_Vertical_${contentType}_Search_Placeholder`),
        dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_SEARCH_INPUT
      }
    )),
    (() => {
      switch (state.status) {
        case "LOADING":
          return /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { align: "center", verticalAlign: "middle", height: "252px" }, /* @__PURE__ */ import_react.default.createElement(import_design_system.Loader, null));
        case "READY":
          return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", paddingBottom: "SP3", overflow: "auto" }, /* @__PURE__ */ import_react.default.createElement(
            import_items_list.ItemsList,
            {
              selectedItem: state.selectedItem,
              items: state.items,
              hasActiveSearch: state.searchText.length > 0,
              onClick: (item) => {
                logBi({
                  dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_ITEMS_LIST,
                  value: contentType
                });
                setState((prev) => {
                  if (prev.status === "READY") {
                    return {
                      ...prev,
                      showSelectionError: false,
                      selectedItem: item.id === prev.selectedItem?.id ? void 0 : item
                    };
                  }
                  return prev;
                });
              },
              contentType,
              modalRef: containerEl
            }
          )), state.showSelectionError && /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { padding: "SP3", position: "absolute", bottom: "40px" }, /* @__PURE__ */ import_react.default.createElement(
            import_design_system.SectionHelper,
            {
              appearance: "danger",
              title: t("Embed_Vertical_Nothing_Selected_Error_Title"),
              showCloseButton: true,
              onClose: () => setState((prev) => ({ ...prev, showSelectionError: false }))
            },
            t("Embed_Vertical_Nothing_Selected_Error_Description")
          )));
        default:
          (0, import_uncreachable.unreachable)(state);
          return null;
      }
    })(),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.SidePanel.Footer, { showDivider: true }, state.status === "READY" && state.items.length === 0 && state.searchText.length === 0 ? /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { align: "right", gap: "SP2" }, /* @__PURE__ */ import_react.default.createElement(
      import_design_system.Button,
      {
        onClick: () => {
          logBi({
            dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_CANCEL_BUTTON
          });
          closeModal();
        },
        priority: "primary",
        dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_CANCEL_BUTTON,
        size: "small"
      },
      t("Embed_Vertical_Close_Button")
    )) : /* @__PURE__ */ import_react.default.createElement(
      import_ui_components.FooterActions,
      {
        dataHook: import_data_hooks.INSERT_VERTICAL_EMBED_FOOTER_ACTIONS,
        onCancel: closeModal,
        logBi,
        onSave,
        saveButtonLabel: t("Embed_Vertical_Add_Button")
      }
    ))
  );
};
//# sourceMappingURL=insert-modal.js.map
