/**
 * GoogleAnalytics - Google Analytics 4 integration component.
 *
 * Loads the GA4 measurement script and configures it.
 * Renders as a macro — include once in your app layout.
 *
 * Usage:
 *   <GoogleAnalytics />
 *
 * ⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
 */

import { useEffect } from 'react';

const GA_MEASUREMENT_ID = import.meta.env.VITE_GA_MEASUREMENT_ID || '';

declare global {
  interface Window {
    dataLayer: unknown[];
    gtag: (...args: unknown[]) => void;
  }
}

/**
 * Google Analytics 4 script loader and configurator.
 *
 * Loads the gtag.js script and initializes GA4 with the measurement ID
 * from the VITE_GA_MEASUREMENT_ID environment variable.
 */
export function GoogleAnalytics() {
  useEffect(() => {
    if (!GA_MEASUREMENT_ID) {
      console.debug('Google Analytics: No measurement ID configured');
      return;
    }

    // Initialize dataLayer
    window.dataLayer = window.dataLayer || [];
    window.gtag = function gtag(...args: unknown[]) {
      window.dataLayer.push(args);
    };
    window.gtag('js', new Date());
    window.gtag('config', GA_MEASUREMENT_ID, {
{% if google_analytics %}
{% if google_analytics.anonymize_ip %}
      anonymize_ip: true,
{% endif %}
{% if google_analytics.send_page_views %}
      send_page_view: true,
{% else %}
      send_page_view: false,
{% endif %}
{% endif %}
    });

    // Load the script
    const script = document.createElement('script');
    script.src = `https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`;
    script.async = true;
    document.head.appendChild(script);

    return () => {
      document.head.removeChild(script);
    };
  }, []);

  return null;
}
