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

import 'app/app.dart';
import 'app/core/utils/notification_service.dart';

DBHelper dbHelper = DBHelper();

Future<void> _initAppInitials() async {
  // HttpOverrides.global = MyHttpOverrides();
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  await ScreenUtil.ensureScreenSize();

  await initLoginStatus();
}

// Firebase initials is separated, app needs to be initialized
// regardless Firebase
Future<void> _initFBInitials() async {
  try {
    await initFCMFunctions();
  } catch (e) {
    debugPrint('FCM error: $e');
  }
}

Future<void> main() async {
  await _initAppInitials();
  await _initFBInitials();

  SharedPreferences prefs = await SharedPreferences.getInstance();
  final bool isSeen = prefs.getBool(Constants.IS_SPLASH_SEEN) ?? false;
  final String locale = await getLocale();

  runApp(ElektronikaShopApp(
    lang: locale,
    isSplashSeen: isSeen,
  ));
}

class ElektronikaShopApp extends StatelessWidget {
  final String lang;
  final bool isSplashSeen;

  ElektronikaShopApp({
    required this.lang,
    required this.isSplashSeen,
  });

  @override
  Widget build(BuildContext context) {
    debugPrint('LANG =>>> $lang');
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return ScreenUtilInit(
          designSize: Size(constraints.maxWidth, constraints.maxHeight),
          builder: (_, child) => GetMaterialApp(
            initialRoute: isSplashSeen ? AppRoutes.DASHBOARD : AppRoutes.SPLASH,
            getPages: AppPages.list,
            debugShowCheckedModeBanner: false,
            locale: Locale(lang, lang.toUpperCase()),
            fallbackLocale: LocalizationService.fallbackLocale,
            translations: LocalizationService(),
            theme: AppTheme.light,
            darkTheme: AppTheme.dark,
            themeMode: ThemeMode.light, // ThemeMode.system
          ),
        );
      },
    );
  }
}

// cd ios
//arch -x86_64 pod install 
//arch -x86_64 pod install --repo-update