/// UnionFlow - Application Mobile Révolutionnaire
///
/// Point d'entrée principal avec système d'authentification adaptatif
/// Architecture ultra-sophistiquée avec dashboard morphique basé sur les rôles
library main;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'core/design_system/theme/app_theme_sophisticated.dart';
import 'core/auth/bloc/auth_bloc.dart';
import 'core/cache/dashboard_cache_manager.dart';
import 'features/auth/presentation/pages/login_page.dart';
import 'features/dashboard/presentation/pages/adaptive_dashboard_page.dart';

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

  // Configuration du système
  await _configureApp();

  // Initialisation du cache
  await DashboardCacheManager.initialize();

  runApp(const UnionFlowApp());
}

/// Configure les paramètres globaux de l'application
Future<void> _configureApp() async {
  // Configuration de l'orientation
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  // Configuration de la barre de statut
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness: Brightness.light,
      systemNavigationBarColor: Colors.white,
      systemNavigationBarIconBrightness: Brightness.dark,
    ),
  );
}

/// Application principale avec système d'authentification Keycloak
class UnionFlowApp extends StatelessWidget {
  const UnionFlowApp({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => AuthBloc()..add(const AuthStatusChecked()),
      child: MaterialApp(
        title: 'UnionFlow',
        debugShowCheckedModeBanner: false,

        // Configuration du thème
        theme: AppThemeSophisticated.lightTheme,
        // darkTheme: AppThemeSophisticated.darkTheme,
        // themeMode: ThemeMode.system,

        // Configuration de la localisation
        locale: const Locale('fr', 'FR'),
        supportedLocales: const [
          Locale('fr', 'FR'), // Français
          Locale('en', 'US'), // Anglais
        ],
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],

        // Configuration des routes
        routes: {
          '/': (context) => BlocBuilder<AuthBloc, AuthState>(
            builder: (context, state) {
              if (state is AuthLoading) {
                return const Scaffold(
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              } else if (state is AuthAuthenticated) {
                return const AdaptiveDashboardPage();
              } else {
                return const LoginPage();
              }
            },
          ),
          '/dashboard': (context) => const AdaptiveDashboardPage(),
          '/login': (context) => const LoginPage(),
        },

        // Page d'accueil par défaut
        initialRoute: '/',

        // Builder global pour gérer les erreurs
        builder: (context, child) {
          return MediaQuery(
            data: MediaQuery.of(context).copyWith(
              textScaler: const TextScaler.linear(1.0),
            ),
            child: child ?? const SizedBox(),
          );
        },
      ),
    );
  }
}