import 'dart:io';

import 'package:flutter/material.dart';
// import 'package:flutter_easyloading/flutter_easyloading.dart';  // 已替换为自定义组件
import 'package:flutter_screenutil/flutter_screenutil.dart';

// import 'package:flutter_map_tile_caching/flutter_map_tile_caching.dart';

import 'package:get/get.dart';

import 'package:kaer_with_panels/app/themes/kr_theme_service.dart';
import 'package:kaer_with_panels/app/localization/getx_translations.dart';
import 'package:kaer_with_panels/app/localization/kr_language_utils.dart';
import 'package:kaer_with_panels/app/routes/app_pages.dart';

import 'package:kaer_with_panels/app/utils/kr_window_manager.dart';

import 'app/utils/kr_secure_storage.dart';
import 'app/common/app_config.dart';

// 全局导航键
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 Hive
  await KRSecureStorage().kr_initHive();

  // 初始化主题
  await KRThemeService().init();

  // 初始化翻译
  final translations = GetxTranslations();
  await translations.loadAllTranslations();

  // 获取最后保存的语言
  final initialLocale = await KRLanguageUtils.getLastSavedLocale();
 


 
  // 初始化窗口管理器
  if (Platform.isMacOS || Platform.isWindows) {

    await KRWindowManager().kr_initWindowManager();
  }
  
  // 启动域名预检测（异步，不阻塞应用启动）
  // 立即启动域名检测，不延迟
  KRDomain.kr_preCheckDomains();
  // 初始化 FMTC
  // try {
  //   if (Platform.isMacOS) {
  //     final baseDir = await getApplicationSupportDirectory();
  //     await FMTCObjectBoxBackend().initialise(rootDirectory: baseDir.path);
  //   } else {
  //     await FMTCObjectBoxBackend().initialise();
  //   }
  //   // 创建地图存储
  //   await FMTCStore(KRFMTC.kr_storeName).manage.create();
  //   // 初始化地图缓存
  //   await KRFMTC.kr_initMapCache();
  // } catch (error, stackTrace) {
   
  // }


  runApp(_myApp(translations, initialLocale));
}

Widget _myApp(GetxTranslations translations, Locale initialLocale) {
  return GetMaterialApp(
    navigatorKey: navigatorKey, // 使用全局导航键
    title: "BearVPN",
    initialRoute: Routes.KR_SPLASH,
    getPages: AppPages.routes,
    builder: (context, child) {
      if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
        /// 屏幕适配
        ScreenUtil.init(context,
            designSize: const Size(868, 668), minTextAdapt: true);
      } else {
        /// 屏幕适配
        ScreenUtil.init(context,
            designSize: const Size(375, 667), minTextAdapt: true);
      }

      // child = FlutterEasyLoading(child: child);  // 已替换为自定义组件
      
      // 添加生命周期监听
      Widget wrappedChild = Listener(
        onPointerDown: (_) async {
          // 确保地图缓存已初始化
          // try {
          //   final store = FMTCStore(KRFMTC.kr_storeName);
          //   if (!await store.manage.ready) {
          //     await store.manage.create();
          //     await KRFMTC.kr_initMapCache();
          //   }
          // } catch (e) {
          //   print('地图缓存初始化失败: $e');
          // }
        },
        child: child,
      );

      // 如果是 Mac 平台，添加顶部安全区域
      if (Platform.isMacOS) {
        wrappedChild = MediaQuery(
          data: MediaQuery.of(context).copyWith(
            padding: MediaQuery.of(context).padding.copyWith(
              top: 10.w, // Mac 平台顶部安全区域
            ),
          ),
          child: wrappedChild,
        );
      }
      
      return wrappedChild;
    },
    theme: KRThemeService().kr_lightTheme(),
    darkTheme: KRThemeService().kr_darkTheme(),
    themeMode: KRThemeService().kr_Theme,
    translations: translations,
    locale: initialLocale,
    fallbackLocale: const Locale('ru'),
    debugShowCheckedModeBanner: false,
    // defaultTransition: Transition.fade,
  );
}
