import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:hello_wallpaper/applovin_max/applovin_manage.dart';
import 'package:hello_wallpaper/common/components/easy_loading.dart';
import 'package:hello_wallpaper/common/storage/hive_storage.dart';
import 'package:hello_wallpaper/firebase_options.dart';
import 'package:hello_wallpaper/res/themes/app_themes.dart';
import 'package:hello_wallpaper/res/values/strings.dart';
import 'package:hello_wallpaper/routes/app_pages.dart';

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

  // 竖屏
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  // 初始化Firebase
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  // 非异步错误
  FlutterError.onError = (errorDetails) {
    FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
  };
  // 异步错误
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: false);
    return true;
  };

  // 初始化广告sdk
  await ApplovinManage().initApplovin();

  // 初始化Hive
  await initHive();

  runApp(const MyApp());

  // EasyLoading配置
  configLoading();

  // 沉浸式状态栏
  if(Platform.isAndroid) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.black,
      systemNavigationBarIconBrightness: Brightness.light,
    ));
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final easyLoading = EasyLoading.init();
    return ScreenUtilInit(
      // 设计稿中设备的尺寸(单位随意,建议dp,但在使用过程中必须保持一致)
      designSize: const Size(375, 812),
      // 是否根据宽度/高度中的最小值适配文字
      minTextAdapt: true,
      // 支持分屏尺寸
      splitScreenMode: true,
      builder: (context, child) {
        return GetMaterialApp(
          title: appName,
          debugShowCheckedModeBanner: false,
          theme: darkTheme,
          darkTheme: darkTheme,
          themeMode: ThemeMode.dark,
          getPages: AppPages.routes,
          initialRoute: AppPages.splashScreen,
          builder: (context, widget) {
            widget = easyLoading(context, widget);
            return MediaQuery(
              // 设置文字大小不随系统设置改变
              data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling),
              child: widget,
            );
          },
        );
      },
    );
  }
}
