"use client";

import Script from "next/script";

interface YandexMetrikaProps {
  counterId?: string;
}

/**
 * Yandex Metrika Integration Component
 * 
 * Loads Yandex Metrika tracking script dynamically based on counter ID
 * received from the funnel configuration.
 * 
 * Initializes with: clickmap, trackLinks, accurateTrackBounce, webvisor.
 * Page views are tracked by PageViewTracker component on route changes.
 * 
 * @param counterId - Yandex Metrika Counter ID (e.g., "95799066")
 */
export function YandexMetrika({ counterId }: YandexMetrikaProps) {
  if (!counterId) {
    return null;
  }

  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__ = ${counterId};

ym(${counterId}, "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/${counterId}`}
            style={{ position: "absolute", left: "-9999px" }}
            alt=""
          />
        </div>
      </noscript>
    </>
  );
}
