// AudioWorklet processor — captures PCM16 in ~40ms chunks at 24kHz
class CaptureProcessor extends AudioWorkletProcessor {
  constructor() {
    super()
    this.buffer = new Float32Array(960) // 40ms at 24kHz
    this.offset = 0
  }

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

    let i = 0
    while (i < input.length) {
      const remaining = this.buffer.length - this.offset
      const toCopy = Math.min(remaining, input.length - i)
      this.buffer.set(input.subarray(i, i + toCopy), this.offset)
      this.offset += toCopy
      i += toCopy

      if (this.offset >= this.buffer.length) {
        // Convert to PCM16
        const pcm16 = new Int16Array(this.buffer.length)
        let rmsSum = 0
        for (let j = 0; j < this.buffer.length; j++) {
          const s = Math.max(-1, Math.min(1, this.buffer[j]))
          pcm16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF
          rmsSum += s * s
        }
        const rms = Math.sqrt(rmsSum / this.buffer.length)
        this.port.postMessage({ pcm16, rms })
        this.offset = 0
      }
    }
    return true
  }
}

registerProcessor('capture-processor', CaptureProcessor)
