import Phaser from "phaser";
import { BACKGROUND_MUSIC_KEY } from "../scenes/BootScene";

const BACKGROUND_MUSIC_VOLUME = 0.34;

export function ensureBackgroundMusic(scene: Phaser.Scene): void {
  if (!scene.cache.audio.exists(BACKGROUND_MUSIC_KEY)) {
    return;
  }

  const playLoop = () => {
    const existing = scene.sound.get(BACKGROUND_MUSIC_KEY);
    if (existing && existing.isPlaying) {
      return;
    }

    scene.sound.stopByKey(BACKGROUND_MUSIC_KEY);
    scene.sound.play(BACKGROUND_MUSIC_KEY, {
      loop: true,
      volume: BACKGROUND_MUSIC_VOLUME
    });
  };

  if (scene.sound.locked) {
    scene.sound.once("unlocked", playLoop);
    return;
  }

  playLoop();
}
