class FluidSynthBridge extends AudioWorkletProcessor {
  constructor() {
    super();
    this.leftQ = [];
    this.rightQ = [];
    this.called = 0;
    this.port.onmessage = (e) => {
      const d = e.data;
      if (d.type === 'PCM') {
        this.leftQ.push(d.L);
        this.rightQ.push(d.R);
      }
    };
  }

  process(inputs, outputs) {
    const out = outputs[0];
    if (!out || out.length === 0) return true;
    this.called++;
    const numCh = out.length;
    const len = out[0].length;
    const qL = this.leftQ;
    const qR = this.rightQ;
    let fi = 0;
    let si = 0;
    // Handle any output channel count (mono devices produce 1 channel, so
    // out[1] may be undefined — never write into a missing channel).
    for (let i = 0; i < len; i++) {
      if (fi >= qL.length) {
        for (let c = 0; c < numCh; c++) out[c][i] = 0;
        continue;
      }
      for (let c = 0; c < numCh; c++) {
        out[c][i] = c % 2 === 0 ? qL[fi][si] : qR[fi][si];
      }
      si++;
      if (si >= qL[fi].length) { fi++; si = 0; }
    }
    if (fi > 0) { this.leftQ.splice(0, fi); this.rightQ.splice(0, fi); }
    return true;
  }
}

registerProcessor('fluidsynth-bridge', FluidSynthBridge);
