"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);

// packages/block-editor/src/components/inserter/media-tab/media-preview.js
var media_preview_exports = {};
__export(media_preview_exports, {
  MediaPreview: () => MediaPreview
});
module.exports = __toCommonJS(media_preview_exports);
var import_clsx = __toESM(require("clsx"));
var import_components = require("@wordpress/components");
var import_i18n = require("@wordpress/i18n");
var import_element = require("@wordpress/element");
var import_blocks = require("@wordpress/blocks");
var import_icons = require("@wordpress/icons");
var import_data = require("@wordpress/data");
var import_notices = require("@wordpress/notices");
var import_blob = require("@wordpress/blob");
var import_url = require("@wordpress/url");
var import_inserter_draggable_blocks = __toESM(require("../../inserter-draggable-blocks"));
var import_utils = require("./utils");
var import_store = require("../../../store");
var import_jsx_runtime = require("react/jsx-runtime");
var ALLOWED_MEDIA_TYPES = ["image"];
var MEDIA_OPTIONS_POPOVER_PROPS = {
  placement: "bottom-end",
  className: "block-editor-inserter__media-list__item-preview-options__popover"
};
function MediaPreviewOptions({ category, media }) {
  if (!category.getReportUrl) {
    return null;
  }
  const reportUrl = category.getReportUrl(media);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_components.DropdownMenu,
    {
      className: "block-editor-inserter__media-list__item-preview-options",
      label: (0, import_i18n.__)("Options"),
      popoverProps: MEDIA_OPTIONS_POPOVER_PROPS,
      icon: import_icons.moreVertical,
      children: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_components.MenuItem,
        {
          onClick: () => window.open(reportUrl, "_blank").focus(),
          icon: import_icons.external,
          children: (0, import_i18n.sprintf)(
            /* translators: %s: The media type to report e.g: "image", "video", "audio" */
            (0, import_i18n.__)("Report %s"),
            category.mediaType
          )
        }
      ) })
    }
  );
}
function InsertExternalImageModal({ onClose, onSubmit }) {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
    import_components.Modal,
    {
      title: (0, import_i18n.__)("Insert external image"),
      onRequestClose: onClose,
      className: "block-editor-inserter-media-tab-media-preview-inserter-external-image-modal",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.__experimentalVStack, { spacing: 3, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { children: (0, import_i18n.__)(
            "This image cannot be uploaded to your Media Library, but it can still be inserted as an external image."
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { children: (0, import_i18n.__)(
            "External images can be removed by the external provider without warning and could even have legal compliance issues related to privacy legislation."
          ) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
          import_components.Flex,
          {
            className: "block-editor-block-lock-modal__actions",
            justify: "flex-end",
            expanded: false,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                import_components.Button,
                {
                  __next40pxDefaultSize: true,
                  variant: "tertiary",
                  onClick: onClose,
                  children: (0, import_i18n.__)("Cancel")
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                import_components.Button,
                {
                  __next40pxDefaultSize: true,
                  variant: "primary",
                  onClick: onSubmit,
                  children: (0, import_i18n.__)("Insert")
                }
              ) })
            ]
          }
        )
      ]
    }
  );
}
function MediaPreview({ media, onClick, category }) {
  const [showExternalUploadModal, setShowExternalUploadModal] = (0, import_element.useState)(false);
  const [isHovered, setIsHovered] = (0, import_element.useState)(false);
  const [isInserting, setIsInserting] = (0, import_element.useState)(false);
  const [block, preview] = (0, import_element.useMemo)(
    () => (0, import_utils.getBlockAndPreviewFromMedia)(media, category.mediaType),
    [media, category.mediaType]
  );
  const { createErrorNotice, createSuccessNotice } = (0, import_data.useDispatch)(import_notices.store);
  const { getSettings, getBlock } = (0, import_data.useSelect)(import_store.store);
  const { updateBlockAttributes } = (0, import_data.useDispatch)(import_store.store);
  const onMediaInsert = (0, import_element.useCallback)(
    (previewBlock) => {
      if (isInserting) {
        return;
      }
      const settings = getSettings();
      const clonedBlock = (0, import_blocks.cloneBlock)(previewBlock);
      const { id, url, caption } = clonedBlock.attributes;
      if (!id && !settings.mediaUpload) {
        setShowExternalUploadModal(true);
        return;
      }
      if (!!id) {
        onClick(clonedBlock);
        return;
      }
      setIsInserting(true);
      window.fetch(url).then((response) => response.blob()).then((blob) => {
        const fileName = (0, import_url.getFilename)(url) || "image.jpg";
        const file = new File([blob], fileName, {
          type: blob.type
        });
        settings.mediaUpload({
          filesList: [file],
          additionalData: { caption },
          onFileChange([img]) {
            if ((0, import_blob.isBlobURL)(img.url)) {
              return;
            }
            if (!getBlock(clonedBlock.clientId)) {
              onClick({
                ...clonedBlock,
                attributes: {
                  ...clonedBlock.attributes,
                  id: img.id,
                  url: img.url
                }
              });
              createSuccessNotice(
                (0, import_i18n.__)("Image uploaded and inserted."),
                { type: "snackbar", id: "inserter-notice" }
              );
            } else {
              updateBlockAttributes(clonedBlock.clientId, {
                ...clonedBlock.attributes,
                id: img.id,
                url: img.url
              });
            }
            setIsInserting(false);
          },
          allowedTypes: ALLOWED_MEDIA_TYPES,
          onError(message) {
            createErrorNotice(message, {
              type: "snackbar",
              id: "inserter-notice"
            });
            setIsInserting(false);
          }
        });
      }).catch(() => {
        setShowExternalUploadModal(true);
        setIsInserting(false);
      });
    },
    [
      isInserting,
      getSettings,
      onClick,
      createSuccessNotice,
      updateBlockAttributes,
      createErrorNotice,
      getBlock
    ]
  );
  const title = typeof media.title === "string" ? media.title : media.title?.rendered || (0, import_i18n.__)("no title");
  const onMouseEnter = (0, import_element.useCallback)(() => setIsHovered(true), []);
  const onMouseLeave = (0, import_element.useCallback)(() => setIsHovered(false), []);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_inserter_draggable_blocks.default, { isEnabled: true, blocks: [block], children: ({ draggable, onDragStart, onDragEnd }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        className: (0, import_clsx.default)(
          "block-editor-inserter__media-list__list-item",
          {
            "is-hovered": isHovered
          }
        ),
        draggable,
        onDragStart,
        onDragEnd,
        children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
          "div",
          {
            onMouseEnter,
            onMouseLeave,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Tooltip, { text: title, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                import_components.Composite.Item,
                {
                  render: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                    "div",
                    {
                      "aria-label": title,
                      role: "option",
                      className: "block-editor-inserter__media-list__item"
                    }
                  ),
                  onClick: () => onMediaInsert(block),
                  children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "block-editor-inserter__media-list__item-preview", children: [
                    preview,
                    isInserting && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "block-editor-inserter__media-list__item-preview-spinner", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Spinner, {}) })
                  ] })
                }
              ) }),
              !isInserting && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                MediaPreviewOptions,
                {
                  category,
                  media
                }
              )
            ]
          }
        )
      }
    ) }),
    showExternalUploadModal && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      InsertExternalImageModal,
      {
        onClose: () => setShowExternalUploadModal(false),
        onSubmit: () => {
          onClick((0, import_blocks.cloneBlock)(block));
          createSuccessNotice((0, import_i18n.__)("Image inserted."), {
            type: "snackbar",
            id: "inserter-notice"
          });
          setShowExternalUploadModal(false);
        }
      }
    )
  ] });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MediaPreview
});
//# sourceMappingURL=media-preview.js.map
