// main.dart — 入口(演示态)
// 串接:登录 → 引导 → 主框架(4 Tab);状态层统一走 Riverpod。
import 'dart:io';
import 'dart:ui' as ui;

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

import 'bridge/vpn_bridge_provider.dart';
import 'pangolin_theme.dart';
import 'services/token_store.dart';
import 'shell/home_shell.dart';
import 'state/app_providers.dart';
import 'state/auth_provider.dart';
import 'system_tray.dart';
import 'widgets/auth_screen.dart';
import 'widgets/onboarding_screen.dart';
import 'widgets/pangolin_logo.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 桌面端:单实例 + 常驻系统托盘(关闭窗口隐藏到托盘而非退出)。
  if (isDesktop) {
    if (!await ensureSingleInstance()) {
      exit(0); // 已有实例在跑(已唤起其窗口),本进程退出。
    }
    await TrayService.instance.init();
  }
  runApp(const ProviderScope(child: PangolinApp()));
}

class PangolinApp extends ConsumerStatefulWidget {
  const PangolinApp({super.key});

  @override
  ConsumerState<PangolinApp> createState() => _PangolinAppState();
}

class _PangolinAppState extends ConsumerState<PangolinApp> {
  AppLifecycleListener? _lifecycle;

  @override
  void initState() {
    super.initState();
    if (isDesktop) {
      // 真退出(Cmd+Q / 托盘退出)前先停内核拆隧道,避免 sing-box 孤儿 + TUN 残留。
      _lifecycle = AppLifecycleListener(onExitRequested: () async {
        await _teardownVpn();
        return ui.AppExitResponse.exit;
      });
      TrayService.instance.onBeforeQuit = _teardownVpn;
    }
  }

  Future<void> _teardownVpn() async {
    try {
      await ref.read(vpnBridgeProvider).stop().timeout(const Duration(seconds: 3));
    } catch (_) {
      // 内核未启动/已退出:忽略。
    }
  }

  @override
  void dispose() {
    _lifecycle?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final mode = ref.watch(themeModeProvider);
    return MaterialApp(
      title: '穿山甲',
      debugShowCheckedModeBanner: false,
      theme: PangolinTheme.light,
      darkTheme: PangolinTheme.dark,
      themeMode: mode,
      home: const RootFlow(),
    );
  }
}

/// 应用根流转:启动时若已有有效会话(7 天内 refresh 有效)直接进主界面,
/// 免登陆;会话失效则回登录页。引导页仅首次注册/登录后看一次。
class RootFlow extends ConsumerStatefulWidget {
  const RootFlow({super.key});
  @override
  ConsumerState<RootFlow> createState() => _RootFlowState();
}

class _RootFlowState extends ConsumerState<RootFlow> {
  final _store = const TokenStore();
  bool _forceOnboarding = false;

  // 登录/注册成功后:未看过引导才进引导,否则直接主界面。
  Future<void> _afterAuth() async {
    final onboarded = await _store.isOnboarded();
    if (!mounted) return;
    setState(() => _forceOnboarding = !onboarded);
  }

  Future<void> _afterOnboarding() async {
    await _store.markOnboarded();
    if (!mounted) return;
    setState(() => _forceOnboarding = false);
  }

  @override
  Widget build(BuildContext context) {
    final t = ref.watch(appTextProvider);
    final auth = ref.watch(authProvider);

    if (auth.isLoading) return const _Splash();
    if (!auth.isLoggedIn) {
      return AuthScreen(t: t, onDone: () { _afterAuth(); });
    }
    if (_forceOnboarding) {
      return OnboardingScreen(t: t, onDone: () { _afterOnboarding(); });
    }
    return const HomeShell();
  }
}

/// 会话恢复期间的极简启动屏(避免登录页一闪而过)。
class _Splash extends StatelessWidget {
  const _Splash();
  @override
  Widget build(BuildContext context) => const Scaffold(
        body: Center(child: PangolinMark(size: 56)),
      );
}
