window.WhisperPro = {
    worker: null,
    onFinal: null,

    init() {
        this.worker = new Worker("assets/whisper/worker.js");

        this.worker.onmessage = (ev) => {
            const msg = ev.data;
            if (msg.type === "ready") console.log("Whisper pronto");
            if (msg.type === "final") this.onFinal && this.onFinal(msg.text);
        };

        this.worker.postMessage({
            type: "init"
        });
    },

    startMic() {
        navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
            const ctx = new AudioContext();
            const src = ctx.createMediaStreamSource(stream);
            const proc = ctx.createScriptProcessor(4096, 1, 1);

            proc.onaudioprocess = (e) => {
                const pcm = e.inputBuffer.getChannelData(0);
                this.worker.postMessage({ type: "pcm", pcm });
            };

            src.connect(proc);
            proc.connect(ctx.destination);

            console.log("Microfone iniciado.");
        });
    }
};
