---
/**
 * Analytics Component
 *
 * Supports two analytics providers (configure via environment variables):
 * - Google Analytics 4: Set GOOGLE_ANALYTICS_ID=G-XXXXXXXXXX
 * - Plausible Analytics: Set PLAUSIBLE_DOMAIN=workroot.in
 *
 * If neither is set, no analytics scripts are injected.
 * The component respects Do Not Track (DNT) browser settings.
 */

const gaId = import.meta.env.GOOGLE_ANALYTICS_ID;
const plausibleDomain = import.meta.env.PLAUSIBLE_DOMAIN;

const hasGA4 = gaId && gaId.startsWith('G-');
const hasPlausible = !!plausibleDomain;
---

{hasGA4 && (
  <>
    <!-- Google Analytics 4 -->
    <link rel="preconnect" href="https://www.googletagmanager.com" />
    <link rel="dns-prefetch" href="https://www.google-analytics.com" />
    <script
      async
      src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}
    ></script>
    <script define:vars={{ gaId }}>
      // Respect Do Not Track
      if (navigator.doNotTrack !== '1' && window.doNotTrack !== '1') {
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());
        gtag('config', gaId, {
          // Anonymize IP for GDPR compliance
          anonymize_ip: true,
          // Disable ad personalization signals
          allow_google_signals: false,
          allow_ad_personalization_signals: false,
          // Send page views automatically
          send_page_view: true,
        });
        // Expose gtag globally for event tracking
        window.gtag = gtag;
      }
    </script>
  </>
)}

{hasPlausible && (
  <>
    <!-- Plausible Analytics (privacy-focused) -->
    <link rel="preconnect" href="https://plausible.io" />
    <script
      defer
      data-domain={plausibleDomain}
      src="https://plausible.io/js/script.tagged-events.js"
    ></script>
    <script>
      // Expose plausible event helper globally
      window.plausible = window.plausible || function() {
        (window.plausible.q = window.plausible.q || []).push(arguments);
      };
    </script>
  </>
)}

{!hasGA4 && !hasPlausible && (
  <!-- Analytics not configured. Set GOOGLE_ANALYTICS_ID or PLAUSIBLE_DOMAIN in .env -->
)}
