import { useEffect } from "react";

export const useVKMetrics = (vkMetricsNumber: number | undefined, preview: boolean = false) => {
  useEffect(() => {
    if (vkMetricsNumber && typeof vkMetricsNumber === "number" && !Number.isNaN(vkMetricsNumber) && !preview) {
      const script = document.createElement("script");
      script.type = "text/javascript";
      script.innerHTML = `
        var _tmr = window._tmr || (window._tmr = []);
        _tmr.push({id: "${vkMetricsNumber}", type: "pageView", start: (new Date()).getTime()});
        (function (d, w, id) {
          if (d.getElementById(id)) return;
          var ts = d.createElement("script"); ts.type = "text/javascript"; ts.async = true; ts.id = id;
          ts.src = "https://top-fwz1.mail.ru/js/code.js";
          var f = function () {var s = d.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ts, s);};
          if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); }
        })(document, window, "tmr-code");
      `;
      document.body.appendChild(script);

      const noscript = document.createElement("noscript");
      noscript.innerHTML = `<div><img src="https://top-fwz1.mail.ru/counter?id=${vkMetricsNumber};js=na" style="position:absolute;left:-9999px;" alt="Top.Mail.Ru" /></div>`;
      document.body.appendChild(noscript);
    }
  }, [vkMetricsNumber]);
};
