"use client";

import { useEffect, useSyncExternalStore } from "react";
import { GoogleAnalytics } from "@next/third-parties/google";
import { usePathname } from "next/navigation";
import { getConsentCookie } from "@/lib/cookie-consent";
import { isMarketingPath } from "@/lib/marketing-pages";
import { captureUtmParams } from "@/lib/utm";

// Subscribe to analytics-consent changes (dispatched by the cookie banner).
function subscribe(callback: () => void) {
  window.addEventListener("cookie-consent-changed", callback);
  return () => window.removeEventListener("cookie-consent-changed", callback);
}
const getAnalyticsConsent = () => getConsentCookie()?.analytics ?? false;
const getServerAnalyticsConsent = () => false;

/**
 * Loads Google Analytics only when ALL of these hold:
 *  - a GA measurement ID is configured,
 *  - the user consented to analytics cookies, and
 *  - the current page is a marketing/funnel page (never a clinical page).
 * This enforces the HIPAA rule: no analytics on any screening/results/report page.
 */
export default function AnalyticsGate() {
  const gaId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
  const pathname = usePathname();
  const analyticsAllowed = useSyncExternalStore(
    subscribe,
    getAnalyticsConsent,
    getServerAnalyticsConsent
  );

  // Persist campaign (UTM) params for first-touch attribution, but only once
  // the visitor has consented to analytics — same policy that gates GA itself.
  useEffect(() => {
    if (analyticsAllowed) captureUtmParams();
  }, [analyticsAllowed, pathname]);

  if (!gaId || !analyticsAllowed || !isMarketingPath(pathname)) return null;

  return <GoogleAnalytics gaId={gaId} />;
}
