/*!
 * fireplayer-plugin-audio-track.js v1.1.0
 * Github: https://fireplayer.net
 * Fire Player - https://fireplayer.net
 * Released under the MIT License.
 */
function fireplayerPluginAudioTrack(option) {
  return (fire) => {
    let { url, offset = 0, sync = 0.3 } = option;
    const audio = new Audio();
    audio.preload = "auto";
    if (url) {
      audio.src = url;
    }
    function syncAudio() {
      if (!fire.video || !url)
        return;
      const videoTime = fire.currentTime;
      const targetTime = videoTime + offset;
      if (Math.abs(audio.currentTime - targetTime) > sync) {
        audio.currentTime = targetTime;
      }
    }
    fire.on("play", () => {
      if (!url)
        return;
      syncAudio();
      audio.play().catch((err) => {
        console.warn(err);
      });
    });
    fire.on("pause", () => {
      audio.pause();
    });
    fire.on("seek", () => {
      syncAudio();
    });
    fire.on("video:timeupdate", () => {
      if (fire.playing) {
        syncAudio();
      }
    });
    fire.on("video:ratechange", () => {
      audio.playbackRate = fire.video.playbackRate;
    });
    fire.on("video:volumechange", () => {
      audio.volume = fire.volume;
      audio.muted = fire.muted;
    });
    fire.on("video:waiting", () => {
      audio.pause();
    });
    fire.on("video:playing", () => {
      if (url && fire.playing) {
        audio.play().catch((err) => {
          console.warn(err);
        });
      }
    });
    fire.on("destroy", () => {
      audio.pause();
      audio.src = "";
      audio.load();
    });
    function update(newOption) {
      if (newOption.url && newOption.url !== url) {
        url = newOption.url;
        audio.src = url;
        if (fire.playing) {
          audio.play().catch((err) => console.warn(err));
        }
      }
      if (newOption.offset !== void 0) {
        offset = newOption.offset;
      }
      if (newOption.sync !== void 0) {
        sync = newOption.sync;
      }
    }
    audio.volume = fire.volume;
    audio.muted = fire.muted;
    audio.playbackRate = fire.video?.playbackRate || 1;
    return {
      name: "fireplayerPluginAudioTrack",
      audio,
      update
    };
  };
}
export {
  fireplayerPluginAudioTrack as default
};
