import { Platform } from 'react-native';

type AnalyticsEvent = {
  name: string;
  params?: Record<string, any>;
  timestamp: string;
};

class Analytics {
  private queue: AnalyticsEvent[] = [];
  private userId: string | null = null;
  private sessionId: string;

  constructor() {
    this.sessionId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }

  setUserId(userId: string) {
    this.userId = userId;
  }

  track(eventName: string, params?: Record<string, any>) {
    const event: AnalyticsEvent = {
      name: eventName,
      params: {
        ...params,
        platform: Platform.OS,
        session_id: this.sessionId,
        user_id: this.userId,
      },
      timestamp: new Date().toISOString(),
    };

    this.queue.push(event);

    // In development, log to console
    if (__DEV__) {
      console.log('[Analytics]', event);
    }

    // TODO: In production, batch send to analytics endpoint
    // this.flush();
  }

  screen(screenName: string, params?: Record<string, any>) {
    this.track('screen_view', { screen_name: screenName, ...params });
  }

  getQueue() {
    return [...this.queue];
  }

  clearQueue() {
    this.queue = [];
  }
}

export const analytics = new Analytics();
