/**
 * AudioWorkletProcessor that downsamples 48kHz → 16kHz and sends PCM16 chunks.
 */
class VoiceProcessor extends AudioWorkletProcessor {
    constructor() {
        super();
        this._buffer = [];
        this._paused = false;
        this.port.onmessage = (e) => {
            if (e.data && e.data.type === "pause") this._paused = true;
            if (e.data && e.data.type === "resume") this._paused = false;
        };
    }

    process(inputs) {
        var input = inputs[0];
        if (!input || !input[0] || this._paused) return true;

        var samples = input[0]; // Float32Array, 128 samples at 48kHz

        // Downsample 48kHz -> 16kHz (take every 3rd sample)
        for (var i = 0; i < samples.length; i += 3) {
            this._buffer.push(samples[i]);
        }

        // Send chunks of 512 samples (32ms at 16kHz)
        while (this._buffer.length >= 512) {
            var chunk = this._buffer.splice(0, 512);
            var pcm16 = new Int16Array(512);
            for (var j = 0; j < 512; j++) {
                pcm16[j] = Math.floor(Math.max(-1, Math.min(1, chunk[j])) * 32767);
            }
            this.port.postMessage(pcm16.buffer, [pcm16.buffer]);
        }

        return true;
    }
}

registerProcessor("voice-processor", VoiceProcessor);
