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

import 'core/router/app_router.dart';
import 'core/theme/app_theme.dart';
import 'core/localization/app_localizations.dart';
import 'core/localization/locale_provider.dart';
import 'core/database/database_service.dart';
import 'features/device/providers/serial_provider.dart';

/// 应用入口
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Kiosk 模式：隐藏系统状态栏和导航栏
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

  // 固定横屏
  SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);

  final db = DatabaseService.instance;
  await db.database;
  await db.initTestData();

  // 使用 ProviderContainer 在 runApp 之前触发启动自动连接
  final container = ProviderContainer();
  container.read(autoSerialConnectProvider);

  runApp(
    UncontrolledProviderScope(
      container: container,
      child: const KuaishaiApp(),
    ),
  );
}

/// 应用主体
class KuaishaiApp extends ConsumerWidget {
  const KuaishaiApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final router = ref.watch(goRouterProvider);
    final locale = ref.watch(localeProvider);

    return MaterialApp.router(
      title: '污水毒品快检一体机',
      debugShowCheckedModeBanner: false,
      theme: AppTheme.lightTheme(),
      darkTheme: AppTheme.darkTheme(),
      themeMode: ThemeMode.light,

      // 国际化配置
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
      ],
      locale: locale,

      // 路由配置
      routerConfig: router,
    );
  }
}