/**
 * Beat playback via WebAudio with loop support and volume control.
 * Decouples from the mic stream — beat plays through speakers/headphones,
 * mic records only the user's voice (with echo cancellation on).
 */

export interface Beat {
  slug: string;
  title: string;
  bpm: number;
  key: string;
  url: string;
  durationSec: number;
}

export class BeatPlayer {
  private audio: HTMLAudioElement;
  private current: Beat | null = null;

  constructor() {
    this.audio = new Audio();
    this.audio.loop = true;
    this.audio.preload = "auto";
    this.audio.crossOrigin = "anonymous";
  }

  async load(beat: Beat) {
    if (this.current?.slug === beat.slug) return;
    this.current = beat;
    // URL relativ zur App-Base; durch base="./" in vite.config resolved Browser korrekt.
    this.audio.src = beat.url.startsWith("/") || beat.url.startsWith("http") ? beat.url : `./${beat.url.replace(/^\.?\//, "")}`;
    try { this.audio.load(); } catch {}
  }

  async play() {
    try {
      await this.audio.play();
    } catch (e) {
      // Auto-play blocked or no source yet
      console.warn("beat play failed", e);
    }
  }

  pause() {
    this.audio.pause();
  }

  stop() {
    this.audio.pause();
    this.audio.currentTime = 0;
  }

  setVolume(v: number) {
    this.audio.volume = Math.max(0, Math.min(1, v));
  }

  isPlaying(): boolean {
    return !this.audio.paused;
  }

  get currentBeat(): Beat | null {
    return this.current;
  }
}
