// packages/block-library/src/embed/edit.js
import clsx from "clsx";
import { __, _x, sprintf } from "@wordpress/i18n";
import { useState, useEffect } from "@wordpress/element";
import { useDispatch, useSelect } from "@wordpress/data";
import {
  useBlockProps,
  store as blockEditorStore
} from "@wordpress/block-editor";
import { store as coreStore } from "@wordpress/core-data";
import { View } from "@wordpress/primitives";
import { Caption } from "../utils/caption.mjs";
import {
  createUpgradedEmbedBlock,
  findMoreSuitableBlock,
  getClassNames,
  rewriteXToTwitter,
  removeAspectRatioClasses,
  fallback,
  getEmbedInfoByProvider,
  getMergedAttributesWithPreview
} from "./util.mjs";
import EmbedControls from "./embed-controls.mjs";
import { embedContentIcon } from "./icons.mjs";
import EmbedLoading from "./embed-loading.mjs";
import EmbedPlaceholder from "./embed-placeholder.mjs";
import EmbedPreview from "./embed-preview.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var EmbedEdit = (props) => {
  const {
    attributes: {
      providerNameSlug,
      previewable,
      responsive,
      url: attributesUrl
    },
    attributes,
    isSelected,
    onReplace,
    setAttributes,
    insertBlocksAfter,
    onFocus
  } = props;
  const defaultEmbedInfo = {
    title: _x("Embed", "block title"),
    icon: embedContentIcon
  };
  const { icon, title } = getEmbedInfoByProvider(providerNameSlug) || defaultEmbedInfo;
  const [url, setURL] = useState(attributesUrl);
  const [isEditingURL, setIsEditingURL] = useState(false);
  const { invalidateResolution } = useDispatch(coreStore);
  const { __unstableMarkNextChangeAsNotPersistent } = useDispatch(blockEditorStore);
  const {
    preview,
    fetching,
    themeSupportsResponsive,
    cannotEmbed,
    hasResolved
  } = useSelect(
    (select) => {
      const {
        getEmbedPreview,
        isPreviewEmbedFallback,
        isRequestingEmbedPreview,
        getThemeSupports,
        hasFinishedResolution
      } = select(coreStore);
      if (!attributesUrl) {
        return { fetching: false, cannotEmbed: false };
      }
      const embedPreview = getEmbedPreview(attributesUrl);
      const previewIsFallback = isPreviewEmbedFallback(attributesUrl);
      const badEmbedProvider = embedPreview?.html === false && embedPreview?.type === void 0;
      const wordpressCantEmbed = embedPreview?.data?.status === 404;
      const validPreview = !!embedPreview && !badEmbedProvider && !wordpressCantEmbed;
      return {
        preview: validPreview ? embedPreview : void 0,
        fetching: isRequestingEmbedPreview(attributesUrl),
        themeSupportsResponsive: getThemeSupports()["responsive-embeds"],
        cannotEmbed: !validPreview || previewIsFallback,
        hasResolved: hasFinishedResolution("getEmbedPreview", [
          attributesUrl
        ])
      };
    },
    [attributesUrl]
  );
  const getMergedAttributes = () => getMergedAttributesWithPreview(
    attributes,
    preview,
    title,
    responsive
  );
  function toggleResponsive(newAllowResponsive) {
    const { className: className2 } = attributes;
    const { html } = preview;
    setAttributes({
      allowResponsive: newAllowResponsive,
      className: getClassNames(
        html,
        className2,
        responsive && newAllowResponsive
      )
    });
  }
  useEffect(() => {
    if (!cannotEmbed || !hasResolved || !attributesUrl) {
      return;
    }
    const newURL = attributesUrl.replace(/\/$/, "");
    if (newURL === attributesUrl) {
      return;
    }
    setURL(newURL);
    setIsEditingURL(false);
    __unstableMarkNextChangeAsNotPersistent();
    setAttributes({ url: newURL });
  }, [
    attributesUrl,
    cannotEmbed,
    hasResolved,
    setAttributes,
    __unstableMarkNextChangeAsNotPersistent
  ]);
  useEffect(() => {
    if (!preview || isEditingURL) {
      return;
    }
    const mergedAttributes = getMergedAttributes();
    if (onReplace) {
      const upgradedBlock = createUpgradedEmbedBlock(
        props,
        mergedAttributes
      );
      if (upgradedBlock) {
        __unstableMarkNextChangeAsNotPersistent();
        setAttributes(upgradedBlock.attributes);
        return;
      }
    }
    const hasChanges = Object.keys(mergedAttributes).some(
      (key) => mergedAttributes[key] !== attributes[key]
    );
    if (hasChanges) {
      __unstableMarkNextChangeAsNotPersistent();
      setAttributes(mergedAttributes);
    }
  }, [preview, isEditingURL]);
  const blockProps = useBlockProps();
  if (fetching) {
    return /* @__PURE__ */ jsx(View, { ...blockProps, children: /* @__PURE__ */ jsx(EmbedLoading, {}) });
  }
  const label = sprintf(__("%s URL"), title);
  const showEmbedPlaceholder = !preview || cannotEmbed || isEditingURL;
  if (showEmbedPlaceholder) {
    return /* @__PURE__ */ jsx(View, { ...blockProps, children: /* @__PURE__ */ jsx(
      EmbedPlaceholder,
      {
        icon,
        label,
        onFocus,
        onSubmit: (event) => {
          if (event) {
            event.preventDefault();
          }
          const rewrittenURL = rewriteXToTwitter(url);
          const blockClass = removeAspectRatioClasses(
            attributes.className
          );
          setURL(rewrittenURL);
          setAttributes({
            url: rewrittenURL,
            ...findMoreSuitableBlock(rewrittenURL)?.attributes,
            className: blockClass
          });
          setIsEditingURL(false);
        },
        value: url,
        cannotEmbed,
        onChange: (value) => setURL(value),
        fallback: () => fallback(url, onReplace),
        tryAgain: () => {
          invalidateResolution("getEmbedPreview", [url]);
        }
      }
    ) });
  }
  const {
    caption,
    type,
    allowResponsive,
    className: classFromPreview
  } = getMergedAttributes();
  const className = clsx(classFromPreview, props.className);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      EmbedControls,
      {
        showEditButton: preview && !cannotEmbed,
        themeSupportsResponsive,
        blockSupportsResponsive: responsive,
        allowResponsive,
        toggleResponsive,
        switchBackToURLInput: () => setIsEditingURL(true)
      }
    ),
    /* @__PURE__ */ jsxs(
      "figure",
      {
        ...blockProps,
        className: clsx(blockProps.className, className, {
          [`is-type-${type}`]: type,
          [`is-provider-${providerNameSlug}`]: providerNameSlug,
          [`wp-block-embed-${providerNameSlug}`]: providerNameSlug
        }),
        children: [
          /* @__PURE__ */ jsx(
            EmbedPreview,
            {
              preview,
              previewable,
              className,
              url,
              type,
              caption,
              onCaptionChange: (value) => setAttributes({ caption: value }),
              isSelected,
              icon,
              label,
              insertBlocksAfter,
              attributes,
              setAttributes
            }
          ),
          /* @__PURE__ */ jsx(
            Caption,
            {
              attributes,
              setAttributes,
              isSelected,
              insertBlocksAfter,
              label: __("Embed caption text"),
              showToolbarButton: isSelected
            }
          )
        ]
      }
    )
  ] });
};
var edit_default = EmbedEdit;
export {
  edit_default as default
};
//# sourceMappingURL=edit.mjs.map
