let analytics = null;

try {
  analytics = require('@react-native-firebase/analytics').default;
  analytics();
} catch (_) {
  analytics = null;
}

const isAvailable = !!analytics;

/**
 * Log a screen view.
 */
export function logScreenView(screenName) {
  if (!isAvailable) return;
  try {
    analytics().logScreenView({ screen_name: screenName, screen_class: screenName });
  } catch (_) {}
}

/**
 * Log a custom event.
 */
export function logEvent(name, params = {}) {
  if (!isAvailable) return;
  try {
    analytics().logEvent(name, params);
  } catch (_) {}
}

/**
 * Set user ID for analytics.
 */
export function setAnalyticsUser(userId) {
  if (!isAvailable) return;
  try {
    analytics().setUserId(userId);
  } catch (_) {}
}

/**
 * Set user property.
 */
export function setUserProperty(name, value) {
  if (!isAvailable) return;
  try {
    analytics().setUserProperty(name, value);
  } catch (_) {}
}

// ============================
// Pre-defined event helpers
// ============================

export function trackSignUp(method) {
  logEvent('sign_up', { method });
}

export function trackLogin(method) {
  logEvent('login', { method });
}

export function trackIdentityCreated(title, source) {
  logEvent('identity_created', { title, source });
}

export function trackHabitCompleted(habitTitle) {
  logEvent('habit_completed', { habit: habitTitle });
}

export function trackDayCompleted(dayNumber, identityCheck, mood) {
  logEvent('day_completed', { day: dayNumber, identity_check: identityCheck, mood });
}

export function trackGamePlayed(gameType, score) {
  logEvent('game_played', { game_type: gameType, score });
}

export function trackJournalSaved(dayNumber) {
  logEvent('journal_saved', { day: dayNumber });
}

export function trackJourneyCompleted(totalScore, daysLogged) {
  logEvent('journey_completed', { total_score: totalScore, days_logged: daysLogged });
}

export function trackShare(contentType) {
  logEvent('share', { content_type: contentType });
}

export function trackJourneyReset(reason) {
  logEvent('journey_reset', { reason });
}
