// Analytics tracking for waitlist page
// Tracks conversion events for Google Analytics / other analytics platforms

export interface AnalyticsEvent {
  category: string;
  action: string;
  label?: string;
  value?: number;
}

// Global analytics tracker
let gtag: (() => void) | null = null;

function initAnalytics() {
  // Check if gtag is already defined (prevents double initialization)
  if (typeof window !== 'undefined' && (window as any).gtag) {
    gtag = (window as any).gtag;
    return;
  }

  // Initialize gtag if Google Analytics is configured
  if (typeof window !== 'undefined' && (window as any).gtag) {
    gtag = (window as any).gtag;
  }
}

function trackEvent(event: AnalyticsEvent) {
  if (!gtag) {
    console.debug('[Analytics] No gtag initialized, event ignored:', event);
    return;
  }

  if (event.value && typeof event.value === 'number') {
    gtag('event', event.action, {
      event_category: event.category,
      event_label: event.label,
      value: event.value,
    });
  } else {
    gtag('event', event.action, {
      event_category: event.category,
      event_label: event.label,
    });
  }
}

// Waitlist-specific events
export const waitlistEvents = {
  page_view: () => trackEvent({
    category: 'engagement',
    action: 'waitlist_page_view',
  }),

  hero_scroll: () => trackEvent({
    category: 'engagement',
    action: 'hero_section_scrolled',
  }),

  form_start: () => trackEvent({
    category: 'conversion',
    action: 'form_started',
  }),

  email_entered: (email: string) => trackEvent({
    category: 'engagement',
    action: 'email_entered',
    label: email,
  }),

  submit_attempt: () => trackEvent({
    category: 'conversion',
    action: 'form_submit_attempted',
  }),

  submit_success: () => trackEvent({
    category: 'conversion',
    action: 'waitlist_signup',
  }),

  submit_error: () => trackEvent({
    category: 'error',
    action: 'form_submit_error',
  }),

  feature_view: (feature: string) => trackEvent({
    category: 'engagement',
    action: `feature_${feature}_viewed`,
    label: feature,
  }),

  testimonial_view: (quote: string) => trackEvent({
    category: 'engagement',
    action: 'testimonial_viewed',
    label: quote.substring(0, 50),
  }),
};

// Fallback for testing without real analytics
export const mockTrack = (event: AnalyticsEvent) => {
  console.log('[Analytics] Mock event:', event);
};

// Export for use in components
export { initAnalytics, trackEvent, waitlistEvents, mockTrack };
