import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:webrtc_controller_flutter/l10n/app_localizations.dart';

import '../auth_controller.dart';

/// 启动页，对应 Android 端 `activity/splash/SplashActivity`。
///
/// 流程：
/// 1. 由 [AuthController] 从安全存储恢复令牌；
/// 2. 调用 `checkLoginState()` 校验（失效时用 refreshToken 续期后重试一次）；
/// 3. 校验通过跳转设置页（`/`），否则清空令牌并跳转登录页（`/login`）。
class SplashPage extends ConsumerStatefulWidget {
  const SplashPage({super.key});

  @override
  ConsumerState<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends ConsumerState<SplashPage> {
  @override
  void initState() {
    super.initState();
    // build() 期间不能直接改动 provider 状态，推迟到首帧之后。
    WidgetsBinding.instance.addPostFrameCallback((_) => _bootstrap());
  }

  Future<void> _bootstrap() async {
    final loggedIn =
        await ref.read(authControllerProvider.notifier).checkLoginState();
    if (!mounted) return;
    context.go(loggedIn ? '/' : '/login');
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    return CupertinoPageScaffold(
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(
              CupertinoIcons.device_phone_portrait,
              size: 64,
              color: CupertinoColors.activeBlue,
            ),
            const SizedBox(height: 20),
            Text(
              l10n.appTitle,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 24),
            const CupertinoActivityIndicator(),
          ],
        ),
      ),
    );
  }
}
