"use client";

import Script from "next/script";

import { YANDEX_METRIKA_ID } from "@/shared/constants/analytics";

/**
 * Yandex Metrika Integration Component
 *
 * Loads Yandex Metrika tracking script dynamically using static counter ID.
 *
 * Initializes with: clickmap, trackLinks, accurateTrackBounce, webvisor.
 * Page views are tracked by PageViewTracker component on route changes.
 */
export function YandexMetrika() {
  return (
    <>
      <Script
        id="yandex-metrika"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
(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 (var j = 0; j < document.scripts.length; j++) {
    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://cdn.jsdelivr.net/npm/yandex-metrica-watch/tag.js", "ym");

// Store counter ID for analyticsService
window.__YM_COUNTER_ID__ = ${YANDEX_METRIKA_ID};

ym(${YANDEX_METRIKA_ID}, "init", {
  clickmap: true,
  trackLinks: true,
  accurateTrackBounce: true,
  webvisor: true
});
          `,
        }}
      />
      <noscript>
        <div>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={`https://mc.yandex.ru/watch/${YANDEX_METRIKA_ID}`}
            style={{ position: "absolute", left: "-9999px" }}
            alt=""
          />
        </div>
      </noscript>
    </>
  );
}
