import { Button, FormField, Input } from "@wix/design-system";
import React, { useContext, useRef, useState } from "react";
import { generateId } from "./../../ricos-content/index.js";
import { DevContext } from "./../../ricos-context/dev-context.js";
import { EditorContext, PluginsEventsContext, RicosContext } from "./../../ricos-context/index.js";
import { fetchOembedWithAuth } from "./../../_shared/fetch-embed-data.js";
import { containsUrl } from "./../../_shared/link/contains-url.js";
import { useRequestService } from "./../../_shared/request-service-provider/request-service-provider.js";
import { ReactPlayer } from "./../../wix-react-player/index.js";
import { MEDIA_POPOVERS_BUTTONS_NAMES_BI } from "./../../wix-rich-content-common/index.js";
import { EMBED_TAB_SUBMIT_BUTTON, EMBED_TAB_URL_INPUT } from "../data-hooks.js";
import classes from "../statics/styles/audio-embed-scss.js";
import { AUDIO_TYPE } from "../types.js";
import { isSoundcloudUrl } from "./utils.js";
const AudioEmbed = ({
  componentData,
  closeModal,
  nodeId,
  logBi
}) => {
  const { t } = useContext(RicosContext);
  const { getPublicCommands } = useContext(EditorContext);
  const pluginsEvents = useContext(PluginsEventsContext);
  const { fetchOembedWithAuthFromDevContext } = useContext(DevContext);
  const { makeRequest } = useRequestService();
  const [url, setUrl] = useState(componentData?.audio?.src?.url || "");
  const [submittedInvalidUrl, setSubmittedInvalidUrl] = useState(false);
  const inputRef = useRef(null);
  const onEmbedClick = async () => {
    pluginsEvents.publishPluginPopoverClick?.({
      pluginId: AUDIO_TYPE,
      buttonName: MEDIA_POPOVERS_BUTTONS_NAMES_BI.embed
    });
    logBi({ dataHook: EMBED_TAB_SUBMIT_BUTTON });
    const { audio, name, coverImage, authorName, disableDownload, ...rest } = componentData;
    if (url && (!containsUrl(url) || !hasValidFilePath(url))) {
      setSubmittedInvalidUrl(true);
      return;
    }
    if (isSoundcloudUrl(url)) {
      await fetchAndEmbedAudio(url, rest);
    } else if (ReactPlayer.canPlay(url)) {
      updateRicosDocument({ audio: { src: { url } } });
      closeModal();
    } else {
      await fetchAndEmbedAudio(url, rest);
    }
  };
  const fetchAndEmbedAudio = async (url2, data) => {
    try {
      const { html } = await fetchOembedWithAuthFromDevContext?.(url2) || await fetchOembedWithAuth?.(url2, makeRequest) || {};
      if (html) {
        updateRicosDocument({ ...data, audio: { src: { url: url2 } }, html });
        closeModal();
      } else {
        setSubmittedInvalidUrl(true);
        inputRef.current?.focus();
      }
    } catch {
      setSubmittedInvalidUrl(true);
      inputRef.current?.focus();
    }
  };
  const updateRicosDocument = (audio) => queueMicrotask(
    () => nodeId ? getPublicCommands().setBlock(nodeId, AUDIO_TYPE, audio) : getPublicCommands().insertBlockWithBlankLines(AUDIO_TYPE, { ...audio, id: generateId() })
  );
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    FormField,
    {
      label: t("AudioModal_Embed_Title"),
      maxLines: 2,
      status: submittedInvalidUrl ? "error" : void 0,
      statusMessage: submittedInvalidUrl ? t("SoundCloudUploadModal_Input_InvalidUrl") : void 0
    },
    /* @__PURE__ */ React.createElement(
      Input,
      {
        inputRef: (ref) => {
          inputRef.current = ref;
        },
        className: classes.input,
        type: "url",
        autocomplete: "off",
        dataHook: EMBED_TAB_URL_INPUT,
        value: url,
        textOverflow: "ellipsis",
        onChange: (e) => {
          setSubmittedInvalidUrl(false);
          setUrl(e.target.value);
          logBi({ dataHook: EMBED_TAB_URL_INPUT, value: e.target.value });
        },
        placeholder: t("EmbedURL_Placeholder"),
        onBlur: () => {
          if (url && !containsUrl(url)) {
            setSubmittedInvalidUrl(true);
          }
        },
        onKeyDown: (e) => {
          if (e.key === "Enter") {
            onEmbedClick();
          }
        }
      }
    )
  ), /* @__PURE__ */ React.createElement(Button, { dataHook: EMBED_TAB_SUBMIT_BUTTON, onClick: onEmbedClick, size: "small" }, t("AudioModal_Embed_ButtonText")));
};
const hasValidFilePath = (url) => {
  const urlObj = new URL(url);
  return urlObj.pathname.length > 1;
};
export {
  AudioEmbed
};
//# sourceMappingURL=audio-embed.js.map
