/**
 * analytics.ts — thin wrapper around Umami's window.umami.track().
 *
 * Why a wrapper?
 * - window.umami is undefined during SSR and before the script loads
 * - gives us a typed, central place to see all tracked events
 * - safe no-op in development if the script isn't loaded
 *
 * Usage:
 *   import { track } from "@/lib/analytics";
 *   track("log-created", { logType: "feed" });
 *
 * Umami dashboard → Events tab shows each event name + property breakdown.
 */

// Extend Window with Umami's runtime API
declare global {
  interface Window {
    umami?: {
      track: (event: string, data?: Record<string, string | number | boolean>) => void;
    };
  }
}

export type EventData = Record<string, string | number | boolean>;

/**
 * Fire a custom Umami analytics event.
 * Safe to call anywhere — no-ops if Umami hasn't loaded yet (SSR, dev, ad-blockers).
 */
export function track(event: string, data?: EventData): void {
  try {
    window.umami?.track(event, data);
  } catch {
    // Swallow — analytics must never break the app
  }
}

// ─── Typed event helpers ──────────────────────────────────────────────────────
// These keep event names consistent across the codebase and show up as
// named events in the Umami dashboard.

/** Feed, diaper, or sleep log saved */
export const trackLogCreated   = (logType: "feed" | "sleep" | "diaper") =>
  track("log-created", { logType });

/** Garment added to wardrobe */
export const trackGarmentAdded = () => track("garment-added");

/** Memory photo uploaded */
export const trackMemoryAdded  = () => track("memory-added");

/** Growth measurement recorded */
export const trackGrowthLogged = () => track("growth-logged");

/** PWA installed from browser prompt */
export const trackPwaInstalled = () => track("pwa-installed");

/** AI chat message sent */
export const trackAiChat       = () => track("ai-chat-sent");

/** Vaccine marked as given */
export const trackVaccineGiven = () => track("vaccine-given");
