/**
 * Google Analytics 4 (GA4) tracking utilities
 * Provides event tracking for conversions, page views, and user interactions.
 */

// Extend window to include gtag
declare global {
  interface Window {
    dataLayer: unknown[];
    gtag: (...args: unknown[]) => void;
  }
}

const GA_MEASUREMENT_ID = import.meta.env.VITE_GA_MEASUREMENT_ID as string | undefined;

/**
 * Initialize Google Analytics by injecting the gtag.js script
 * Called once on app startup
 */
export function initGA(): void {
  if (!GA_MEASUREMENT_ID || typeof window === "undefined") return;

  // Avoid double-initialization
  if (document.querySelector(`script[src*="googletagmanager.com/gtag"]`)) return;

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

  // Initialize dataLayer and gtag
  window.dataLayer = window.dataLayer || [];
  window.gtag = function (...args: unknown[]) {
    window.dataLayer.push(args);
  };
  window.gtag("js", new Date());
  window.gtag("config", GA_MEASUREMENT_ID, {
    send_page_view: false, // We'll send page views manually for SPA
  });
}

/**
 * Disable Google Analytics by removing the script and clearing dataLayer.
 * Called when user revokes analytics consent.
 */
export function disableGA(): void {
  if (typeof window === "undefined") return;

  // Set GA opt-out flag
  if (GA_MEASUREMENT_ID) {
    (window as unknown as Record<string, unknown>)[`ga-disable-${GA_MEASUREMENT_ID}`] = true;
  }

  // Remove the gtag script element
  const script = document.querySelector(`script[src*="googletagmanager.com/gtag"]`);
  if (script) script.remove();

  // Clear dataLayer
  if (window.dataLayer) {
    window.dataLayer.length = 0;
  }
}

/**
 * Track a page view (for SPA navigation)
 */
export function trackPageView(path: string, title?: string): void {
  if (!GA_MEASUREMENT_ID || typeof window === "undefined" || !window.gtag) return;
  window.gtag("event", "page_view", {
    page_path: path,
    page_title: title || document.title,
    page_location: window.location.origin + path,
  });
}

/**
 * Track a custom event
 */
export function trackEvent(
  eventName: string,
  params?: Record<string, string | number | boolean>
): void {
  if (!GA_MEASUREMENT_ID || typeof window === "undefined" || !window.gtag) return;
  window.gtag("event", eventName, params);
}

/**
 * Track contact form submission as a conversion event
 */
export function trackContactFormSubmission(formLocation: string, industry?: string): void {
  trackEvent("generate_lead", {
    event_category: "Contact",
    event_label: formLocation,
    form_location: formLocation,
    industry: industry || "general",
    value: 1,
    currency: "AED",
  });
}

/**
 * Track partner link click
 */
export function trackPartnerClick(partnerName: string, partnerUrl: string): void {
  trackEvent("click", {
    event_category: "Partner",
    event_label: partnerName,
    link_url: partnerUrl,
    outbound: true,
  });
}

/**
 * Track CTA button click
 */
export function trackCTAClick(ctaName: string, ctaLocation: string): void {
  trackEvent("cta_click", {
    event_category: "CTA",
    event_label: ctaName,
    cta_location: ctaLocation,
  });
}

/**
 * Track language switch
 */
export function trackLanguageSwitch(language: string): void {
  trackEvent("language_switch", {
    event_category: "Engagement",
    event_label: language,
  });
}

/**
 * Track phone call click
 */
export function trackPhoneClick(phoneNumber: string): void {
  trackEvent("click_to_call", {
    event_category: "Contact",
    event_label: phoneNumber,
  });
}

/**
 * Track WhatsApp click
 */
export function trackWhatsAppClick(): void {
  trackEvent("whatsapp_click", {
    event_category: "Contact",
    event_label: "WhatsApp",
  });
}

/**
 * Track quote request form submission
 */
export function trackQuoteRequest(source: string, industry?: string): void {
  trackEvent("generate_lead", {
    event_category: "Quote",
    event_label: source,
    form_location: source,
    industry: industry || "general",
    value: 1,
    currency: "AED",
  });
}

/**
 * Capture UTM parameters from URL and store in sessionStorage.
 * Call on app init.
 */
export function captureUTMParams(): Record<string, string> {
  if (typeof window === "undefined") return {};
  const params = new URLSearchParams(window.location.search);
  const utmKeys = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
  const captured: Record<string, string> = {};
  for (const key of utmKeys) {
    const val = params.get(key);
    if (val) captured[key] = val;
  }
  if (Object.keys(captured).length > 0) {
    sessionStorage.setItem("alzar_utm", JSON.stringify(captured));
  }
  return captured;
}

/**
 * Get stored UTM parameters from sessionStorage
 */
export function getStoredUTM(): Record<string, string> {
  if (typeof window === "undefined") return {};
  try {
    return JSON.parse(sessionStorage.getItem("alzar_utm") || "{}");
  } catch {
    return {};
  }
}
