// packages/block-editor/src/components/content-only-controls/media/index.js
import {
  Button,
  Icon,
  __experimentalGrid as Grid
} from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { __ } from "@wordpress/i18n";
import {
  audio as audioIcon,
  image as imageIcon,
  media as mediaIcon,
  video as videoIcon
} from "@wordpress/icons";
import MediaReplaceFlow from "../../media-replace-flow";
import MediaUploadCheck from "../../media-upload/check";
import { useInspectorPopoverPlacement } from "../use-inspector-popover-placement";
import { getMediaSelectKey } from "../../../store/private-keys";
import { store as blockEditorStore } from "../../../store";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function MediaThumbnail({ data, field, attachment }) {
  const config = field.config || {};
  const { allowedTypes = [], multiple = false } = config;
  if (multiple) {
    return "todo multiple";
  }
  if (attachment?.media_type === "image" || attachment?.poster) {
    return /* @__PURE__ */ jsx(
      "img",
      {
        className: "block-editor-content-only-controls__media-thumbnail",
        alt: "",
        width: 24,
        height: 24,
        src: attachment.media_type === "image" ? attachment.source_url : attachment.poster
      }
    );
  }
  if (allowedTypes.length === 1) {
    const value = field.getValue({ item: data });
    const url = value?.url;
    if (url) {
      return /* @__PURE__ */ jsx(
        "img",
        {
          className: "block-editor-content-only-controls__media-thumbnail",
          alt: "",
          width: 24,
          height: 24,
          src: url
        }
      );
    }
    let icon;
    if (allowedTypes[0] === "image") {
      icon = imageIcon;
    } else if (allowedTypes[0] === "video") {
      icon = videoIcon;
    } else if (allowedTypes[0] === "audio") {
      icon = audioIcon;
    } else {
      icon = mediaIcon;
    }
    if (icon) {
      return /* @__PURE__ */ jsx(Icon, { icon, size: 24 });
    }
  }
  return /* @__PURE__ */ jsx(Icon, { icon: mediaIcon, size: 24 });
}
function Media({ data, field, config = {} }) {
  const { popoverProps } = useInspectorPopoverPlacement({
    isControl: true
  });
  const value = field.getValue({ item: data });
  const { allowedTypes = [], multiple = false } = field.config || {};
  const { clientId, updateBlockAttributes, fieldDef } = config;
  const updateAttributes = (newFieldValue) => {
    const mappedChanges = field.setValue({
      item: data,
      value: newFieldValue
    });
    updateBlockAttributes(clientId, mappedChanges);
  };
  const hasFeaturedImageSupport = fieldDef?.mapping && "featuredImage" in fieldDef.mapping;
  const id = value?.id;
  const url = value?.url;
  const attachment = useSelect(
    (select) => {
      if (!id) {
        return;
      }
      const settings = select(blockEditorStore).getSettings();
      const getMedia = settings[getMediaSelectKey];
      if (!getMedia) {
        return;
      }
      return getMedia(select, id);
    },
    [id]
  );
  let chooseItemLabel;
  if (allowedTypes.length === 1) {
    const allowedType = allowedTypes[0];
    if (allowedType === "image") {
      chooseItemLabel = __("Choose an image\u2026");
    } else if (allowedType === "video") {
      chooseItemLabel = __("Choose a video\u2026");
    } else if (allowedType === "application") {
      chooseItemLabel = __("Choose a file\u2026");
    } else {
      chooseItemLabel = __("Choose a media item\u2026");
    }
  } else {
    chooseItemLabel = __("Choose a media item\u2026");
  }
  return /* @__PURE__ */ jsx(MediaUploadCheck, { children: /* @__PURE__ */ jsx(
    MediaReplaceFlow,
    {
      className: "block-editor-content-only-controls__media-replace-flow",
      allowedTypes,
      mediaId: id,
      mediaURL: url,
      multiple,
      popoverProps,
      onReset: () => {
        const resetValue = {};
        if (fieldDef?.mapping) {
          Object.keys(fieldDef.mapping).forEach((key) => {
            if (key === "id" || key === "src" || key === "url") {
              resetValue[key] = void 0;
            } else if (key === "caption" || key === "alt") {
              resetValue[key] = "";
            }
          });
        }
        if (hasFeaturedImageSupport) {
          resetValue.featuredImage = false;
        }
        updateAttributes({ ...value, ...resetValue });
      },
      ...hasFeaturedImageSupport && {
        useFeaturedImage: !!value?.featuredImage,
        onToggleFeaturedImage: () => {
          updateAttributes({
            ...value,
            featuredImage: !value?.featuredImage
          });
        }
      },
      onSelect: (selectedMedia) => {
        if (selectedMedia.id && selectedMedia.url) {
          let mediaType = "image";
          if (selectedMedia.mime_type) {
            if (selectedMedia.mime_type.startsWith("video/")) {
              mediaType = "video";
            } else if (selectedMedia.mime_type.startsWith("audio/")) {
              mediaType = "audio";
            }
          }
          const newValue = {};
          if (fieldDef?.mapping) {
            Object.keys(fieldDef.mapping).forEach(
              (key) => {
                if (key === "id") {
                  newValue[key] = selectedMedia.id;
                } else if (key === "src" || key === "url") {
                  newValue[key] = selectedMedia.url;
                } else if (key === "type") {
                  newValue[key] = mediaType;
                } else if (key === "link" && selectedMedia.link) {
                  newValue[key] = selectedMedia.link;
                } else if (key === "caption" && !value?.caption && selectedMedia.caption) {
                  newValue[key] = selectedMedia.caption;
                } else if (key === "alt" && !value?.alt && selectedMedia.alt) {
                  newValue[key] = selectedMedia.alt;
                } else if (key === "poster" && selectedMedia.poster) {
                  newValue[key] = selectedMedia.poster;
                }
              }
            );
          }
          if (hasFeaturedImageSupport) {
            newValue.featuredImage = false;
          }
          const finalValue = { ...value, ...newValue };
          updateAttributes(finalValue);
        }
      },
      renderToggle: (buttonProps) => /* @__PURE__ */ jsx(
        Button,
        {
          __next40pxDefaultSize: true,
          className: "block-editor-content-only-controls__media",
          ...buttonProps,
          children: /* @__PURE__ */ jsxs(
            Grid,
            {
              rowGap: 0,
              columnGap: 8,
              templateColumns: "24px 1fr",
              className: "block-editor-content-only-controls__media-row",
              children: [
                url && /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(
                    MediaThumbnail,
                    {
                      attachment,
                      field,
                      data
                    }
                  ),
                  /* @__PURE__ */ jsx("span", {
                    className: "block-editor-content-only-controls__media-title",
                    // TODO - truncate long titles or url smartly (e.g. show filename).
                    children: attachment?.title?.raw && attachment?.title?.raw !== "" ? attachment?.title?.raw : url
                  })
                ] }),
                !url && /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: "block-editor-content-only-controls__media-placeholder",
                      style: {
                        width: "24px",
                        height: "24px"
                      }
                    }
                  ),
                  /* @__PURE__ */ jsx("span", { className: "block-editor-content-only-controls__media-title", children: chooseItemLabel })
                ] })
              ]
            }
          )
        }
      )
    }
  ) });
}
export {
  Media as default
};
//# sourceMappingURL=index.js.map
