/**
 * Funnel Event Utilities
 *
 * Core utilities for emitting registration funnel events.
 * Handles session management and referrer tracking.
 *
 * CONSENT-FREE: No localStorage/sessionStorage/cookies used.
 * All state is held in memory and resets on tab close.
 */

import type { FunnelEventPayload } from './types';

// In-memory state for consent-free tracking
let funnelSessionId: string | null = null;
let entryReferrer: string | null = null;

/**
 * Get or create a session ID for the current SPA lifecycle.
 * Held in memory only - resets on tab close (consent-free).
 */
export function getSessionId(): string {
  if (!funnelSessionId) {
    funnelSessionId = `${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
  }
  return funnelSessionId;
}

/**
 * Store entry referrer when user lands on registration page.
 * Only captures once per SPA lifecycle to preserve original attribution.
 */
export function captureEntryReferrer(): void {
  if (entryReferrer === null) {
    entryReferrer = document.referrer || 'direct';
  }
}

/**
 * Get and clear stored entry referrer for signup attribution.
 * Returns undefined if no referrer was captured.
 */
export function getAndClearEntryReferrer(): string | undefined {
  const referrer = entryReferrer;
  if (referrer) {
    entryReferrer = null;
    return referrer;
  }
  return undefined;
}

/**
 * Emit a funnel event to the analytics API.
 * Fails silently - analytics should never break user experience.
 */
export async function emitFunnelEvent(payload: FunnelEventPayload): Promise<void> {
  try {
    await fetch('/api/track/registration-funnel', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
  } catch {
    // Fail silently - analytics shouldn't break user experience
  }
}
