"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 file_viewer_exports = {};
__export(file_viewer_exports, {
  FileViewer: () => FileViewer
});
module.exports = __toCommonJS(file_viewer_exports);
var import_classnames = __toESM(require("classnames"));
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_v1 = require("./../../ricos-schema/legacy/wix/rich_content/v1/index.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_data_hooks = require("../data-hooks.js");
var import_download_icon = require("../icons/download-icon.js");
var import_error_icon = require("../icons/error-icon.js");
var import_get_icon = require("../icons/get-icon.js");
var import_file_upload_viewer_scss = __toESM(require("../statics/styles/file-upload-viewer-scss.js"));
var import_types = require("../types.js");
const KB = 1e3;
const MB = KB * 1e3;
const getNameWithoutType = (fileName) => {
  if (!fileName) {
    return fileName;
  }
  const lastDotIndex = fileName.lastIndexOf(".");
  return lastDotIndex !== -1 ? fileName.substring(0, lastDotIndex) : fileName;
};
const getFormattedFileSize = (componentData, tempDataPlaceHolder) => {
  const sizeInKb = componentData.sizeInKb ?? tempDataPlaceHolder?.sizeInKb;
  const size = componentData.size ?? tempDataPlaceHolder?.size;
  if (sizeInKb && !isNaN(parseFloat(sizeInKb))) {
    return formatFileSize(parseFloat(sizeInKb) * KB);
  }
  if (size) {
    return formatFileSize(size);
  }
  return void 0;
};
const formatFileSize = (sizeInBytes) => {
  if (sizeInBytes < KB) {
    return `${Math.round(sizeInBytes)}B`;
  }
  if (sizeInBytes < MB) {
    return `${Math.round(sizeInBytes / KB)}KB`;
  }
  return `${(sizeInBytes / MB).toFixed(2)}MB`;
};
const FileViewerContent = ({ state, fileData }) => {
  const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const { name, type } = fileData;
  if (!(0, import_wix_rich_content_common.isDefined)(name) || !(0, import_wix_rich_content_common.isDefined)(type)) {
    return null;
  }
  const TypeIcon = (0, import_get_icon.getIcon)(type);
  const fileBasename = getNameWithoutType(name);
  const fileExtension = type ? `.${type}` : void 0;
  let infoString;
  if (state === "error") {
    infoString = t("UploadFile_Error_Generic_Item");
  } else {
    const translationKey = state === "loading" ? "UploadFile_Viewer_Loader" : "UploadFile_Viewer_Download";
    const fileType = type?.toUpperCase() ?? "";
    const formattedFileSize = getFormattedFileSize(fileData);
    const fileSizeSuffix = formattedFileSize ? ` • ${formattedFileSize}` : "";
    infoString = `${t(translationKey, { fileType })}${fileSizeSuffix}`;
  }
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(TypeIcon, { className: import_file_upload_viewer_scss.default.file_upload_type_icon }), /* @__PURE__ */ import_react.default.createElement("div", { className: import_file_upload_viewer_scss.default.file_upload_description }, /* @__PURE__ */ import_react.default.createElement("div", { className: import_file_upload_viewer_scss.default.file_upload_name_container, "data-hook": import_data_hooks.FILE_UPLOAD_NAME_CONTAINER }, /* @__PURE__ */ import_react.default.createElement("span", { className: import_file_upload_viewer_scss.default.file_upload_name, "data-hook": import_data_hooks.FILE_UPLOAD_NAME }, fileBasename), fileExtension && /* @__PURE__ */ import_react.default.createElement("span", { className: import_file_upload_viewer_scss.default.file_upload_extension, "data-hook": import_data_hooks.FILE_UPLOAD_EXTENSION }, fileExtension)), /* @__PURE__ */ import_react.default.createElement("div", { className: import_file_upload_viewer_scss.default.file_upload_file_info }, infoString)), /* @__PURE__ */ import_react.default.createElement("div", { className: import_file_upload_viewer_scss.default.file_upload_status_icon_container }, state === "loading" && /* @__PURE__ */ import_react.default.createElement(import_ui_components.DoubleLoader, { className: import_file_upload_viewer_scss.default.file_loader_icon }), state === "error" && /* @__PURE__ */ import_react.default.createElement(import_error_icon.ErrorIcon, { className: import_file_upload_viewer_scss.default.file_upload_status_icon }), state === "ready" && /* @__PURE__ */ import_react.default.createElement(import_download_icon.DownloadIcon, { className: import_file_upload_viewer_scss.default.file_upload_status_icon })));
};
const FileViewer = ({ settings, componentData, isLoading = false, tempDataPlaceHolder, helpers, nodeId }) => {
  const { tabIndex } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const linkRef = import_react.default.useRef(null);
  const [shouldDownloadOnRender, setShouldDownloadOnRender] = import_react.default.useState(false);
  const [resolvedFileUrl, setResolvedFileUrl] = import_react.default.useState(void 0);
  const [isResolvingUrl, setResolvingUrl] = import_react.default.useState(false);
  const state = isLoading || isResolvingUrl ? "loading" : componentData.error ? "error" : "ready";
  (0, import_react.useEffect)(() => {
    if (!shouldDownloadOnRender) {
      return;
    }
    linkRef.current?.click();
    setShouldDownloadOnRender(false);
  }, [shouldDownloadOnRender]);
  const onFileClick = () => {
    if (componentData.name) {
      helpers?.onViewerAction?.(import_types.FILE_UPLOAD_TYPE, "Click", componentData.name, nodeId, {
        type: import_v1.Node_Type.FILE,
        fileData: componentData
      });
    }
  };
  const renderContainerWithoutLink = () => {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: import_file_upload_viewer_scss.default.file_upload_link }, /* @__PURE__ */ import_react.default.createElement(FileViewerContent, { state, fileData: tempDataPlaceHolder || componentData }));
  };
  const renderDownloadLink = (fileUrl) => {
    return /* @__PURE__ */ import_react.default.createElement(
      "a",
      {
        "data-hook": import_data_hooks.FILE_UPLOAD_LINK,
        "data-cancel-link": true,
        ref: linkRef,
        className: import_file_upload_viewer_scss.default.file_upload_link,
        tabIndex,
        href: fileUrl,
        target: settings.downloadTarget,
        download: componentData.name || true,
        onClick: onFileClick
      },
      /* @__PURE__ */ import_react.default.createElement(FileViewerContent, { state, fileData: componentData })
    );
  };
  const renderResolverButton = (resolveFileUrl) => {
    const handleClick = () => {
      if (isResolvingUrl) {
        return;
      }
      setResolvingUrl(true);
      resolveFileUrl({
        id: componentData?.src?.id,
        type: componentData.type,
        path: componentData.path,
        mimeType: componentData.mimeType,
        name: componentData.name,
        size: componentData.size,
        pdfSettings: componentData.pdfSettings,
        privacy: componentData?.src?.private ? "private" : "public"
      }).then((resolvedFileUrl2) => {
        setResolvedFileUrl(resolvedFileUrl2);
        setResolvingUrl(false);
        setShouldDownloadOnRender(true);
      });
    };
    const handleKeyDown = (e) => {
      if (e.key === "Enter") {
        handleClick();
      }
    };
    return /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        onClick: handleClick,
        onKeyDown: handleKeyDown,
        className: import_file_upload_viewer_scss.default.file_upload_link
      },
      /* @__PURE__ */ import_react.default.createElement(FileViewerContent, { state, fileData: componentData })
    );
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      "data-hook": import_data_hooks.ROOT,
      className: (0, import_classnames.default)(
        import_file_upload_viewer_scss.default.file_upload_container,
        componentData.error && import_file_upload_viewer_scss.default.file_upload_error_container
      )
    },
    (() => {
      if (componentData.error || tempDataPlaceHolder) {
        return renderContainerWithoutLink();
      }
      const baseFileUrl = componentData.src?.url || resolvedFileUrl;
      const fileUrl = baseFileUrl && componentData.type !== "pdf" ? `${baseFileUrl}${baseFileUrl.includes("?") ? "&" : "?"}dn=${encodeURIComponent(
        componentData.name || ""
      )}` : baseFileUrl;
      const resolveFileUrl = settings.resolveFileUrl ?? helpers?.resolveFileUrl;
      if (fileUrl) {
        return renderDownloadLink(fileUrl);
      }
      return resolveFileUrl ? renderResolverButton(resolveFileUrl) : renderContainerWithoutLink();
    })()
  );
};
//# sourceMappingURL=file-viewer.js.map
