import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/app/routing/app_navigator.dart';
import 'package:mypoint_flutter_app/core/theme/base_color.dart';
import 'package:mypoint_flutter_app/features/splash/splash_screen.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import 'package:mypoint_flutter_app/app/app_initializer.dart';
import 'package:flutter_web_plugins/url_strategy.dart';

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (kIsWeb) {
    setUrlStrategy(PathUrlStrategy());
    await _precacheWebSplashImage();
  }
  // Initialize all app features
  await AppInitializer.initialize();
  // Run the app
  runApp(const MyApp());
  // Setup post-initialization callbacks
  AppInitializer.setupPostInitCallbacks();
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      navigatorKey: AppNavigator.key,
      navigatorObservers: [routeObserver],
      debugShowCheckedModeBanner: false,
      // initialRoute: '/splash',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.brown),
        primaryColor: BaseColor.primary500,
      ),
      locale: const Locale('vi'),
      home: SplashScreen(),
      getPages: RouterPage.pages(),
    );
  }
}

Future<void> _precacheWebSplashImage() async {
  if (!kIsWeb) return;
  try {
    final imageProvider = const AssetImage('assets/images/splash_screen.webp');
    final stream = imageProvider.resolve(ImageConfiguration.empty);
    final completer = Completer<void>();
    late final ImageStreamListener listener;
    listener = ImageStreamListener(
      (info, synchronousCall) {
        stream.removeListener(listener);
        if (!completer.isCompleted) completer.complete();
      },
      onError: (error, stackTrace) {
        stream.removeListener(listener);
        if (!completer.isCompleted) completer.completeError(error, stackTrace);
      },
    );
    stream.addListener(listener);
    await completer.future.timeout(const Duration(seconds: 2), onTimeout: () {
      stream.removeListener(listener);
    });
  } catch (error, stackTrace) {
    debugPrint('Failed to precache splash image: $error');
    debugPrintStack(stackTrace: stackTrace);
  }
}
