function injectGtm(id) {
  const w = window;
  w.dataLayer = w.dataLayer || [];
  w.dataLayer.push({ 'gtm.start': Date.now(), event: 'gtm.js' });
  const firstScript = document.getElementsByTagName('script')[0];
  const gtmScript = document.createElement('script');
  gtmScript.async = true;
  gtmScript.src = 'https://www.googletagmanager.com/gtm.js?id=' + id;
  firstScript.parentNode.insertBefore(gtmScript, firstScript);
  const nos = document.createElement('noscript');
  const iframe = document.createElement('iframe');
  iframe.src = 'https://www.googletagmanager.com/ns.html?id=' + id;
  iframe.height = '0';
  iframe.width = '0';
  iframe.setAttribute('style', 'display:none;visibility:hidden');
  nos.appendChild(iframe);
  document.body.insertBefore(nos, document.body.firstChild);
}


function injectGtag(ids) {
  const list = ids.filter(Boolean);
  if (!list.length) {
    return;
  }
  const s = document.createElement('script');
  s.async = true;
  s.src = 'https://www.googletagmanager.com/gtag/js?id=' + list[0];
  document.head.appendChild(s);
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    window.dataLayer.push(arguments);
  }
  window.gtag = gtag;
  gtag('js', new Date());
  list.forEach((id) => {
    gtag('config', id);
  });
}


function injectYandex(id, webvisor) {
  if (!id) {
    return;
  }
  (function (m, e, t, r, i, k, a) {
    m[i] =
      m[i] ||
      function () {
        (m[i].a = m[i].a || []).push(arguments);
      };
    m[i].l = 1 * new Date();
    for (let j = 0; j < document.scripts.length; j += 1) {
      if (document.scripts[j].src === r) {
        return;
      }
    }
    k = e.createElement(t);
    a = e.getElementsByTagName(t)[0];
    k.async = 1;
    k.src = r;
    a.parentNode.insertBefore(k, a);
  })(window, document, 'script', 'https://mc.yandex.ru/metrika/tag.js', 'ym');
  window.ym(id, 'init', {
    clickmap: true,
    trackLinks: true,
    accurateTrackBounce: true,
    webvisor: !!webvisor,
  });
}


function runTracking() {
  const c = window.__SITE_CONFIG__ || {};
  if (c.gtmContainerId) {
    injectGtm(c.gtmContainerId);
  } else {
    injectGtag([c.ga4MeasurementId, c.googleAdsId].filter(Boolean));
  }
  injectYandex(c.yandexMetrikaId, c.yandexWebvisor);
}


runTracking();
