// Wait for Firebase Auth to restore persisted session (critical for Android OIDC)
        await initializeFirebaseAuth();




/**
 * Initialize Firebase Auth and wait for persisted session to be restored
 * This is critical for Android where OIDC session restoration is asynchronous
 * Returns the persisted user (if any) or null
 */
const initializeFirebaseAuth = async (): Promise<FirebaseAuthTypes.User | null> => {
  return new Promise((resolve) => {
    const auth = getFirebaseAuth();

    // onAuthStateChanged fires immediately with persisted state (if any)
    // This is how React Native Firebase restores sessions on app restart
    const unsubscribe = auth.onAuthStateChanged(async (user) => {
      unsubscribe(); // Only need the first event for initialization

      if (user) {
        try {
          // Force token refresh to validate session is still active
          // This is critical for Android where OIDC tokens may have expired
          await user.getIdToken(true); // true = force refresh
          resolve(user);
        } catch (error) {
          // Token refresh failed - session expired or Token Service API not enabled
          await crashlyticsService.recordError(error, {
            action: 'TOKEN_REFRESH_FAILED_ON_INIT',
            metadata: { uid: user.uid },
          });

          // Sign out the stale user to prevent API failures
          await signOut(auth);

          resolve(null);
        }
      } else {
        resolve(null);
      }
    });

    // Fallback timeout in case onAuthStateChanged never fires (shouldn't happen)
    setTimeout(() => {
      unsubscribe();
      crashlyticsService.log('Firebase auth initialization timeout - proceeding without user');
      resolve(null);
    }, 5000);
  });
};