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/services.dart';

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

import 'package:get/get.dart';
// import 'package:flutter_stripe/flutter_stripe.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/widgets/kr_local_image.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';
import 'app/services/kr_site_config_service.dart';
import 'app/services/global_overlay_service.dart';
import 'app/utils/kr_log_util.dart';

import 'package:kaer_with_panels/app/routes/transitions/slide_transparent_transition.dart';
import 'package:kaer_with_panels/app/routes/transitions/transition_config.dart';

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

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

  // 防止首帧渲染过早（重点）
  WidgetsBinding.instance.deferFirstFrame();

  // ✅ 等待 Flutter 确保窗口尺寸准备完毕（关键修复）
  await Future.delayed(const Duration(milliseconds: 100));

  if (Platform.isAndroid || Platform.isIOS) {
    await SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
    );
  }

  // 初始化日志系统
  KRLogUtil.kr_init();

  // Stripe.publishableKey = 'pk_live_51SbuYxAawOMH8rEEkz6f4mnxAUjGC72eQ6qdm5tT6whC4hULkxxdbiPsB4gSCIMnNIGCsIgeASTXBakUcbOuUwQO00jSWjuufx';
  // Stripe.merchantIdentifier = 'merchant.com.taw.hifastvpn';
  // if (Platform.isIOS) {
  //   await Stripe.instance.applySettings();
  // }
  // 初始化 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) {
   
  // }

  // 初始化全局 Overlay 服务
  Get.put(GlobalOverlayService());

  runApp(_myApp(translations, initialLocale));
  WidgetsBinding.instance.allowFirstFrame();
}

Widget _myApp(GetxTranslations translations, Locale initialLocale) {
  return GetMaterialApp(
    navigatorKey: navigatorKey, // 使用全局导航键
    title: "Hi快VPN",
    initialRoute: Routes.KR_SPLASH,
    getPages: AppPages.routes,
    builder: (context, child) {
      /// 屏幕适配 - 统一使用手机端设计尺寸
      ScreenUtil.init(
        context,
        designSize: const Size(375, 812),
        minTextAdapt: true,
      );

      // child = FlutterEasyLoading(child: child);  // 已替换为自定义组件
      
      // 添加生命周期监听
      Widget wrappedChild = Listener(
        onPointerDown: (_) async {
        },
        child: child,
      );

      // 如果是桌面平台，添加顶部安全区域
      if (Platform.isMacOS || Platform.isWindows) {
        wrappedChild = MediaQuery(
          data: MediaQuery.of(context).copyWith(
            padding: MediaQuery.of(context).padding.copyWith(
              top: 24.w, // 桌面端顶部安全区域，避开窗口控件
            ),
          ),
          child: wrappedChild,
        );
      }

      // 使用 Stack 布局来设置背景
      return ColoredBox(
        color: Colors.black, // 超出宽度的区域显示黑色背景
        child: Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 450), // 限制最大宽度
            child: Stack(
              fit: StackFit.expand,
              children: [
                // 背景层：使用您的自定义组件
                const KrLocalImage(
                  imageName: 'global-bg',
                  imageType: ImageType.jpg,
                  fit: BoxFit.cover, // 确保背景覆盖整个屏幕
                ),
                // 内容层
                wrappedChild,
                Overlay(
                  initialEntries: [
                    OverlayEntry(builder: (_) => const SizedBox.shrink()), // 初始化空 Overlay
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    },
    theme: KRThemeService().kr_lightTheme(),
    darkTheme: KRThemeService().kr_darkTheme(),
    themeMode: KRThemeService().kr_Theme,
    translations: translations,
    locale: initialLocale,
    fallbackLocale: const Locale('zh', 'CN'),
    debugShowCheckedModeBanner: false,
    transitionDuration: TransitionConfig.defaultDuration, // 设置动画持续时间
    customTransition: TransitionConfig.createDefaultTransition(),
    routingCallback: (routing) {
      if (routing == null || routing.current == null) return;
      
      final String current = routing.current!;
      print('🔥 routing.current: $current');
      
      // ✅ 同步路由状态到服务，用于内部 UI 响应（如隐藏/显示文字）
      GlobalOverlayService.instance.updateCurrentRoute(current);

      // ✅ 显式列表，用于容错匹配
      const showButtonRoutes = [
        Routes.MR_LOGIN,
        Routes.HI_MENU,
        Routes.KR_HOME,
        Routes.HI_USER_INFO,
        Routes.KR_ORDER_STATUS,
      ];

      // 检查是否是购买页（使用多种匹配方式确保成功）
      bool isPurchasePage = current == Routes.KR_PURCHASE_MEMBERSHIP || 
                            current.contains(Routes.KR_PURCHASE_MEMBERSHIP) ||
                            Routes.KR_PURCHASE_MEMBERSHIP.contains(current);

      if (isPurchasePage) {
        // ✅ 购买页：必须可见但透明，解决返回时的遮挡问题
        GlobalOverlayService.instance.updateSubscriptionButtonColor(Colors.transparent);
        GlobalOverlayService.instance.safeShowSubscriptionButton();
      } else if (showButtonRoutes.any((r) => current == r || current.contains(r) || r.contains(current))) {
        // ✅ 其他白名单页面：可见并恢复默认主色
        GlobalOverlayService.instance.updateSubscriptionButtonColor(null);
        GlobalOverlayService.instance.safeShowSubscriptionButton();
      } else {
        // ✅ 默认：隐藏
        GlobalOverlayService.instance.hideSubscriptionButton();
      }
    },
  );
}
