class PCMRecorderProcessor 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.length > 0) {
            const inputChannel = input[0]; // Mono Channel 0
            
            for (let i = 0; i < inputChannel.length; i++) {
                this.buffer[this.bufferIndex++] = inputChannel[i];
                
                // When Ring-Buffer fills, send Float32Array to Main Thread
                if (this.bufferIndex >= this.bufferSize) {
                    this.port.postMessage({
                        type: 'PCM_DATA',
                        buffer: this.buffer.slice(0, this.bufferSize)
                    });
                    this.bufferIndex = 0;
                }
            }
        }
        return true; // Keep worklet active
    }
}

registerProcessor('pcm-recorder-processor', PCMRecorderProcessor);
