import 'package:food_delivery_client/feature/common/presentation/blocs/language_bloc/language_bloc.dart';
import 'package:toastification/toastification.dart';

import 'food_delivery_client.dart';

void main() {
  runZonedGuarded(
    () async{
      WidgetsFlutterBinding.ensureInitialized();
      FlutterError.onError = (details) {
        FlutterError.presentError(details);
        log("Flutter.onError $details");
      };
      Bloc.observer = AppBlocObserver();
      await configureDependencies();
      runApp(
        BlocProvider(create: (context) => sl<LanguageBloc>(), child: MyApp()),
      );
    },
    (error, stack) {
      log("RunZoneGuard Error $error");
    },
  );
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LanguageBloc, LanguageState>(
      bloc: context.read<LanguageBloc>()..add(LanguageEvent.started()),
      builder: (context, state) {
        return ToastificationWrapper(
          child: MaterialApp.router(
            title: "Uber Eats",
            debugShowCheckedModeBanner: false,
            theme: AppTheme.lightTheme,
            routerConfig: sl<AppRoutes>().router,
            locale: state.currentLocale,
            supportedLocales: L10n.locales,
            localizationsDelegates: [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            builder: (context, child) => GestureDetector(
              onTap: () {
                FocusManager.instance.primaryFocus?.unfocus();
              },
              child: MediaQuery(
                data: MediaQuery.of(
                  context,
                ).copyWith(textScaler: const TextScaler.linear(1)),
                child: child!,
              ),
            ),
          ),
        );
      },
    );
  }
}
