"use client";

import { useSyncExternalStore } from "react";
import Script from "next/script";
import { getServerConsentSnapshot, readConsent, subscribeToConsent } from "@/lib/cookieConsent";

// Lädt gtag.js NUR, wenn (a) eine Analytics-ID gesetzt ist UND (b) die
// Kategorie "Statistik" zugestimmt wurde (TTDSG/DSGVO) — vorher (Till,
// 19.10.2026) lud das Skript bereits, sobald nur die ID gesetzt war, ganz
// ohne Einwilligung.
export function GoogleAnalyticsLoader({ gaId }: { gaId: string }) {
  const consent = useSyncExternalStore(subscribeToConsent, readConsent, getServerConsentSnapshot);

  if (!gaId || !consent?.statistics) return null;

  return (
    <>
      <Script src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`} strategy="afterInteractive" />
      <Script id="ga4-init" strategy="afterInteractive">
        {`window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${gaId}');`}
      </Script>
    </>
  );
}
