let crashlytics = null;

try {
  crashlytics = require('@react-native-firebase/crashlytics').default;
  // Test if native module is available
  crashlytics();
} catch (_) {
  crashlytics = null;
}

const isAvailable = !!crashlytics;

export function initCrashlytics() {
  if (!isAvailable) {
    console.log('Crashlytics: native module not available (Expo Go). Skipping.');
    return;
  }
  try {
    crashlytics().setCrashlyticsCollectionEnabled(true);

    const originalHandler = ErrorUtils.getGlobalHandler();
    ErrorUtils.setGlobalHandler((error, isFatal) => {
      crashlytics().recordError(error);
      if (isFatal) crashlytics().log(`Fatal: ${error.message}`);
      if (originalHandler) originalHandler(error, isFatal);
    });

    console.log('Crashlytics initialized');
  } catch (e) {
    console.warn('Crashlytics init failed:', e.message);
  }
}

export function setUser(userId, email) {
  if (!isAvailable) return;
  try {
    if (userId) crashlytics().setUserId(userId);
    if (email) crashlytics().setAttribute('email', email);
  } catch (_) {}
}

export function log(message) {
  if (!isAvailable) return;
  try { crashlytics().log(message); } catch (_) {}
}

export function recordError(error, context) {
  if (!isAvailable) return;
  try {
    if (context) crashlytics().log(context);
    crashlytics().recordError(error instanceof Error ? error : new Error(String(error)));
  } catch (_) {}
}

export function testCrash() {
  if (!isAvailable) {
    console.warn('Crashlytics not available in Expo Go');
    return;
  }
  crashlytics().crash();
}
