/**
 * Central, fail-safe analytics helper (GA4).
 * Never throws — if gtag has not loaded yet, events are queued on dataLayer
 * and picked up once the GA4 script initialises.
 */

export const GA_MEASUREMENT_ID = "G-2BFVKCT4BL";

export type AnalyticsParams = Record<string, unknown>;

type DataLayerWindow = Window & {
  dataLayer?: unknown[];
  gtag?: (...args: unknown[]) => void;
};

function getWindow(): DataLayerWindow | null {
  return typeof window === "undefined" ? null : (window as DataLayerWindow);
}

/** Current path, safe in SSR/tests. */
export function currentPath(): string {
  const w = getWindow();
  return w?.location?.pathname ?? "";
}

/** "en" for English routes, otherwise "sv". */
export function currentLanguage(): string {
  const path = currentPath();
  if (path === "/de" || path.startsWith("/de/")) return "de";
  if (path === "/en" || path.startsWith("/en/")) return "en";
  if (typeof document !== "undefined" && document.documentElement?.lang) {
    return document.documentElement.lang.toLowerCase().startsWith("en") ? "en" : "sv";
  }
  return "sv";
}

/** Best-effort service area derived from the path. */
export function currentServiceArea(path = currentPath()): string | undefined {
  const p = path.toLowerCase();
  if (/hologram|holobox|holospin|holonet|invisible-screen|magic-mirror/.test(p)) return "hologram";
  if (/(^|\/)vr|vr-|virtual-reality/.test(p)) return "vr";
  if (/(^|\/)ai|ai-/.test(p)) return "ai";
  return undefined;
}

/** Low-level, never-throwing gtag call. Queues on dataLayer when gtag is absent. */
export function safeGtag(...args: unknown[]): void {
  try {
    const w = getWindow();
    if (!w) return;
    if (typeof w.gtag === "function") {
      w.gtag(...args);
      return;
    }
    w.dataLayer = w.dataLayer || [];
    w.dataLayer.push(args);
  } catch {
    /* analytics must never break the app */
  }
}

/** Track a GA4 event with default context params. */
export function trackEvent(eventName: string, params: AnalyticsParams = {}): void {
  const path = currentPath();
  const serviceArea = (params.service_area as string | undefined) ?? currentServiceArea(path);
  const payload: AnalyticsParams = {
    page_path: path,
    language: currentLanguage(),
    ...(serviceArea ? { service_area: serviceArea } : {}),
    ...params,
  };
  safeGtag("event", eventName, payload);
}

/** SPA page view on route change. */
export function trackPageView(path: string = currentPath()): void {
  safeGtag("event", "page_view", {
    page_path: path,
    page_location: getWindow()?.location?.href,
    page_title: typeof document !== "undefined" ? document.title : undefined,
    language: currentLanguage(),
    ...(currentServiceArea(path) ? { service_area: currentServiceArea(path) } : {}),
  });
}

export const trackFormStart = (formName: string, params: AnalyticsParams = {}) =>
  trackEvent("form_start", { form_name: formName, ...params });

/** Only call after the contact-form function responded without error. */
export const trackGenerateLead = (params: AnalyticsParams = {}) =>
  trackEvent("generate_lead", params);

export const trackFormError = (
  formName: string,
  errorType: "validation" | "server",
  message?: string,
) => trackEvent("form_error", { form_name: formName, error_type: errorType, error_message: message });

export const trackBookMeetingClick = (params: AnalyticsParams = {}) =>
  trackEvent("book_meeting_click", params);

export const trackEmailClick = (email?: string) =>
  trackEvent("email_click", { email_address: email });

export const trackPhoneClick = (phone?: string) =>
  trackEvent("phone_click", { phone_number: phone });

export const trackDownloadGuide = (fileUrl?: string) =>
  trackEvent("download_guide", { file_url: fileUrl });

export const trackCaseView = (caseSlug?: string, params: AnalyticsParams = {}) =>
  trackEvent("case_view", { case_slug: caseSlug, ...params });

export const trackCaseCtaClick = (caseSlug?: string, params: AnalyticsParams = {}) =>
  trackEvent("case_cta_click", { case_slug: caseSlug, ...params });

/** Classify an outbound/anchor href into an event, or null when untracked. */
export function classifyLinkHref(href: string): null | { event: string; params: AnalyticsParams } {
  if (!href) return null;
  const lower = href.toLowerCase();
  if (lower.includes("calendly.com")) return { event: "book_meeting_click", params: { link_url: href } };
  if (lower.startsWith("mailto:")) return { event: "email_click", params: { email_address: href.slice(7) } };
  if (lower.startsWith("tel:")) return { event: "phone_click", params: { phone_number: href.slice(4) } };
  if (lower.endsWith(".pdf") || lower.includes("/guide") || lower.includes("guide.pdf"))
    return { event: "download_guide", params: { file_url: href } };
  return null;
}

/** Global delegated click tracking for calendly / mailto / tel / guide links. */
export function trackLinkClickFromEvent(event: MouseEvent): void {
  try {
    const target = event.target as HTMLElement | null;
    const anchor = target?.closest?.("a[href]") as HTMLAnchorElement | null;
    if (!anchor) return;
    const match = classifyLinkHref(anchor.getAttribute("href") || "");
    if (!match) return;
    trackEvent(match.event, match.params);
  } catch {
    /* never break navigation */
  }
}
