"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 shape_select_modal_content_exports = {};
__export(shape_select_modal_content_exports, {
  ShapeSelectModalContent: () => ShapeSelectModalContent
});
module.exports = __toCommonJS(shape_select_modal_content_exports);
var import_design_system = require("@wix/design-system");
var import_classnames = __toESM(require("classnames"));
var import_react = __toESM(require("react"));
var import_react_infinite_scroller = __toESM(require("react-infinite-scroller"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_bi_context_provider = require("./../bi-context-provider/bi-context-provider.js");
var import_request_service_provider = require("./../request-service-provider/request-service-provider.js");
var import_wix_rich_content_common = require("./../../wix-rich-content-common/index.js");
var import_ui_components = require("./../../ui-components/index.js");
var import_consts = require("./consts.js");
var import_data_hooks = require("./data-hooks.js");
var import_shape_select_empty = require("./shape-select-empty.js");
var import_shape_select_modal_content_scss = __toESM(require("./shape-select-modal-content-scss.js"));
var import_shape_service = require("./shape-service.js");
const ShapeSelectModalContent = ({ onShapeSelect, selectedCategoryId }) => {
  const { makeRequest } = (0, import_request_service_provider.useRequestService)();
  const { t, isMobile } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const devShapeService = (0, import_ricos_context.useDevShapeService)();
  const logBi = (0, import_bi_context_provider.useBiNext)({ modalId: import_data_hooks.SHAPE_SELECT_MODAL, pluginId: "shape" });
  const requestIdRef = (0, import_react.useRef)("");
  const isDevEnv = !!devShapeService?.fetchShapes;
  const [state, setState] = (0, import_react.useState)({
    type: "LOADING",
    searchString: ""
  });
  const [loadedImages, setLoadedImages] = (0, import_react.useState)(/* @__PURE__ */ new Set());
  (0, import_react.useEffect)(() => {
    requestIdRef.current = (0, import_wix_rich_content_common.uuid)();
    setState({
      type: "LOADING",
      searchString: ""
    });
    setLoadedImages(/* @__PURE__ */ new Set());
    loadShapesData({ page: 1, searchString: "", requestId: requestIdRef.current });
  }, [selectedCategoryId]);
  const loadShapesData = async ({
    page,
    searchString: searchString2,
    requestId
  }) => {
    try {
      const fetchShapesFn = devShapeService?.fetchShapes ?? import_shape_service.fetchShapes;
      const response = await fetchShapesFn(
        {
          cursor: {
            limit: 50,
            cursor: String(page)
          },
          searchString: searchString2,
          searchCategories: [
            {
              categoryId: selectedCategoryId
            }
          ]
        },
        makeRequest
      );
      const shapeItems = response.categoryResults?.[0]?.items || [];
      if (!requestIdRef.current || requestIdRef.current === requestId) {
        setState((prev) => {
          const prevItems = prev.type === "LOADING" || prev.type === "ERROR" ? [] : prev.items;
          return {
            type: "LOADED",
            items: page === 1 ? shapeItems : [...prevItems, ...shapeItems],
            hasMore: !isDevEnv ? !!shapeItems.length : false,
            page,
            searchString: searchString2
          };
        });
      }
    } catch {
      setState({
        type: "ERROR"
      });
    }
  };
  const onShapeKeyDown = (e, shape) => {
    if (["Enter", " "].includes(e.key)) {
      onShapeSelect(shape);
    }
  };
  const onImageLoad = (imageId) => {
    setLoadedImages((prev) => new Set(prev).add(imageId));
  };
  const onSearchChange = (e) => {
    logBi({
      dataHook: import_data_hooks.SHAPE_SELECT_MODAL_SEARCH_INPUT,
      value: e.target.value
    });
    requestIdRef.current = (0, import_wix_rich_content_common.uuid)();
    loadShapesData({ page: 1, searchString: e.target.value, requestId: requestIdRef.current });
    setState({
      type: "LOADING",
      searchString: e.target.value
    });
    setLoadedImages(/* @__PURE__ */ new Set());
  };
  const onSearchClear = () => {
    requestIdRef.current = (0, import_wix_rich_content_common.uuid)();
    setState({
      type: "LOADING",
      searchString: ""
    });
    loadShapesData({ page: 1, searchString: "", requestId: requestIdRef.current });
  };
  const onInfiniteScrollLoadMore = async () => {
    if (state.type !== "LOADED") {
      return;
    }
    const nextPage = state.page + 1;
    requestIdRef.current = (0, import_wix_rich_content_common.uuid)();
    setState({
      type: "LOADING_MORE",
      items: state.items,
      page: nextPage,
      searchString: state.searchString
    });
    await loadShapesData({
      page: nextPage,
      searchString: state.searchString,
      requestId: requestIdRef.current
    });
  };
  const searchString = state.type === "ERROR" ? "" : state.searchString;
  const items = state.type === "LOADED" || state.type === "LOADING_MORE" ? state.items : [];
  const hasMore = state.type === "LOADED" ? state.hasMore : false;
  return /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical" }, /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { padding: "SP3" }, /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Search,
    {
      className: import_shape_select_modal_content_scss.default.searchInput,
      dataHook: import_data_hooks.SHAPE_SELECT_MODAL_SEARCH_INPUT,
      placeholder: selectedCategoryId === import_consts.SHAPES_CATEGORY_ID ? t("ShapeSelectModalContent_Search_Placeholder") : t("ShapeSelectModalContent_Search_Placeholder_VectorArt"),
      onChange: onSearchChange,
      onClear: onSearchClear,
      debounceMs: import_consts.SEARCH_DEBOUNCE_MS,
      value: searchString
    }
  )), /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      "data-hook": import_data_hooks.SHAPE_SELECT_MODAL_CONTENT,
      className: (0, import_classnames.default)(import_shape_select_modal_content_scss.default.shape_select_modal_content_infinite_scroll_container, {
        [import_shape_select_modal_content_scss.default.mobile]: isMobile
      })
    },
    state.type === "LOADING" && /* @__PURE__ */ import_react.default.createElement("div", { className: import_shape_select_modal_content_scss.default.shape_select_modal_content_spinner_search }, /* @__PURE__ */ import_react.default.createElement(import_design_system.Loader, { size: "small" })),
    state.type === "ERROR" && /* @__PURE__ */ import_react.default.createElement(import_shape_select_empty.ShapeSelectEmpty, { isError: true, selectedCategoryId }),
    state.type === "LOADED" && !state.items.length && state.searchString && /* @__PURE__ */ import_react.default.createElement(import_shape_select_empty.ShapeSelectEmpty, { selectedCategoryId }),
    /* @__PURE__ */ import_react.default.createElement(
      import_react_infinite_scroller.default,
      {
        className: import_shape_select_modal_content_scss.default.shape_select_modal_content_infinite_scroll,
        initialLoad: false,
        loadMore: onInfiniteScrollLoadMore,
        hasMore,
        useWindow: false,
        loader: state.type === "LOADING_MORE" && /* @__PURE__ */ import_react.default.createElement("div", { className: import_shape_select_modal_content_scss.default.shape_select_modal_content_spinner_load_more }, /* @__PURE__ */ import_react.default.createElement(import_design_system.Loader, { size: "small" }))
      },
      items.map(
        ({ item }) => item && item.id && /* @__PURE__ */ import_react.default.createElement("div", { key: item.id, className: import_shape_select_modal_content_scss.default.shape_select_modal_content_item_wrapper }, !loadedImages.has(item.id) && /* @__PURE__ */ import_react.default.createElement("div", { className: import_shape_select_modal_content_scss.default.shape_select_modal_content_image_loader }, /* @__PURE__ */ import_react.default.createElement(import_ui_components.DoubleLoader, null)), /* @__PURE__ */ import_react.default.createElement(
          import_design_system.Image,
          {
            "data-id": item.id,
            tabIndex: 0,
            transparent: true,
            onKeyDown: (e) => onShapeKeyDown(e, item),
            onClick: () => onShapeSelect(item),
            onLoad: () => onImageLoad(item.id),
            dataHook: import_data_hooks.SHAPE_SELECT_MODAL_CONTENT_ITEM,
            id: item.id,
            role: "img",
            "aria-label": "Shape",
            fit: "contain",
            height: 182,
            src: item.assets?.vector?.image?.url || "",
            className: (0, import_classnames.default)(import_shape_select_modal_content_scss.default.shape_select_modal_content_shape_img_container, {
              [import_shape_select_modal_content_scss.default.shape_select_modal_content_shape_img_loading]: !loadedImages.has(
                item.id
              )
            }),
            showBorder: true,
            borderRadius: "8px",
            alt: item.title || ""
          }
        ))
      )
    )
  ));
};
//# sourceMappingURL=shape-select-modal-content.js.map
