import 'dart:async';
import 'dart:ui';

import 'package:atmo_sphere/tools/firebase_options.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'app.dart';

bool isFirebaseInitialized = false;
void main() async {

  runZonedGuarded<Future<void>>(()async{

    WidgetsFlutterBinding.ensureInitialized();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);

    try {
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      ).timeout(const Duration(seconds: 15)); // 设置15秒超时
      print("✅ Firebase 初始化成功。");
      isFirebaseInitialized = true; // 成功后设置标志

    } on TimeoutException {
    } catch (error, stack) {
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: false);
    }

    // Firebase 成功初始化后，配置依赖它的服务
    if (isFirebaseInitialized) {
      //设置全局错误处理器
      FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
      PlatformDispatcher.instance.onError = (error, stack) {
        FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
        return true;
      };
      // 使用我们的安全服务来记录 App Open
      AnalyticsService.instance.logAppOpen();
    }


    final analyticsObserver = SafeFirebaseAnalyticsObserver();
    runApp( ProviderScope(child: AtmoSphereApp(analyticsObserver: analyticsObserver)));

  }, (e,s){});


}

class AnalyticsService {
  // 单例模式
  AnalyticsService._();
  static final instance = AnalyticsService._();

  final _analytics = FirebaseAnalytics.instance;

  void logAppOpen() {
    if (isFirebaseInitialized) {
      _analytics.logAppOpen();
    } else {
      print("[AnalyticsService] Skipped logAppOpen: Firebase not initialized.");
    }
  }


}

class SafeFirebaseAnalyticsObserver extends NavigatorObserver {
  late final FirebaseAnalyticsObserver _observer;

  SafeFirebaseAnalyticsObserver() {
    if (isFirebaseInitialized) {
      _observer = FirebaseAnalyticsObserver(analytics: AnalyticsService.instance._analytics);
    }
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (isFirebaseInitialized) {
      _observer.didPush(route, previousRoute);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (isFirebaseInitialized) {
      _observer.didPop(route, previousRoute);
    }
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    if (isFirebaseInitialized) {
      _observer.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    }
  }
}