import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/ui/base/app_theme.dart';
import 'di/app_providers.dart';
import 'di/network_provider.dart';
import 'router/app_router.dart';

/// 应用根组件
///
/// 职责：
/// - 路由配置（go_router，含登录守卫）
/// - 主题配置（亮色 / 暗色 / 跟随系统）
/// - App 生命周期监听（前后台切换 → WebSocket 断连/重连）
/// - 启动初始化（[AppInitializer] 两阶段串行队列）
///
/// ## 启动初始化
///
/// 通过 [appInitializerProvider] 声明任务，两阶段串行执行：
/// - Critical：首帧前，只放必须阻塞的任务
/// - Deferred：首帧后，不争抢资源、不卡 UI
///
/// 详见 [AppInitializer] 文档。
class IMApp extends ConsumerStatefulWidget {
  const IMApp({super.key});

  @override
  ConsumerState<IMApp> createState() => _IMAppState();
}

class _IMAppState extends ConsumerState<IMApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    ref.read(appInitializerProvider).run();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final socketManager = ref.read(socketManagerProvider);

    switch (state) {
      case AppLifecycleState.resumed:
        socketManager.onEnterForeground();
      case AppLifecycleState.paused:
        socketManager.onEnterBackground();
      case AppLifecycleState.inactive:
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'IM App', // TODO: 接入国际化
      theme: AppTheme.theme,
      darkTheme: AppTheme.darkTheme,
      themeMode: ref.watch(themeModeProvider),
      routerConfig: ref.watch(routerProvider),
    );
  }
}
