// packages/block-library/src/utils/waveform-player.js
import { useEffect, useRef } from "@wordpress/element";
import { useEvent, useRefEffect } from "@wordpress/compose";
import { initWaveformPlayer } from "./waveform-utils.mjs";
import { jsx } from "react/jsx-runtime";
var EMPTY_ARTIST_PLACEHOLDER = " ";
function updatePlayerMetadata(instance, { title, artist, image }) {
  if (instance.titleEl) {
    instance.titleEl.textContent = title ?? "";
  }
  if (instance.subtitleEl) {
    instance.subtitleEl.textContent = artist ?? "";
    instance.subtitleEl.style.display = artist ? "" : "none";
  }
  if (instance.artworkEl && image) {
    instance.artworkEl.src = image;
  }
}
function WaveformPlayer({
  src,
  title,
  artist,
  image,
  waveformStyle,
  onEnded
}) {
  const onEndedEvent = useEvent(onEnded);
  const metadataRef = useRef({ title, artist, image });
  const playerRef = useRef();
  const hasImage = !!image;
  useEffect(() => {
    metadataRef.current = { title, artist, image };
    const instance = playerRef.current?.instance;
    if (instance) {
      updatePlayerMetadata(instance, { title, artist, image });
    }
  }, [title, artist, image]);
  const ref = useRefEffect(
    (element) => {
      if (!src) {
        return;
      }
      let cancelled = false;
      let playerDestroy;
      function init() {
        if (cancelled) {
          return;
        }
        const player = initWaveformPlayer(element, {
          src,
          ...metadataRef.current,
          waveformStyle,
          artist: metadataRef.current.artist || EMPTY_ARTIST_PLACEHOLDER,
          onEnded: () => onEndedEvent?.()
        });
        playerRef.current = player;
        updatePlayerMetadata(player.instance, metadataRef.current);
        const { destroy } = player;
        playerDestroy = destroy;
      }
      const timeoutId = setTimeout(init, 100);
      return () => {
        cancelled = true;
        clearTimeout(timeoutId);
        playerRef.current = void 0;
        playerDestroy?.();
      };
    },
    [onEndedEvent, src, waveformStyle, hasImage]
  );
  return /* @__PURE__ */ jsx("div", { ref, className: "wp-block-playlist__waveform-player" });
}
export {
  WaveformPlayer
};
//# sourceMappingURL=waveform-player.mjs.map
