import 'dart:developer';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_qline/view_models/screen_config_view_model.dart';
import 'package:provider/provider.dart';
import 'package:hmg_qline/config/dependency_injection.dart';
import 'package:hmg_qline/config/routes.dart';
import 'package:hmg_qline/constants/app_constants.dart';
import 'package:hmg_qline/view_models/queuing_view_model.dart';
import 'package:hmg_qline/views/view_helpers/size_config.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
import 'package:hmg_qline/services/crash_handler_service.dart';

void main() {
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();
    try {
      await AppDependencies.addDependencies();
      // initialize crash handler after DI setup
      getIt.get<CrashHandlerService>().setupGlobalErrorHandlers();
      await WakelockPlus.enable();
    } catch (e) {
      log('Initialization error: $e');
    }

    runApp(const MyApp());
  }, (error, stack) async {
    try {
      await getIt.get<CrashHandlerService>().handleCrash(error: error, stackTrace: stack, context: 'runZonedGuarded');
    } catch (e) {
      log('Error in runZonedGuarded handler: $e');
    }
  });
}

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

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return OrientationBuilder(builder: (context, orientation) {
          SizeConfig().init(constraints, orientation);

          // Comprehensive Orientation Debug Logging
          log("=== ORIENTATION DEBUG (main.dart) ===");
          log("OrientationBuilder orientation: $orientation");
          log("MediaQuery orientation: ${MediaQuery.of(context).orientation}");
          log("Screen size: ${MediaQuery.of(context).size}");
          log("Constraints: maxWidth=${constraints.maxWidth}, maxHeight=${constraints.maxHeight}");
          log("Is Portrait (OrientationBuilder): ${orientation == Orientation.portrait}");
          log("Is Landscape (OrientationBuilder): ${orientation == Orientation.landscape}");
          log("=====================================");

          SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
          SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

          return MultiProvider(
            providers: [
              ChangeNotifierProvider<ScreenConfigViewModel>(
                create: (context) => getIt.get<ScreenConfigViewModel>(),
                lazy: false,
              ),
              ChangeNotifierProvider<QueuingViewModel>(
                create: (context) => getIt.get<QueuingViewModel>(),
                lazy: false,
              ),
            ],
            child: MaterialApp(
              showSemanticsDebugger: false,
              title: AppStrings.appName,
              theme: ThemeData(
                fontFamily: AppStrings.fontNamePoppins,
                colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.grey).copyWith(
                  surface: const Color.fromRGBO(255, 255, 255, 1),
                ),
              ),
              initialRoute: AppRoutes.initialRoute,
              routes: AppRoutes.routes,
              debugShowCheckedModeBanner: false,
            ),
          );
        });
      },
    );
  }
}

// vTJJHSbhMyeq04KfmM3KAg
