class PcmProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.buffer = [];
    // sampleRate is a global in AudioWorkletProcessor scope
    this.ratio = sampleRate / 16000;
    this.needsResample = Math.abs(this.ratio - 1.0) > 0.01;
    this.resamplePos = 0;
  }

  process(inputs) {
    const input = inputs[0];
    if (!input || input.length === 0) return true;

    const samples = input[0]; // First channel (mono)
    if (!samples) return true;

    if (this.needsResample) {
      // Simple downsampling to 16kHz
      for (let i = 0; i < samples.length; i++) {
        this.resamplePos += 1;
        if (this.resamplePos >= this.ratio) {
          this.buffer.push(samples[i]);
          this.resamplePos -= this.ratio;
        }
      }
    } else {
      for (let i = 0; i < samples.length; i++) {
        this.buffer.push(samples[i]);
      }
    }

    // Send every ~0.5 seconds at 16kHz = 8000 samples
    if (this.buffer.length >= 8000) {
      this.port.postMessage({ type: "pcm", samples: this.buffer });
      this.buffer = [];
    }

    return true;
  }
}

registerProcessor("pcm-processor", PcmProcessor);
