/**
 * Google Consent Mode v2 — defaults set to "denied" before any tag loads.
 * After the user makes a choice, CookieBanner calls gtag('consent','update', ...).
 *
 * Next.js 16 / React 19'da `next/script` inline scripts ile sorunlu olduğu için
 * doğrudan <script dangerouslySetInnerHTML> kullanıyoruz. Script senkron olarak
 * HTML parse edildiği anda çalışır — gtag('consent','default') hiçbir analytics
 * scripti yüklenmeden önce kaydedilir.
 */
export function ConsentInit({ gtmId }: { gtmId?: string | null }) {
  const defaultConsent = `
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    window.gtag = gtag;
    gtag('consent', 'default', {
      ad_storage: 'denied',
      ad_user_data: 'denied',
      ad_personalization: 'denied',
      analytics_storage: 'denied',
      functionality_storage: 'granted',
      personalization_storage: 'denied',
      security_storage: 'granted',
      wait_for_update: 500,
    });
  `;

  const gtmSnippet = gtmId
    ? `
      (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});
      var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
      j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
      })(window,document,'script','dataLayer','${gtmId}');
    `
    : null;

  return (
    <>
      <script dangerouslySetInnerHTML={{ __html: defaultConsent }} />
      {gtmSnippet && (
        <>
          <script dangerouslySetInnerHTML={{ __html: gtmSnippet }} />
          <noscript>
            <iframe
              src={`https://www.googletagmanager.com/ns.html?id=${gtmId}`}
              height="0"
              width="0"
              style={{ display: "none", visibility: "hidden" }}
            />
          </noscript>
        </>
      )}
    </>
  );
}
