/**
 * AudioWorklet Processor for PCM16 capture
 * Runs in a separate thread - does NOT block the main UI thread
 */
class AudioProcessor extends AudioWorkletProcessor {
  constructor() {
    super()
    this.bufferSize = 4096
    this.buffer = new Float32Array(this.bufferSize)
    this.bufferIndex = 0
  }

  process(inputs, outputs, parameters) {
    const input = inputs[0]
    if (!input || !input[0]) return true

    const inputChannel = input[0]
    
    // Accumulate samples
    for (let i = 0; i < inputChannel.length; i++) {
      this.buffer[this.bufferIndex++] = inputChannel[i]
      
      // When buffer is full, convert to PCM16 and send
      if (this.bufferIndex >= this.bufferSize) {
        // Convert Float32 to PCM16
        const pcm16 = new Int16Array(this.bufferSize)
        for (let j = 0; j < this.bufferSize; j++) {
          const s = Math.max(-1, Math.min(1, this.buffer[j]))
          pcm16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF
        }
        
        // Send to main thread
        this.port.postMessage({
          type: 'audio',
          pcm16: pcm16.buffer
        }, [pcm16.buffer])
        
        // Reset buffer
        this.buffer = new Float32Array(this.bufferSize)
        this.bufferIndex = 0
      }
    }
    
    return true
  }
}

registerProcessor('audio-processor', AudioProcessor)
