import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'app/app.dart';
import 'app/constants/api_domains.dart';
import 'app/controllers/api_controller.dart';
import 'app/controllers/core_controller.dart';
import 'app/data/sp/ix_sp.dart';
import 'utils/device_manager.dart';
import 'utils/log/log_manager.dart';
import 'utils/log/logger.dart';
import 'utils/ntp_time_service.dart';
import 'config/theme/theme_extensions/theme_extension.dart';

Future<void> main() async {
  runZonedGuarded(
    () async {
      await _initializeApp();
      runApp(const App());
    },
    (error, stackTrace) {
      // TODO统一错误处理
      log('main', 'Error: $error\n$stackTrace');
    },
  );
}

// 将初始化逻辑提取到单独的方法
Future<void> _initializeApp() async {
  try {
    WidgetsFlutterBinding.ensureInitialized();

    // 1. 系统UI配置
    await _configureSystemUI();

    // 2. 初始化日志
    await LogManager().init();

    // 3. 数据存储初始化
    await IXSP.init();

    // 3.1 初始化ApiDomains
    await ApiDomains.instance.init();

    // 4. 获取设备ID
    await DeviceManager.getDeviceId();

    // 5. 注册全局控制器
    _registerControllers();

    // 6. 初始化响应式主题
    ReactiveTheme.init();

    // 7. 初始化NTP时间校准器
    NtpTimeService().initialize();
  } catch (e, stack) {
    log('main', 'Initialization error: $e\n$stack');
    rethrow;
  }
}

void _registerControllers() {
  Bind.lazyPut(() => CoreController());
  Bind.lazyPut(() => ApiController());
}

Future<void> _configureSystemUI() async {
  // UI相关配置集中管理
  // await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  if (Platform.isAndroid) {
    await SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  // 设置系统UI样式，确保系统导航栏完全透明
  // SystemChrome.setSystemUIOverlayStyle(
  //   const SystemUiOverlayStyle(
  //     statusBarColor: Colors.transparent,
  //     systemNavigationBarColor: Colors.transparent,
  //   ),
  // );
}
