"use client";

import { useEffect } from "react";

/** Injects gtag.js when the central admin has saved a GA4 measurement ID —
    this is what feeds data into the property the admin monitors from
    Central → Accounts → Google Analytics. */
export default function GaScript() {
  useEffect(() => {
    let cancelled = false;
    fetch("/api/public/analytics-tag")
      .then((r) => r.json())
      .then(({ measurementId }: { measurementId: string | null }) => {
        if (cancelled || !measurementId) return;
        const w = window as unknown as { dataLayer?: unknown[]; gtag?: (...args: unknown[]) => void };
        w.dataLayer = w.dataLayer || [];
        w.gtag = function gtag(...args: unknown[]) {
          w.dataLayer!.push(args);
        };
        w.gtag("js", new Date());
        w.gtag("config", measurementId, { anonymize_ip: true });
        const script = document.createElement("script");
        script.async = true;
        script.src = `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`;
        document.head.appendChild(script);
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, []);
  return null;
}
