'use client';

import Script from 'next/script';

const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;

/**
 * Google Analytics 4 integration component.
 *
 * Only renders when NEXT_PUBLIC_GA_MEASUREMENT_ID is set.
 * Uses Next.js Script component for optimal loading strategy.
 *
 * @see https://developers.google.com/analytics/devguides/collection/ga4
 */
export function GoogleAnalytics() {
  // Don't render if no measurement ID is configured
  if (!GA_MEASUREMENT_ID) {
    return null;
  }

  return (
    <>
      {/* Google tag (gtag.js) */}
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${GA_MEASUREMENT_ID}', {
            page_path: window.location.pathname,
          });
        `}
      </Script>
    </>
  );
}

// Type for gtag function
type GtagFn = {
  (command: 'config', targetId: string, config?: object): void;
  (command: 'event', eventName: string, eventParams?: object): void;
  (command: 'js', date: Date): void;
};

/**
 * Track custom events in Google Analytics.
 * Use this function to track specific user interactions.
 *
 * @example
 * trackEvent('button_click', { button_name: 'subscribe' });
 */
export function trackEvent(
  eventName: string,
  eventParams?: Record<string, string | number | boolean>
) {
  if (typeof window !== 'undefined' && 'gtag' in window) {
    (window as unknown as { gtag: GtagFn }).gtag('event', eventName, eventParams);
  }
}
