export class AudioPlayer {
  private context: AudioContext | null = null;
  private source: AudioBufferSourceNode | null = null;

  async playPCM(base64Data: string, sampleRate: number = 24000) {
    this.stop();
    
    if (!this.context) {
      this.context = new AudioContext({ sampleRate });
    }
    if (this.context.state === 'suspended') {
      await this.context.resume();
    }

    const binaryString = atob(base64Data);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }

    // The data is 16-bit PCM (little endian)
    const float32Data = new Float32Array(bytes.length / 2);
    const dataView = new DataView(bytes.buffer);
    for (let i = 0; i < float32Data.length; i++) {
      const int16 = dataView.getInt16(i * 2, true);
      float32Data[i] = int16 / 32768.0;
    }

    const audioBuffer = this.context.createBuffer(1, float32Data.length, sampleRate);
    audioBuffer.getChannelData(0).set(float32Data);

    this.source = this.context.createBufferSource();
    this.source.buffer = audioBuffer;
    this.source.connect(this.context.destination);
    
    return new Promise<void>((resolve) => {
      this.source!.onended = () => resolve();
      this.source!.start();
    });
  }

  stop() {
    if (this.source) {
      this.source.stop();
      this.source.disconnect();
      this.source = null;
    }
  }
}
