class PCMProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.buffer = new Float32Array(0);
    this.port.onmessage = (e) => {
      const incoming = e.data;
      const merged = new Float32Array(this.buffer.length + incoming.length);
      merged.set(this.buffer);
      merged.set(incoming, this.buffer.length);
      this.buffer = merged;
    };
  }

  process(_inputs, outputs) {
    const output = outputs[0];
    if (!output || output.length === 0) return true;

    const channels = output.length;
    const frameSize = output[0].length;
    const samplesNeeded = frameSize * channels;

    if (this.buffer.length >= samplesNeeded) {
      // Deinterleave: buffer is interleaved L R L R ...
      for (let i = 0; i < frameSize; i++) {
        for (let ch = 0; ch < channels; ch++) {
          output[ch][i] = this.buffer[i * channels + ch];
        }
      }
      this.buffer = this.buffer.slice(samplesNeeded);
    } else {
      // Not enough data — output silence
      for (let ch = 0; ch < channels; ch++) {
        output[ch].fill(0);
      }
    }

    return true;
  }
}

registerProcessor('pcm-processor', PCMProcessor);
