(function () {
  if (document.body.dataset['marketwebComponentsInit']) {
    return;
  }
  document.body.dataset['marketwebComponentsInit'] = true;
  const checkParameters = function (originSrc) {
    if (!originSrc.indexOf('?')) {
      return;
    }
    const originalQueryString = originSrc.substring(originSrc.indexOf('?') + 1);
    const originalParams = new URLSearchParams(originalQueryString);
    const injectElements = originalParams
      .get('inject')
      .split(',')
      .map(function (item) {
        return item.trim();
      });
    injectElements.forEach(function (element) {
      const s = document.createElement('script');
      let injectSrc = originSrc.replace('pn-marketweb-init.js', 'pn-marketweb-inject.js');
      injectSrc = injectSrc.substring(0, injectSrc.indexOf('?'));
      const params = new URLSearchParams(originalQueryString);
      params.delete('inject');
      params.set('inject', element);

      if (element.indexOf('header') !== -1) {
        params.set('domlocation', 'top');
      }
      if (element.indexOf('footer') !== -1) {
        params.set('domlocation', 'bottom');
      }

      s.setAttribute('src', `${injectSrc}?${params.toString()}`);
      document.querySelector('head').appendChild(s);
    });
  };

  const s = document.createElement('script');
  const currentMinorVersion = "4.3.0";
  const requestedComponentVersion = (new URLSearchParams(window.location.search)).get("componentversion");
  const versionToLoad = (requestedComponentVersion) ? requestedComponentVersion : currentMinorVersion;
  const currentScriptTag = document.querySelector('script[src*="pn-marketweb-init.js"]');
  let currentScriptSrc = currentScriptTag.getAttribute('src');
  currentScriptSrc = currentScriptSrc.replace('@latest', '@' + versionToLoad);
  checkParameters(currentScriptSrc);
  const loaderScriptSrc = currentScriptSrc.replace('pn-marketweb-init.js', 'standalone-loader.js');
  s.setAttribute('type', 'module');
  s.setAttribute('src', loaderScriptSrc);
  document.querySelector('head').appendChild(s);
})();
