/**
 * GA4-Tracking für WEBklar (Marketing-Site).
 * Aktiv nur wenn VITE_GA4_MEASUREMENT_ID gesetzt ist.
 */

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

const MEASUREMENT_ID = import.meta.env.VITE_GA4_MEASUREMENT_ID?.trim();

let initialized = false;

function isEnabled(): boolean {
  return Boolean(MEASUREMENT_ID) && typeof window !== "undefined";
}

function gtag(...args: unknown[]): void {
  if (!isEnabled() || typeof window.gtag !== "function") return;
  window.gtag(...args);
}

/** Lädt gtag.js einmal; Consent standardmäßig verweigert (EU), bis CMP anbindet. */
export function initAnalytics(): void {
  if (!isEnabled() || initialized) return;
  initialized = true;

  window.dataLayer = window.dataLayer ?? [];
  window.gtag = function gtagShim(...args: unknown[]) {
    window.dataLayer?.push(args);
  };

  gtag("consent", "default", {
    analytics_storage: "denied",
    ad_storage: "denied",
    wait_for_update: 500,
  });

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

  gtag("js", new Date());
  gtag("config", MEASUREMENT_ID!, {
    send_page_view: false,
    anonymize_ip: true,
  });
}

/** Nach Cookie-Einwilligung aufrufen (z. B. CMP). */
export function grantAnalyticsConsent(): void {
  gtag("consent", "update", {
    analytics_storage: "granted",
    ad_storage: "denied",
  });
}

export function trackPageView(pagePath: string, pageTitle?: string): void {
  if (!isEnabled()) return;
  gtag("event", "page_view", {
    page_path: pagePath,
    page_title: pageTitle ?? document.title,
    page_location: window.location.href,
  });
}

export function trackEvent(
  eventName: string,
  params?: Record<string, string | number | boolean>
): void {
  if (!isEnabled()) return;
  gtag("event", eventName, params ?? {});
}

export function trackCtaClick(buttonText: string, location: string): void {
  trackEvent("cta_clicked", {
    button_text: buttonText,
    location,
  });
}

export function trackFormSubmitted(formType: string): void {
  trackEvent("form_submitted", { form_type: formType });
}
