/// 自然写互动课堂平板端应用软件 V1.0
/// APP入口 - Flutter平板端应用初始化
///
/// 功能说明：
/// 1. 平板端应用初始化（Pad自适应布局配置）
/// 2. 学生端/教师端双模式切换
/// 3. 护眼模式初始化（色温调节、使用时长监控）
/// 4. 全局Bloc状态管理注入
/// 5. 离线模式支持（断网时可继续作答）

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

  // 全局错误处理
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.presentError(details);
    debugPrint('[CrashReport] ${details.exception}');
  };

  // 设置系统UI（平板端支持横屏+竖屏）
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
  ]);

  // 初始化全局服务
  await _initServices();

  runZonedGuarded(() {
    runApp(const WritechPadApp());
  }, (error, stack) {
    debugPrint('[CrashReport] $error\n$stack');
  });
}

/// 初始化全局服务
Future<void> _initServices() async {
  debugPrint('[App] 服务初始化开始');
  // 初始化数据库、网络、BLE、护眼模块
  debugPrint('[App] 服务初始化完成');
}

/// 平板端应用根Widget
class WritechPadApp extends StatefulWidget {
  const WritechPadApp({super.key});

  @override
  State<WritechPadApp> createState() => _WritechPadAppState();
}

class _WritechPadAppState extends State<WritechPadApp>
    with WidgetsBindingObserver {
  /// 当前用户模式（学生/教师）
  String _userMode = 'student';

  /// 护眼模式是否开启
  bool _eyeCareEnabled = false;

  /// 色温滤镜值（0.0=正常，1.0=最暖）
  double _colorTemperature = 0.0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      debugPrint('[App] 应用恢复前台');
    } else if (state == AppLifecycleState.paused) {
      debugPrint('[App] 应用进入后台');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '自然写互动课堂',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF4CAF50),
          brightness: Brightness.light,
        ),
        fontFamily: 'NotoSansSC',
      ),
      // 护眼色温滤镜叠加
      builder: (context, child) {
        if (_eyeCareEnabled && _colorTemperature > 0) {
          return ColorFiltered(
            colorFilter: ColorFilter.matrix(_buildWarmMatrix(_colorTemperature)),
            child: child,
          );
        }
        return child ?? const SizedBox();
      },
      initialRoute: '/splash',
      routes: {
        '/splash': (_) => const _SplashPage(),
        '/login': (_) => const _LoginPage(),
        '/student_home': (_) => const _StudentHomePage(),
        '/teacher_home': (_) => const _TeacherHomePage(),
        '/homework': (_) => const _HomeworkPage(),
        '/practice': (_) => const _PracticePage(),
        '/error_book': (_) => const _ErrorBookPage(),
        '/settings': (_) => const _SettingsPage(),
      },
    );
  }

  /// 构建暖色温矩阵（护眼模式）
  List<double> _buildWarmMatrix(double intensity) {
    final r = 1.0;
    final g = 1.0 - intensity * 0.1;
    final b = 1.0 - intensity * 0.3;
    return [
      r, 0, 0, 0, 0,
      0, g, 0, 0, 0,
      0, 0, b, 0, 0,
      0, 0, 0, 1, 0,
    ];
  }
}

// 占位页面声明
class _SplashPage extends StatelessWidget {
  const _SplashPage();
  @override
  Widget build(BuildContext context) => const Scaffold(body: Center(child: Text('自然写')));
}
class _LoginPage extends StatelessWidget {
  const _LoginPage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
class _StudentHomePage extends StatelessWidget {
  const _StudentHomePage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
class _TeacherHomePage extends StatelessWidget {
  const _TeacherHomePage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
class _HomeworkPage extends StatelessWidget {
  const _HomeworkPage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
class _PracticePage extends StatelessWidget {
  const _PracticePage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
class _ErrorBookPage extends StatelessWidget {
  const _ErrorBookPage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
class _SettingsPage extends StatelessWidget {
  const _SettingsPage();
  @override
  Widget build(BuildContext context) => const Scaffold();
}
