(function () {
  if (window.__FluidSynthReady) return;

  var FLUIDSYNTH_JS_URL;
  var FLUIDSYNTH_WASM_URL;

  if (window.__FLUIDSYNTH_CDN) {
    FLUIDSYNTH_JS_URL = window.__FLUIDSYNTH_CDN;
  } else if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    FLUIDSYNTH_JS_URL = 'https://cdn.jsdelivr.net/npm/@enikey87/fluidsynth-emscripten@0.1.1/dist/libfluidsynth-2.3.0-sf3.js';
  } else {
    FLUIDSYNTH_JS_URL = '/static/js/vendor/libfluidsynth-2.3.0-sf3.js';
  }

  FLUIDSYNTH_WASM_URL = FLUIDSYNTH_JS_URL.replace(/\.js$/, '.wasm');

  window.__FluidSynthLocateWasm = function () { return FLUIDSYNTH_WASM_URL; };

  window.__FluidSynthReady = new Promise(function (resolve) {
    var script = document.createElement('script');
    script.type = 'module';
    script.textContent = [
      'import FluidsynthModule from "' + FLUIDSYNTH_JS_URL + '";',
      'window.__FluidSynthModuleFactory = FluidsynthModule;',
      'console.log("[FluidSynth] Loaded:", "' + FLUIDSYNTH_JS_URL + '");'
    ].join('\n');
    document.head.appendChild(script);

    var check = setInterval(function () {
      if (window.__FluidSynthModuleFactory) {
        clearInterval(check);
        resolve();
      }
    }, 50);
    setTimeout(function () { clearInterval(check); resolve(); }, 15000);
  });
})();
