export interface GA4LoadOptions {
  debug?: boolean;
  autoTrackPageViews?: boolean;
  autoTrackScrolls?: boolean;
  autoTrackOutboundLinks?: boolean;
}

export const loadGA4 = async (
  measurementId: string,
  options: GA4LoadOptions = {}
): Promise<void> => {
  const {
    debug = false,
    autoTrackPageViews = true,
    autoTrackScrolls = true,
    autoTrackOutboundLinks = false,
  } = options;

  // Load GA4 script
  await new Promise<void>((resolve) => {
    const script = document.createElement("script");
    script.async = true;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
    script.onload = () => resolve();
    document.head.appendChild(script);
  });

  // Initialize gtag
  window.dataLayer = window.dataLayer || [];
  (window as any).gtag = function (...args: unknown[]) {
    (window as any).dataLayer.push(args);
  };

  // Configure GA4
  (window as any).gtag("config", measurementId, {
    debug_mode: debug,
    send_page_view: autoTrackPageViews,
  });

  // Auto-track scrolls
  if (autoTrackScrolls) {
    const scrollDepth = [25, 50, 75, 100];
    scrollDepth.forEach((threshold) => {
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              (window as any).gtag("event", "scroll", {
                scroll_percentage: threshold,
              });
              observer.unobserve(entry.target);
            }
          });
        },
        { threshold: threshold / 100 }
      );
      observer.observe(document.body);
    });
  }

  // Auto-track outbound links
  if (autoTrackOutboundLinks) {
    document.addEventListener("click", (e) => {
      const target = e.target as HTMLAnchorElement;
      if (target.tagName === "A" && target.href) {
        const currentHost = window.location.hostname;
        const linkHost = new URL(target.href).hostname;
        if (linkHost !== currentHost) {
          (window as any).gtag("event", "click", {
            event_category: "outbound_link",
            event_label: target.href,
            value: 1,
          });
        }
      }
    });
  }
};
