From 262ce70998fa52dec3120589f51c47e96fb96df4 Mon Sep 17 00:00:00 2001
From: 905086 <k2049@qq.com>
Date: Tue, 03 Nov 2026 17:04:19 +0800
Subject: [PATCH] feat: 完成游戏盒子前后端基础功能开发

---
 fluttergamebox/lib/widgets/activate_dialog.dart               |  195 +
 server/models/models.go                                       |  104 
 .gitignore                                                    |   19 
 server/handlers/admin.go                                      |  299 ++
 fluttergamebox/windows/flutter/generated_plugins.cmake        |    3 
 server/middleware/auth.go                                     |   48 
 fluttergamebox/windows/flutter/generated_plugin_registrant.cc |    9 
 server/utils/utils.go                                         |   57 
 files/image/logo.png                                          |    0 
 files/提示词.md                                                  |   60 
 fluttergamebox/lib/pages/library_page.dart                    |  631 ++++
 fluttergamebox/lib/pages/main_shell.dart                      |  866 ++++++
 fluttergamebox/lib/widgets/info_dialogs.dart                  |  325 ++
 fluttergamebox/lib/pages/detail_page.dart                     |  730 +++++
 fluttergamebox/lib/pages/tools_page.dart                      |  244 +
 server/main.go                                                |   76 
 fluttergamebox/lib/widgets/download_manager.dart              |  390 ++
 fluttergamebox/linux/flutter/generated_plugin_registrant.cc   |   12 
 files/image/登录页面图片.png                                        |    0 
 server/handlers/keys.go                                       |   76 
 fluttergamebox/assets/images/logo.png                         |    0 
 fluttergamebox/pubspec.yaml                                   |   10 
 fluttergamebox/lib/common/theme.dart                          |   16 
 fluttergamebox/macos/Flutter/GeneratedPluginRegistrant.swift  |   10 
 fluttergamebox/lib/pages/login_page.dart                      |  431 +++
 fluttergamebox/lib/widgets/window_controls.dart               |   69 
 fluttergamebox/lib/store/app_state.dart                       |  327 ++
 server/go.mod                                                 |   45 
 server/handlers/games.go                                      |  221 +
 fluttergamebox/lib/pages/favorites_page.dart                  |  101 
 fluttergamebox/lib/widgets/auth_dialogs.dart                  |  272 +
 fluttergamebox/lib/pages/store_page.dart                      |  436 +++
 fluttergamebox/linux/flutter/generated_plugins.cmake          |    3 
 fluttergamebox/lib/widgets/game_card.dart                     |  247 +
 fluttergamebox/pubspec.lock                                   |  345 ++
 server/go.sum                                                 |  138 +
 fluttergamebox/lib/main.dart                                  |  184 
 fluttergamebox/lib/utils/util.dart                            |   65 
 fluttergamebox/test/widget_test.dart                          |   27 
 fluttergamebox/lib/api/api_service.dart                       |  229 +
 server/handlers/auth.go                                       |  177 +
 fluttergamebox/assets/images/login_art.png                    |    0 
 fluttergamebox/lib/api/api_client.dart                        |   55 
 server/admin/index.html                                       |  462 +++
 server/config/db.go                                           |  187 +
 45 files changed, 8,065 insertions(+), 136 deletions(-)

diff --git a/.gitignore b/.gitignore
index ee26b53..57f9f5e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -99,3 +99,22 @@
 
 # 依赖目录
 node_modules/
+
+# Go 服务端相关
+server/*.exe
+server/gamebox-server
+# 运行时上传目录(封面、游戏包等,不入库)
+server/uploads/
+
+# 数据库文件(SQLite)
+*.db
+*.sqlite
+
+# 运行日志
+fluttergamebox/app_log.txt
+
+# 临时截图 / 对标裁剪图
+.screenshots/
+card_fav.png
+card_lib.png
+card_store.png
diff --git a/files/image/logo.png b/files/image/logo.png
new file mode 100644
index 0000000..8e19987
--- /dev/null
+++ b/files/image/logo.png
Binary files differ
diff --git "a/files/image/\347\231\273\345\275\225\351\241\265\351\235\242\345\233\276\347\211\207.png" "b/files/image/\347\231\273\345\275\225\351\241\265\351\235\242\345\233\276\347\211\207.png"
new file mode 100644
index 0000000..29ef38c
--- /dev/null
+++ "b/files/image/\347\231\273\345\275\225\351\241\265\351\235\242\345\233\276\347\211\207.png"
Binary files differ
diff --git "a/files/\346\217\220\347\244\272\350\257\215.md" "b/files/\346\217\220\347\244\272\350\257\215.md"
index 330d443..7a281d4 100644
--- "a/files/\346\217\220\347\244\272\350\257\215.md"
+++ "b/files/\346\217\220\347\244\272\350\257\215.md"
@@ -2,3 +2,63 @@
 
 <br />
 
+这是游戏盒子项目。
+
+对标项目的前端截图已经放到了files/target目录。
+
+项目要在windows客户端正常运行。
+
+前端使用flutter开发,目录在fluttergamebox。flutter项目刚创建好,没有开始开发。
+
+后端使用golang + gin + gorm + mysql开发。
+
+管理后台直接用gin实现。
+
+前端页面要一比一百分之百还原对标项目。
+
+可能用到的一些图片在files/image文件夹中,其他需要用到的可以用ai生成,或者用纯色占位。
+
+<br />
+
+mysql
+
+用户:root
+
+密码:123qwe
+
+数据库:gamebox
+
+<br />
+
+<br />
+
+管理后台要可以:
+
+生成会员密钥(日卡、月卡、年卡)。
+
+密钥默认不可以在不同的机器上使用,但是管理员可以手动将已经再其他电脑上使用过的密钥,再从新设置成可以再次使用。
+
+密钥到期以后,不能再下载游戏。从新使用其他密钥激活会员才可以下载游戏。
+
+密钥到期以后,已经下载的游戏还可以继续玩。
+
+要可以查看、上传、修改、删除游戏。
+
+上传游戏要可以上传图片、视频、游戏安装包、说明图片文字。
+
+要可以设置类别,增加、删除、修改类别的名字。
+
+上传游戏的时候可以设置成某个类别。
+
+<br />
+
+游戏详情页也要有首页的顶部导航栏。
+
+首页、资源库页面的启动和添加参考对标页面进行修改。位置不对。
+
+收藏中没有展示不已经收藏的游戏。
+
+<br />
+
+<br />
+
diff --git a/fluttergamebox/assets/images/login_art.png b/fluttergamebox/assets/images/login_art.png
new file mode 100644
index 0000000..29ef38c
--- /dev/null
+++ b/fluttergamebox/assets/images/login_art.png
Binary files differ
diff --git a/fluttergamebox/assets/images/logo.png b/fluttergamebox/assets/images/logo.png
new file mode 100644
index 0000000..8e19987
--- /dev/null
+++ b/fluttergamebox/assets/images/logo.png
Binary files differ
diff --git a/fluttergamebox/lib/api/api_client.dart b/fluttergamebox/lib/api/api_client.dart
new file mode 100644
index 0000000..6b6bed3
--- /dev/null
+++ b/fluttergamebox/lib/api/api_client.dart
@@ -0,0 +1,55 @@
+import 'package:dio/dio.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+class ApiClient {
+  static const baseUrl = 'http://localhost:8080';
+  static final Dio dio = Dio(BaseOptions(
+    baseUrl: baseUrl,
+    connectTimeout: const Duration(seconds: 10),
+    receiveTimeout: const Duration(minutes: 30),
+  ));
+
+  static String? token;
+
+  static Future<void> init() async {
+    final sp = await SharedPreferences.getInstance();
+    token = sp.getString('token');
+    dio.interceptors.add(InterceptorsWrapper(
+      onRequest: (options, handler) {
+        if (token != null) {
+          options.headers['Authorization'] = 'Bearer $token';
+        }
+        handler.next(options);
+      },
+    ));
+  }
+
+  static Future<void> saveToken(String t) async {
+    token = t;
+    final sp = await SharedPreferences.getInstance();
+    await sp.setString('token', t);
+  }
+
+  static Future<void> clearToken() async {
+    token = null;
+    final sp = await SharedPreferences.getInstance();
+    await sp.remove('token');
+  }
+
+  static Future<Map<String, dynamic>> get(String path,
+      {Map<String, dynamic>? params}) async {
+    final res = await dio.get(path, queryParameters: params);
+    return res.data as Map<String, dynamic>;
+  }
+
+  static Future<Map<String, dynamic>> post(String path,
+      [dynamic data]) async {
+    final res = await dio.post(path, data: data);
+    return res.data as Map<String, dynamic>;
+  }
+
+  static Future<Map<String, dynamic>> delete(String path) async {
+    final res = await dio.delete(path);
+    return res.data as Map<String, dynamic>;
+  }
+}
diff --git a/fluttergamebox/lib/api/api_service.dart b/fluttergamebox/lib/api/api_service.dart
new file mode 100644
index 0000000..a0c78b5
--- /dev/null
+++ b/fluttergamebox/lib/api/api_service.dart
@@ -0,0 +1,229 @@
+import 'dart:convert';
+import 'package:fluttergamebox/api/api_client.dart';
+
+class Game {
+  final int id;
+  final String title;
+  final int categoryId;
+  final String categoryName;
+  final String platform; // pc / switch
+  final String tags;
+  final String size;
+  final String installSize;
+  final String osReq;
+  final String cpuReq;
+  final String gpuReq;
+  final String ramReq;
+  final String versionNote;
+  final String cover;
+  final String video;
+  final List<String> screenshots;
+  final String description;
+  final List<GameFile> files;
+  final bool isBanner;
+  final int downloadCount;
+
+  Game({
+    required this.id,
+    required this.title,
+    required this.categoryId,
+    required this.categoryName,
+    required this.platform,
+    required this.tags,
+    required this.size,
+    required this.installSize,
+    required this.osReq,
+    required this.cpuReq,
+    required this.gpuReq,
+    required this.ramReq,
+    required this.versionNote,
+    required this.cover,
+    required this.video,
+    required this.screenshots,
+    required this.description,
+    required this.files,
+    required this.isBanner,
+    required this.downloadCount,
+  });
+
+  factory Game.fromJson(Map<String, dynamic> j) {
+    List<String> shots = [];
+    try {
+      if (j['screenshots'] is String && j['screenshots'].isNotEmpty) {
+        shots = (jsonDecode(j['screenshots']) as List).cast<String>();
+      }
+    } catch (_) {}
+    List<GameFile> files = [];
+    try {
+      if (j['files'] is String && j['files'].isNotEmpty) {
+        files = (jsonDecode(j['files']) as List)
+            .map((e) => GameFile.fromJson(e))
+            .toList();
+      }
+    } catch (_) {}
+    return Game(
+      id: (j['id'] ?? 0) as int,
+      title: j['title'] ?? '',
+      categoryId: (j['category_id'] ?? 0) as int,
+      categoryName: j['category_name'] ?? '',
+      platform: j['platform'] ?? 'pc',
+      tags: j['tags'] ?? '',
+      size: j['size'] ?? '',
+      installSize: j['install_size'] ?? '',
+      osReq: j['os_req'] ?? '',
+      cpuReq: j['cpu_req'] ?? '',
+      gpuReq: j['gpu_req'] ?? '',
+      ramReq: j['ram_req'] ?? '',
+      versionNote: j['version_note'] ?? '',
+      cover: j['cover'] ?? '',
+      video: j['video'] ?? '',
+      screenshots: shots,
+      description: j['description'] ?? '',
+      files: files,
+      isBanner: (j['is_banner'] ?? false) as bool,
+      downloadCount: (j['download_count'] ?? 0) as int,
+    );
+  }
+
+  String get platformLabel => platform == 'switch' ? 'Switch资源' : 'PC资源';
+}
+
+class GameFile {
+  final String name;
+  final String size;
+  final String url;
+  GameFile({required this.name, required this.size, required this.url});
+  factory GameFile.fromJson(Map<String, dynamic> j) => GameFile(
+        name: j['name'] ?? '',
+        size: j['size'] ?? '',
+        url: j['url'] ?? '',
+      );
+}
+
+class Category {
+  final int id;
+  final String name;
+  Category({required this.id, required this.name});
+  factory Category.fromJson(Map<String, dynamic> j) =>
+      Category(id: j['id'], name: j['name']);
+}
+
+class Tool {
+  final int id;
+  final String name;
+  final String size;
+  final String cover;
+  final String description;
+  final String fileUrl;
+  Tool({
+    required this.id,
+    required this.name,
+    required this.size,
+    required this.cover,
+    required this.description,
+    required this.fileUrl,
+  });
+  factory Tool.fromJson(Map<String, dynamic> j) => Tool(
+        id: j['id'],
+        name: j['name'] ?? '',
+        size: j['size'] ?? '',
+        cover: j['cover'] ?? '',
+        description: j['description'] ?? '',
+        fileUrl: j['file_url'] ?? '',
+      );
+}
+
+class ApiService {
+  // ---------- 认证 ----------
+  static Future<Map<String, dynamic>> captcha() async =>
+      await ApiClient.get('/api/captcha');
+
+  static Future<Map<String, dynamic>> register(Map<String, dynamic> data) async =>
+      await ApiClient.post('/api/register', data);
+
+  static Future<Map<String, dynamic>> login(String phone, String password) async =>
+      await ApiClient.post('/api/login', {'phone': phone, 'password': password});
+
+  static Future<Map<String, dynamic>> resetPassword(Map<String, dynamic> data) async =>
+      await ApiClient.post('/api/reset_password', data);
+
+  static Future<Map<String, dynamic>> userInfo() async =>
+      await ApiClient.get('/api/user/info');
+
+  // ---------- 游戏数据 ----------
+  static Future<List<Game>> games(
+      {String platform = 'all',
+      int category = 0,
+      String keyword = '',
+      String sort = 'updated'}) async {
+    final res = await ApiClient.get('/api/games', params: {
+      'platform': platform,
+      'category': category.toString(),
+      'keyword': keyword,
+      'sort': sort,
+    });
+    if (res['code'] != 0) return [];
+    return (res['data'] as List).map((e) => Game.fromJson(e)).toList();
+  }
+
+  static Future<List<Game>> banners() async {
+    final res = await ApiClient.get('/api/banners');
+    if (res['code'] != 0) return [];
+    return (res['data'] as List).map((e) => Game.fromJson(e)).toList();
+  }
+
+  static Future<Map<String, dynamic>> gameDetail(int id) async =>
+      await ApiClient.get('/api/games/$id');
+
+  static Future<List<Category>> categories() async {
+    final res = await ApiClient.get('/api/categories');
+    if (res['code'] != 0) return [];
+    return (res['data'] as List).map((e) => Category.fromJson(e)).toList();
+  }
+
+  static Future<List<Tool>> tools() async {
+    final res = await ApiClient.get('/api/tools');
+    if (res['code'] != 0) return [];
+    return (res['data'] as List).map((e) => Tool.fromJson(e)).toList();
+  }
+
+  static Future<String> announcements() async {
+    final res = await ApiClient.get('/api/announcements');
+    if (res['code'] != 0) return '';
+    final list = res['data'] as List;
+    if (list.isEmpty) return '';
+    return list.first['content'] ?? '';
+  }
+
+  // ---------- 收藏 / 资源库 ----------
+  static Future<Map<String, dynamic>> toggleFavorite(int gameId) async =>
+      await ApiClient.post('/api/favorites', {'game_id': gameId});
+
+  static Future<List<Game>> favorites() async {
+    final res = await ApiClient.get('/api/favorites');
+    if (res['code'] != 0) return [];
+    return (res['data'] as List).map((e) => Game.fromJson(e)).toList();
+  }
+
+  static Future<Map<String, dynamic>> addToLibrary(int gameId) async =>
+      await ApiClient.post('/api/library', {'game_id': gameId});
+
+  static Future<List<Game>> library() async {
+    final res = await ApiClient.get('/api/library');
+    if (res['code'] != 0) return [];
+    return (res['data'] as List).map((e) => Game.fromJson(e)).toList();
+  }
+
+  static Future<Map<String, dynamic>> removeFromLibrary(int gameId) async =>
+      await ApiClient.delete('/api/library/$gameId');
+
+  // ---------- 下载 / 密钥 ----------
+  static Future<Map<String, dynamic>> downloadInfo(int gameId) async =>
+      await ApiClient.get('/api/download/$gameId');
+
+  static Future<Map<String, dynamic>> activateKey(
+      String code, String machineCode) async {
+    return await ApiClient.post(
+        '/api/keys/activate', {'code': code, 'machine_code': machineCode});
+  }
+}
diff --git a/fluttergamebox/lib/common/theme.dart b/fluttergamebox/lib/common/theme.dart
new file mode 100644
index 0000000..9f113af
--- /dev/null
+++ b/fluttergamebox/lib/common/theme.dart
@@ -0,0 +1,16 @@
+import 'package:flutter/material.dart';
+
+class AppColors {
+  static const bg = Color(0xFF14161F); // 主背景
+  static const bgLight = Color(0xFF1E2130); // 卡片背景
+  static const bgLighter = Color(0xFF262A3D); // hover/边框
+  static const accent = Color(0xFF2B7FFF); // 主蓝色
+  static const accentDark = Color(0xFF1E63D6);
+  static const pink = Color(0xFFFF5C8A); // logo粉
+  static const red = Color(0xFFE74C3C);
+  static const green = Color(0xFF2ECC71);
+  static const yellow = Color(0xFFF1C40F);
+  static const textWhite = Color(0xFFFFFFFF);
+  static const textGray = Color(0xFF9AA0B4);
+  static const textDim = Color(0xFF6B7085);
+}
diff --git a/fluttergamebox/lib/main.dart b/fluttergamebox/lib/main.dart
index 244a702..6f2e629 100644
--- a/fluttergamebox/lib/main.dart
+++ b/fluttergamebox/lib/main.dart
@@ -1,122 +1,88 @@
-import 'package:flutter/material.dart';
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:window_manager/window_manager.dart';
 
-void main() {
-  runApp(const MyApp());
+import 'api/api_client.dart';
+import 'pages/login_page.dart';
+import 'pages/main_shell.dart';
+
+void main() async {
+  WidgetsFlutterBinding.ensureInitialized();
+  await windowManager.ensureInitialized();
+  await windowManager.waitUntilReadyToShow(
+    const WindowOptions(
+      size: Size(1280, 820),
+      minimumSize: Size(1100, 700),
+      title: '99游戏盒子',
+      titleBarStyle: TitleBarStyle.hidden,
+      center: true,
+      backgroundColor: Color(0xFF14161F),
+    ),
+    () async {
+      await windowManager.show();
+      await windowManager.focus();
+    },
+  );
+  runApp(const GameBoxApp());
 }
 
-class MyApp extends StatelessWidget {
-  const MyApp({super.key});
+class GameBoxApp extends StatefulWidget {
+  const GameBoxApp({super.key});
+  @override
+  State<GameBoxApp> createState() => _GameBoxAppState();
+}
 
-  // This widget is the root of your application.
+class _GameBoxAppState extends State<GameBoxApp> with WindowListener {
+  bool _ready = false;
+
+  @override
+  void initState() {
+    super.initState();
+    windowManager.addListener(this);
+    _init();
+  }
+
+  @override
+  void dispose() {
+    windowManager.removeListener(this);
+    super.dispose();
+  }
+
+  @override
+  void onWindowClose() async {
+    await windowManager.destroy();
+  }
+
+  Future<void> _init() async {
+    await ApiClient.init();
+    if (ApiClient.token != null) {
+      await AppState.instance.refreshUserInfo();
+    }
+    if (mounted) setState(() => _ready = true);
+  }
+
   @override
   Widget build(BuildContext context) {
     return MaterialApp(
-      title: 'Flutter Demo',
+      title: '99游戏盒子',
+      debugShowCheckedModeBanner: false,
       theme: ThemeData(
-        // This is the theme of your application.
-        //
-        // TRY THIS: Try running your application with "flutter run". You'll see
-        // the application has a purple toolbar. Then, without quitting the app,
-        // try changing the seedColor in the colorScheme below to Colors.green
-        // and then invoke "hot reload" (save your changes or press the "hot
-        // reload" button in a Flutter-supported IDE, or press "r" if you used
-        // the command line to start the app).
-        //
-        // Notice that the counter didn't reset back to zero; the application
-        // state is not lost during the reload. To reset the state, use hot
-        // restart instead.
-        //
-        // This works for code too, not just values: Most code changes can be
-        // tested with just a hot reload.
-        colorScheme: .fromSeed(seedColor: Colors.deepPurple),
+        fontFamily: 'Microsoft YaHei',
+        scaffoldBackgroundColor: const Color(0xFF14161F),
+        colorScheme: const ColorScheme.dark(primary: Color(0xFF2B7FFF)),
       ),
-      home: const MyHomePage(title: 'Flutter Demo Home Page'),
-    );
-  }
-}
-
-class MyHomePage extends StatefulWidget {
-  const MyHomePage({super.key, required this.title});
-
-  // This widget is the home page of your application. It is stateful, meaning
-  // that it has a State object (defined below) that contains fields that affect
-  // how it looks.
-
-  // This class is the configuration for the state. It holds the values (in this
-  // case the title) provided by the parent (in this case the App widget) and
-  // used by the build method of the State. Fields in a Widget subclass are
-  // always marked "final".
-
-  final String title;
-
-  @override
-  State<MyHomePage> createState() => _MyHomePageState();
-}
-
-class _MyHomePageState extends State<MyHomePage> {
-  int _counter = 0;
-
-  void _incrementCounter() {
-    setState(() {
-      // This call to setState tells the Flutter framework that something has
-      // changed in this State, which causes it to rerun the build method below
-      // so that the display can reflect the updated values. If we changed
-      // _counter without calling setState(), then the build method would not be
-      // called again, and so nothing would appear to happen.
-      _counter++;
-    });
-  }
-
-  @override
-  Widget build(BuildContext context) {
-    // This method is rerun every time setState is called, for instance as done
-    // by the _incrementCounter method above.
-    //
-    // The Flutter framework has been optimized to make rerunning build methods
-    // fast, so that you can just rebuild anything that needs updating rather
-    // than having to individually change instances of widgets.
-    return Scaffold(
-      appBar: AppBar(
-        // TRY THIS: Try changing the color here to a specific color (to
-        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
-        // change color while the other colors stay the same.
-        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
-        // Here we take the value from the MyHomePage object that was created by
-        // the App.build method, and use it to set our appbar title.
-        title: Text(widget.title),
-      ),
-      body: Center(
-        // Center is a layout widget. It takes a single child and positions it
-        // in the middle of the parent.
-        child: Column(
-          // Column is also a layout widget. It takes a list of children and
-          // arranges them vertically. By default, it sizes itself to fit its
-          // children horizontally, and tries to be as tall as its parent.
-          //
-          // Column has various properties to control how it sizes itself and
-          // how it positions its children. Here we use mainAxisAlignment to
-          // center the children vertically; the main axis here is the vertical
-          // axis because Columns are vertical (the cross axis would be
-          // horizontal).
-          //
-          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
-          // action in the IDE, or press "p" in the console), to see the
-          // wireframe for each widget.
-          mainAxisAlignment: .center,
-          children: [
-            const Text('You have pushed the button this many times:'),
-            Text(
-              '$_counter',
-              style: Theme.of(context).textTheme.headlineMedium,
+      home: _ready
+          ? AnimatedBuilder(
+              animation: AppState.instance,
+              builder: (context, _) => AppState.instance.loggedIn
+                  ? const MainShell()
+                  : const LoginPage(),
+            )
+          : const Scaffold(
+              body: Center(
+                child: CircularProgressIndicator(color: Color(0xFF2B7FFF)),
+              ),
             ),
-          ],
-        ),
-      ),
-      floatingActionButton: FloatingActionButton(
-        onPressed: _incrementCounter,
-        tooltip: 'Increment',
-        child: const Icon(Icons.add),
-      ),
     );
   }
 }
diff --git a/fluttergamebox/lib/pages/detail_page.dart b/fluttergamebox/lib/pages/detail_page.dart
new file mode 100644
index 0000000..f538ae3
--- /dev/null
+++ b/fluttergamebox/lib/pages/detail_page.dart
@@ -0,0 +1,730 @@
+import 'dart:async';
+
+import 'package:file_picker/file_picker.dart';
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/util.dart';
+import 'package:fluttergamebox/widgets/download_manager.dart';
+
+class DetailPage extends StatefulWidget {
+  final int gameId;
+  final VoidCallback? onBack; // 在主Shell内展示时由Shell提供(保留顶部导航栏)
+  const DetailPage({super.key, required this.gameId, this.onBack});
+  @override
+  State<DetailPage> createState() => _DetailPageState();
+}
+
+class _DetailPageState extends State<DetailPage> {
+  Game? game;
+  bool isFavorite = false;
+  bool inLibrary = false;
+  bool _loading = true;
+  int _mediaIndex = 0;
+  Timer? _slideTimer;
+  late PageController _pageCtrl;
+
+  @override
+  void initState() {
+    super.initState();
+    _pageCtrl = PageController();
+    _load();
+  }
+
+  @override
+  void dispose() {
+    _slideTimer?.cancel();
+    _pageCtrl.dispose();
+    super.dispose();
+  }
+
+  Future<void> _load() async {
+    final res = await ApiService.gameDetail(widget.gameId);
+    if (!mounted) return;
+    if (res['code'] == 0) {
+      setState(() {
+        game = Game.fromJson(res['data']['game']);
+        isFavorite = res['data']['is_favorite'] == true;
+        inLibrary = res['data']['in_library'] == true;
+        _loading = false;
+      });
+      // 媒体自动轮播
+      _slideTimer?.cancel();
+      _slideTimer = Timer.periodic(const Duration(seconds: 5), (_) {
+        final mediaCount = 1 + (game?.screenshots.length ?? 0);
+        if (mediaCount > 1 && mounted && _pageCtrl.hasClients) {
+          _pageCtrl.nextPage(
+              duration: const Duration(milliseconds: 400),
+              curve: Curves.easeInOut);
+        }
+      });
+    } else {
+      setState(() => _loading = false);
+    }
+  }
+
+  Future<void> _toggleFavorite() async {
+    final res = await ApiService.toggleFavorite(widget.gameId);
+    if (res['code'] == 0 && mounted) {
+      setState(() => isFavorite = !isFavorite);
+      _toast(res['msg'] ?? '操作成功');
+    }
+  }
+
+  Future<void> _addToLibrary() async {
+    final res = await ApiService.addToLibrary(widget.gameId);
+    if (res['code'] == 0 && mounted) {
+      setState(() => inLibrary = true);
+      _showConfirmDialog(
+          '兑换成功!', '游戏已加入资源库,请在资源库页面查看。');
+    } else if (mounted) {
+      _toast(res['msg'] ?? '添加失败', error: true);
+    }
+  }
+
+  Future<void> _download() async {
+    if (game == null) return;
+    // 检查下载路径
+    var dlPath = await AppPrefs.getDownloadPath();
+    if (dlPath.isEmpty) {
+      final ok = await _askDownloadPath();
+      if (!ok) return;
+      dlPath = await AppPrefs.getDownloadPath();
+    }
+    // 会员校验+开始下载
+    try {
+      await DownloadManager.instance.startDownload(game!);
+      if (mounted) showDownloadDialog(context);
+      setState(() => inLibrary = true);
+    } catch (e) {
+      if (mounted) _toast(e.toString(), error: true);
+    }
+  }
+
+  /// 首次下载询问下载路径
+  Future<bool> _askDownloadPath() async {
+    final res = await ApiService.downloadInfo(widget.gameId);
+    if (res['code'] != 0) {
+      if (mounted) _toast(res['msg'] ?? '无法下载', error: true);
+      return false;
+    }
+    final result = await showDialog<bool>(
+      context: context,
+      builder: (context) => _DownloadPathDialog(gameTitle: game!.title),
+    );
+    return result == true;
+  }
+
+  void _toast(String msg, {bool error = false}) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding:
+                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: error ? AppColors.red : AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                Icon(error ? Icons.error_outline : Icons.check_circle,
+                    color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(
+                          color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  void _showConfirmDialog(String title, String content) {
+    showDialog(
+      context: context,
+      builder: (context) => Dialog(
+        backgroundColor: Colors.white,
+        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+        child: Container(
+          width: 360,
+          padding: const EdgeInsets.all(24),
+          child: Column(
+            mainAxisSize: MainAxisSize.min,
+            children: [
+              const Icon(Icons.check_circle,
+                  color: AppColors.green, size: 48),
+              const SizedBox(height: 16),
+              Text(title,
+                  style: const TextStyle(
+                      color: Colors.black,
+                      fontSize: 16,
+                      fontWeight: FontWeight.bold)),
+              const SizedBox(height: 8),
+              Text(content,
+                  textAlign: TextAlign.center,
+                  style: const TextStyle(
+                      color: Color(0xFF666666), fontSize: 13)),
+              const SizedBox(height: 20),
+              SizedBox(
+                width: 120,
+                child: ElevatedButton(
+                  onPressed: () => Navigator.pop(context),
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    foregroundColor: Colors.white,
+                  ),
+                  child: const Text('确定'),
+                ),
+              ),
+            ],
+          ),
+        ),
+      ),
+    );
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      backgroundColor: AppColors.bg,
+      body: _loading
+          ? const Center(
+              child: CircularProgressIndicator(color: AppColors.accent))
+          : game == null
+              ? const Center(
+                  child: Text('游戏不存在',
+                      style: TextStyle(color: AppColors.textGray)))
+              : Column(
+                  children: [
+                    _buildHeader(),
+                    Expanded(
+                      child: SingleChildScrollView(
+                        child: Padding(
+                          padding: const EdgeInsets.fromLTRB(70, 16, 70, 40),
+                          child: Row(
+                            crossAxisAlignment: CrossAxisAlignment.start,
+                            children: [
+                              // 左侧:媒体+介绍
+                              Expanded(child: _buildLeft()),
+                              const SizedBox(width: 20),
+                              // 右侧:配置+操作
+                              SizedBox(width: 320, child: _buildRight()),
+                            ],
+                          ),
+                        ),
+                      ),
+                    ),
+                  ],
+                ),
+    );
+  }
+
+  Widget _buildHeader() {
+    return Container(
+      height: 52,
+      color: const Color(0xFF191C2B),
+      padding: const EdgeInsets.symmetric(horizontal: 16),
+      child: Row(
+        children: [
+          IconButton(
+            icon: const Icon(Icons.arrow_back,
+                size: 20, color: AppColors.textGray),
+            onPressed: () {
+              if (widget.onBack != null) {
+                widget.onBack!();
+              } else {
+                Navigator.pop(context);
+              }
+            },
+          ),
+          const SizedBox(width: 8),
+          Expanded(
+            child: Text(game!.title,
+                maxLines: 1,
+                overflow: TextOverflow.ellipsis,
+                style: const TextStyle(
+                    color: Colors.white,
+                    fontSize: 15,
+                    fontWeight: FontWeight.w500)),
+          ),
+          // 收藏
+          GestureDetector(
+            onTap: _toggleFavorite,
+            child: Row(
+              children: [
+                Icon(
+                  isFavorite ? Icons.star : Icons.star_border,
+                  size: 18,
+                  color: isFavorite ? AppColors.yellow : AppColors.textGray,
+                ),
+                const SizedBox(width: 4),
+                Text(isFavorite ? '取消收藏' : '收藏',
+                    style: TextStyle(
+                        color: isFavorite
+                            ? AppColors.yellow
+                            : AppColors.textGray,
+                        fontSize: 13)),
+              ],
+            ),
+          ),
+          const SizedBox(width: 20),
+        ],
+      ),
+    );
+  }
+
+  Widget _buildLeft() {
+    return Column(
+      crossAxisAlignment: CrossAxisAlignment.start,
+      children: [
+        // 媒体轮播
+        _buildMedia(),
+        const SizedBox(height: 20),
+        // 游戏介绍
+        const Text('游戏介绍',
+            style: TextStyle(
+                color: Colors.white,
+                fontSize: 15,
+                fontWeight: FontWeight.w500)),
+        const SizedBox(height: 12),
+        Container(
+          width: double.infinity,
+          padding: const EdgeInsets.all(16),
+          decoration: BoxDecoration(
+            color: AppColors.bgLight,
+            borderRadius: BorderRadius.circular(6),
+          ),
+          child: Text(
+            game!.description.isEmpty ? '暂无介绍' : game!.description,
+            style: const TextStyle(
+                color: AppColors.textGray, fontSize: 13, height: 1.8),
+          ),
+        ),
+        // 截图
+        if (game!.screenshots.isNotEmpty) ...[
+          const SizedBox(height: 20),
+          const Text('游戏截图',
+              style: TextStyle(
+                  color: Colors.white,
+                  fontSize: 15,
+                  fontWeight: FontWeight.w500)),
+          const SizedBox(height: 12),
+          Wrap(
+            spacing: 10,
+            runSpacing: 10,
+            children: game!.screenshots
+                .map((s) => ClipRRect(
+                      borderRadius: BorderRadius.circular(4),
+                      child: Image.network(
+                        ApiClient.baseUrl + s,
+                        width: 200,
+                        height: 112,
+                        fit: BoxFit.cover,
+                        errorBuilder: (_, __, ___) => Container(
+                          width: 200,
+                          height: 112,
+                          color: AppColors.bgLighter,
+                        ),
+                      ),
+                    ))
+                .toList(),
+          ),
+        ],
+      ],
+    );
+  }
+
+  Widget _buildMedia() {
+    final mediaCount = 1 + game!.screenshots.length;
+    return Column(
+      children: [
+        AspectRatio(
+          aspectRatio: 16 / 8,
+          child: PageView.builder(
+            controller: _pageCtrl,
+            itemCount: mediaCount,
+            onPageChanged: (i) => setState(() => _mediaIndex = i),
+            itemBuilder: (context, i) {
+              if (i == 0 && game!.video.isNotEmpty) {
+                // 视频占位(展示封面+播放按钮)
+                return _buildMediaItem(game!.cover, isVideo: true);
+              }
+              final img = i == 0 ? game!.cover : game!.screenshots[i - 1];
+              return _buildMediaItem(img);
+            },
+          ),
+        ),
+        const SizedBox(height: 8),
+        // 缩略图
+        Row(
+          children: [
+            for (var i = 0; i < mediaCount; i++)
+              GestureDetector(
+                onTap: () => _pageCtrl.animateToPage(i,
+                    duration: const Duration(milliseconds: 300),
+                    curve: Curves.easeInOut),
+                child: Container(
+                  width: 88,
+                  height: 50,
+                  margin: const EdgeInsets.only(right: 8),
+                  decoration: BoxDecoration(
+                    borderRadius: BorderRadius.circular(4),
+                    border: Border.all(
+                      color: _mediaIndex == i
+                          ? AppColors.accent
+                          : Colors.transparent,
+                      width: 2,
+                    ),
+                  ),
+                  child: ClipRRect(
+                    borderRadius: BorderRadius.circular(3),
+                    child: Image.network(
+                      ApiClient.baseUrl +
+                          (i == 0 ? game!.cover : game!.screenshots[i - 1]),
+                      fit: BoxFit.cover,
+                      errorBuilder: (_, __, ___) =>
+                          Container(color: AppColors.bgLighter),
+                    ),
+                  ),
+                ),
+              ),
+          ],
+        ),
+      ],
+    );
+  }
+
+  Widget _buildMediaItem(String img, {bool isVideo = false}) {
+    return ClipRRect(
+      borderRadius: BorderRadius.circular(8),
+      child: Stack(
+        fit: StackFit.expand,
+        children: [
+          Image.network(
+            ApiClient.baseUrl + img,
+            fit: BoxFit.cover,
+            errorBuilder: (_, __, ___) =>
+                Container(color: AppColors.bgLighter),
+          ),
+          if (isVideo)
+            Center(
+              child: Container(
+                width: 64,
+                height: 64,
+                decoration: BoxDecoration(
+                  color: Colors.black.withOpacity(0.5),
+                  shape: BoxShape.circle,
+                  border: Border.all(color: Colors.white38),
+                ),
+                child: const Icon(Icons.play_arrow,
+                    color: Colors.white, size: 36),
+              ),
+            ),
+          // 版本说明条
+          Positioned(
+            left: 0,
+            right: 0,
+            bottom: 0,
+            child: Container(
+              padding:
+                  const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+              decoration: BoxDecoration(
+                gradient: LinearGradient(
+                  begin: Alignment.bottomCenter,
+                  end: Alignment.topCenter,
+                  colors: [
+                    Colors.black.withOpacity(0.8),
+                    Colors.transparent,
+                  ],
+                ),
+              ),
+              child: Text(game!.versionNote,
+                  maxLines: 1,
+                  overflow: TextOverflow.ellipsis,
+                  style: const TextStyle(color: Colors.white, fontSize: 13)),
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+
+  Widget _buildRight() {
+    return Container(
+      padding: const EdgeInsets.all(20),
+      decoration: BoxDecoration(
+        color: AppColors.bgLight,
+        borderRadius: BorderRadius.circular(8),
+      ),
+      child: Column(
+        crossAxisAlignment: CrossAxisAlignment.start,
+        children: [
+          // 类别标签
+          Wrap(
+            spacing: 8,
+            runSpacing: 8,
+            children: [
+              _tag(game!.platformLabel, AppColors.accent),
+              for (final t in game!.tags.split(','))
+                if (t.trim().isNotEmpty) _tag(t.trim(), AppColors.bgLighter),
+            ],
+          ),
+          const SizedBox(height: 18),
+          _infoRow('游戏大小', game!.size),
+          _infoRow('磁盘占用', game!.installSize),
+          const Divider(color: AppColors.bgLighter, height: 28),
+          _infoRow('操作系统', game!.osReq),
+          _infoRow('CPU', game!.cpuReq),
+          _infoRow('内存', game!.ramReq),
+          _infoRow('显卡', game!.gpuReq),
+          const SizedBox(height: 20),
+          // 加入资源库
+          SizedBox(
+            width: double.infinity,
+            height: 44,
+            child: ElevatedButton(
+              onPressed: inLibrary ? null : _addToLibrary,
+              style: ElevatedButton.styleFrom(
+                backgroundColor: inLibrary
+                    ? const Color(0xFF3A3F52)
+                    : const Color(0xFF00A651),
+                foregroundColor: Colors.white,
+                disabledBackgroundColor: const Color(0xFF3A3F52),
+                disabledForegroundColor: AppColors.textGray,
+                shape: RoundedRectangleBorder(
+                    borderRadius: BorderRadius.circular(4)),
+              ),
+              child: Row(
+                mainAxisAlignment: MainAxisAlignment.center,
+                children: [
+                  Icon(
+                    inLibrary
+                        ? Icons.check_circle_outline
+                        : Icons.add_circle_outline,
+                    size: 18,
+                  ),
+                  const SizedBox(width: 8),
+                  Text(inLibrary ? '已在资源库' : '加入资源库',
+                      style: const TextStyle(fontSize: 14)),
+                ],
+              ),
+            ),
+          ),
+          const SizedBox(height: 12),
+          // 下载游戏
+          SizedBox(
+            width: double.infinity,
+            height: 44,
+            child: ElevatedButton(
+              onPressed: _download,
+              style: ElevatedButton.styleFrom(
+                backgroundColor: AppColors.accent,
+                foregroundColor: Colors.white,
+                shape: RoundedRectangleBorder(
+                    borderRadius: BorderRadius.circular(4)),
+              ),
+              child: const Row(
+                mainAxisAlignment: MainAxisAlignment.center,
+                children: [
+                  Icon(Icons.download, size: 18),
+                  SizedBox(width: 8),
+                  Text('下载游戏', style: TextStyle(fontSize: 14)),
+                ],
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+
+  Widget _tag(String text, Color color) {
+    return Container(
+      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
+      decoration: BoxDecoration(
+        color: color,
+        borderRadius: BorderRadius.circular(3),
+      ),
+      child: Text(text,
+          style: const TextStyle(color: Colors.white, fontSize: 12)),
+    );
+  }
+
+  Widget _infoRow(String label, String value) {
+    return Padding(
+      padding: const EdgeInsets.symmetric(vertical: 5),
+      child: Row(
+        crossAxisAlignment: CrossAxisAlignment.start,
+        children: [
+          SizedBox(
+            width: 60,
+            child: Text(label,
+                style: const TextStyle(
+                    color: AppColors.textDim, fontSize: 13)),
+          ),
+          Expanded(
+            child: Text(value.isEmpty ? '-' : value,
+                style: const TextStyle(
+                    color: AppColors.textWhite, fontSize: 13)),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+/// 下载路径选择弹窗
+class _DownloadPathDialog extends StatefulWidget {
+  final String gameTitle;
+  const _DownloadPathDialog({required this.gameTitle});
+  @override
+  State<_DownloadPathDialog> createState() => _DownloadPathDialogState();
+}
+
+class _DownloadPathDialogState extends State<_DownloadPathDialog> {
+  final _dlCtrl = TextEditingController();
+  final _insCtrl = TextEditingController();
+
+  @override
+  void initState() {
+    super.initState();
+    _load();
+  }
+
+  Future<void> _load() async {
+    final dl = await AppPrefs.getDownloadPath();
+    final ins = await AppPrefs.getInstallPath();
+    setState(() {
+      _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
+      _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
+    });
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Dialog(
+      backgroundColor: const Color(0xFF1E2130),
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+      child: Container(
+        width: 500,
+        padding: const EdgeInsets.all(24),
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: [
+            Row(
+              children: [
+                const Icon(Icons.folder,
+                    size: 16, color: AppColors.textGray),
+                const SizedBox(width: 8),
+                const Text('请选择下载安装路径',
+                    style: TextStyle(
+                        color: Colors.white,
+                        fontSize: 14,
+                        fontWeight: FontWeight.w500)),
+                const Spacer(),
+                GestureDetector(
+                  onTap: () => Navigator.pop(context, false),
+                  child: const Icon(Icons.close,
+                      size: 16, color: AppColors.textGray),
+                ),
+              ],
+            ),
+            const SizedBox(height: 18),
+            _pathRow('下载路径', _dlCtrl),
+            const SizedBox(height: 12),
+            _pathRow('安装路径', _insCtrl),
+            const SizedBox(height: 20),
+            Row(
+              mainAxisAlignment: MainAxisAlignment.end,
+              children: [
+                OutlinedButton(
+                  onPressed: () => Navigator.pop(context, false),
+                  style: OutlinedButton.styleFrom(
+                    foregroundColor: AppColors.textGray,
+                    side: const BorderSide(color: AppColors.bgLighter),
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 22, vertical: 10),
+                  ),
+                  child: const Text('取消'),
+                ),
+                const SizedBox(width: 12),
+                ElevatedButton(
+                  onPressed: () async {
+                    await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
+                    if (context.mounted) Navigator.pop(context, true);
+                  },
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    foregroundColor: Colors.white,
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 22, vertical: 10),
+                  ),
+                  child: const Text('确认'),
+                ),
+              ],
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+
+  Widget _pathRow(String label, TextEditingController ctrl) {
+    return Column(
+      crossAxisAlignment: CrossAxisAlignment.start,
+      children: [
+        Text(label,
+            style: const TextStyle(color: AppColors.textGray, fontSize: 12)),
+        const SizedBox(height: 6),
+        Row(
+          children: [
+            Expanded(
+              child: TextField(
+                controller: ctrl,
+                style: const TextStyle(color: Colors.black, fontSize: 13),
+                decoration: InputDecoration(
+                  filled: true,
+                  fillColor: Colors.white,
+                  contentPadding: const EdgeInsets.symmetric(
+                      horizontal: 10, vertical: 10),
+                  border: OutlineInputBorder(
+                      borderRadius: BorderRadius.circular(4),
+                      borderSide: BorderSide.none),
+                ),
+              ),
+            ),
+            const SizedBox(width: 8),
+            ElevatedButton(
+              onPressed: () async {
+                final dir = await FilePicker.platform.getDirectoryPath();
+                if (dir != null) setState(() => ctrl.text = dir);
+              },
+              style: ElevatedButton.styleFrom(
+                backgroundColor: AppColors.accent,
+                foregroundColor: Colors.white,
+                padding: const EdgeInsets.symmetric(
+                    horizontal: 14, vertical: 11),
+              ),
+              child: const Text('选择目录', style: TextStyle(fontSize: 12)),
+            ),
+          ],
+        ),
+      ],
+    );
+  }
+}
diff --git a/fluttergamebox/lib/pages/favorites_page.dart b/fluttergamebox/lib/pages/favorites_page.dart
new file mode 100644
index 0000000..dc7ba78
--- /dev/null
+++ b/fluttergamebox/lib/pages/favorites_page.dart
@@ -0,0 +1,101 @@
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/widgets/game_card.dart';
+
+class FavoritesPage extends StatefulWidget {
+  const FavoritesPage({super.key});
+  @override
+  State<FavoritesPage> createState() => FavoritesPageState();
+}
+
+class FavoritesPageState extends State<FavoritesPage>
+    with AutomaticKeepAliveClientMixin {
+  List<Game> games = [];
+  bool _loading = true;
+
+  @override
+  bool get wantKeepAlive => true;
+
+  @override
+  void initState() {
+    super.initState();
+    _load();
+  }
+
+  Future<void> _load() async {
+    final g = await ApiService.favorites();
+    if (!mounted) return;
+    setState(() {
+      games = g;
+      _loading = false;
+    });
+  }
+
+  /// 供主Shell刷新(切换到收藏页/关闭详情页时重新拉取)
+  void refresh() => _load();
+
+  @override
+  Widget build(BuildContext context) {
+    super.build(context);
+    return Container(
+      color: AppColors.bg,
+      padding: const EdgeInsets.fromLTRB(70, 20, 70, 0),
+      child: Column(
+        crossAxisAlignment: CrossAxisAlignment.start,
+        children: [
+          Row(
+            children: [
+              const Icon(Icons.star, color: AppColors.yellow, size: 18),
+              const SizedBox(width: 8),
+              const Text('我的收藏',
+                  style: TextStyle(
+                      color: Colors.white,
+                      fontSize: 16,
+                      fontWeight: FontWeight.w500)),
+              const SizedBox(width: 12),
+              Text('共 ${games.length} 款',
+                  style: const TextStyle(
+                      color: AppColors.textGray, fontSize: 13)),
+            ],
+          ),
+          const SizedBox(height: 16),
+          Expanded(
+            child: _loading
+                ? const Center(
+                    child:
+                        CircularProgressIndicator(color: AppColors.accent))
+                : games.isEmpty
+                    ? const Center(
+                        child: Column(
+                          mainAxisSize: MainAxisSize.min,
+                          children: [
+                            Icon(Icons.star_border,
+                                size: 56, color: AppColors.textDim),
+                            SizedBox(height: 12),
+                            Text('暂无收藏游戏',
+                                style: TextStyle(
+                                    color: AppColors.textGray,
+                                    fontSize: 14)),
+                          ],
+                        ),
+                      )
+                    : GridView.builder(
+                        padding: const EdgeInsets.only(bottom: 40),
+                        gridDelegate:
+                            const SliverGridDelegateWithFixedCrossAxisCount(
+                          crossAxisCount: 4,
+                          mainAxisSpacing: 18,
+                          crossAxisSpacing: 16,
+                          childAspectRatio: 0.62,
+                        ),
+                        itemCount: games.length,
+                        itemBuilder: (context, i) => GameCard(game: games[i]),
+                      ),
+          ),
+        ],
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/pages/library_page.dart b/fluttergamebox/lib/pages/library_page.dart
new file mode 100644
index 0000000..7441ce0
--- /dev/null
+++ b/fluttergamebox/lib/pages/library_page.dart
@@ -0,0 +1,631 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/util.dart';
+import 'package:path/path.dart' as p;
+
+class LibraryPage extends StatefulWidget {
+  const LibraryPage({super.key});
+  @override
+  State<LibraryPage> createState() => LibraryPageState();
+}
+
+class LibraryPageState extends State<LibraryPage>
+    with AutomaticKeepAliveClientMixin {
+  List<Game> games = [];
+  List<Category> categories = [];
+  int category = 0;
+  bool _loading = true;
+  final GlobalKey<AnimatedListState> _listKey = GlobalKey();
+
+  @override
+  bool get wantKeepAlive => true;
+
+  @override
+  void initState() {
+    super.initState();
+    _load();
+  }
+
+  Future<void> _load() async {
+    final g = await ApiService.library();
+    final c = await ApiService.categories();
+    if (!mounted) return;
+    setState(() {
+      games = g;
+      categories = c.where((e) => e.name != '常用工具').toList();
+      _loading = false;
+    });
+  }
+
+  /// 供主Shell刷新(切换到资源库页/关闭详情页时重新拉取)
+  void refresh() => _load();
+
+  List<Game> get filtered => category == 0
+      ? games
+      : games.where((g) => g.categoryId == category).toList();
+
+  @override
+  Widget build(BuildContext context) {
+    super.build(context);
+    return Container(
+      color: AppColors.bg,
+      padding: const EdgeInsets.fromLTRB(70, 20, 70, 0),
+      child: Column(
+        crossAxisAlignment: CrossAxisAlignment.start,
+        children: [
+          // 顶部:类别筛选
+          Row(
+            children: [
+              const Text('我的资源库',
+                  style: TextStyle(
+                      color: Colors.white,
+                      fontSize: 16,
+                      fontWeight: FontWeight.w500)),
+              const SizedBox(width: 20),
+              _CategoryFilter(
+                categories: categories,
+                value: category,
+                onChanged: (v) => setState(() => category = v ?? 0),
+              ),
+              const Spacer(),
+              // 模拟器管理
+              ElevatedButton.icon(
+                onPressed: () => _showEmulatorDialog(context),
+                icon: const Icon(Icons.memory, size: 16),
+                label: const Text('模拟器管理', style: TextStyle(fontSize: 13)),
+                style: ElevatedButton.styleFrom(
+                  backgroundColor: AppColors.bgLight,
+                  foregroundColor: AppColors.textWhite,
+                  elevation: 0,
+                  padding: const EdgeInsets.symmetric(
+                      horizontal: 14, vertical: 8),
+                ),
+              ),
+            ],
+          ),
+          const SizedBox(height: 16),
+          Expanded(
+            child: _loading
+                ? const Center(
+                    child:
+                        CircularProgressIndicator(color: AppColors.accent))
+                : filtered.isEmpty
+                    ? Center(
+                        child: Column(
+                          mainAxisSize: MainAxisSize.min,
+                          children: [
+                            const Icon(Icons.folder_open,
+                                size: 56, color: AppColors.textDim),
+                            const SizedBox(height: 12),
+                            const Text('资源库空空如也,快去添加游戏吧',
+                                style: TextStyle(
+                                    color: AppColors.textGray, fontSize: 14)),
+                            const SizedBox(height: 16),
+                            ElevatedButton(
+                              onPressed: () => Navigator.pop(context),
+                              child: const Text('去商店逛逛'),
+                            ),
+                          ],
+                        ),
+                      )
+                    : GridView.builder(
+                        padding: const EdgeInsets.only(bottom: 40),
+                        gridDelegate:
+                            const SliverGridDelegateWithFixedCrossAxisCount(
+                          crossAxisCount: 5,
+                          mainAxisSpacing: 18,
+                          crossAxisSpacing: 16,
+                          childAspectRatio: 0.60,
+                        ),
+                        itemCount: filtered.length,
+                        itemBuilder: (context, i) =>
+                            _LibraryCard(game: filtered[i], onRemove: _load),
+                      ),
+          ),
+        ],
+      ),
+    );
+  }
+
+  void _showEmulatorDialog(BuildContext context) {
+    showDialog(
+      context: context,
+      builder: (context) => Dialog(
+        backgroundColor: const Color(0xFF1E2130),
+        shape:
+            RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+        child: Container(
+          width: 480,
+          padding: const EdgeInsets.all(24),
+          child: Column(
+            mainAxisSize: MainAxisSize.min,
+            crossAxisAlignment: CrossAxisAlignment.start,
+            children: [
+              Row(
+                children: [
+                  const Icon(Icons.memory,
+                      size: 16, color: AppColors.textGray),
+                  const SizedBox(width: 8),
+                  const Text('模拟器管理',
+                      style: TextStyle(
+                          color: Colors.white,
+                          fontSize: 14,
+                          fontWeight: FontWeight.w500)),
+                  const Spacer(),
+                  GestureDetector(
+                    onTap: () => Navigator.pop(context),
+                    child: const Icon(Icons.close,
+                        size: 16, color: AppColors.textGray),
+                  ),
+                ],
+              ),
+              const SizedBox(height: 16),
+              Container(
+                padding: const EdgeInsets.all(12),
+                decoration: BoxDecoration(
+                  color: AppColors.bg,
+                  borderRadius: BorderRadius.circular(4),
+                ),
+                child: const Row(
+                  children: [
+                    Icon(Icons.info_outline,
+                        size: 14, color: AppColors.textGray),
+                    SizedBox(width: 8),
+                    Expanded(
+                      child: Text(
+                          '下载Switch游戏前,请先下载安装模拟器。启动Switch游戏会自动调用模拟器运行。',
+                          style: TextStyle(
+                              color: AppColors.textGray, fontSize: 12)),
+                    ),
+                  ],
+                ),
+              ),
+              const SizedBox(height: 16),
+              _EmulatorItem(
+                name: 'Yuzu模拟器',
+                desc: '最新版本,支持所有Switch游戏',
+                installed: true,
+              ),
+              const SizedBox(height: 10),
+              _EmulatorItem(
+                name: 'Ryujinx模拟器',
+                desc: '兼容性好,部分游戏更流畅',
+                installed: false,
+              ),
+            ],
+          ),
+        ),
+      ),
+    );
+  }
+}
+
+class _EmulatorItem extends StatelessWidget {
+  final String name;
+  final String desc;
+  final bool installed;
+  const _EmulatorItem({
+    required this.name,
+    required this.desc,
+    required this.installed,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      padding: const EdgeInsets.all(14),
+      decoration: BoxDecoration(
+        color: AppColors.bg,
+        borderRadius: BorderRadius.circular(6),
+        border: Border.all(color: AppColors.bgLighter),
+      ),
+      child: Row(
+        children: [
+          Container(
+            width: 44,
+            height: 44,
+            decoration: BoxDecoration(
+              color: AppColors.bgLighter,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: const Icon(Icons.videogame_asset,
+                color: AppColors.accent, size: 22),
+          ),
+          const SizedBox(width: 12),
+          Expanded(
+            child: Column(
+              crossAxisAlignment: CrossAxisAlignment.start,
+              children: [
+                Row(
+                  children: [
+                    Text(name,
+                        style: const TextStyle(
+                            color: Colors.white,
+                            fontSize: 13,
+                            fontWeight: FontWeight.w500)),
+                    const SizedBox(width: 8),
+                    if (installed)
+                      Container(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 6, vertical: 1),
+                        decoration: BoxDecoration(
+                          color: AppColors.green.withOpacity(0.15),
+                          borderRadius: BorderRadius.circular(2),
+                        ),
+                        child: const Text('已安装',
+                            style: TextStyle(
+                                color: AppColors.green, fontSize: 10)),
+                      ),
+                  ],
+                ),
+                const SizedBox(height: 4),
+                Text(desc,
+                    style: const TextStyle(
+                        color: AppColors.textDim, fontSize: 12)),
+              ],
+            ),
+          ),
+          installed
+              ? OutlinedButton(
+                  onPressed: () {},
+                  style: OutlinedButton.styleFrom(
+                    foregroundColor: AppColors.textGray,
+                    side: const BorderSide(color: AppColors.bgLighter),
+                  ),
+                  child: const Text('打开', style: TextStyle(fontSize: 12)),
+                )
+              : ElevatedButton(
+                  onPressed: () {},
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    foregroundColor: Colors.white,
+                  ),
+                  child: const Text('安装', style: TextStyle(fontSize: 12)),
+                ),
+        ],
+      ),
+    );
+  }
+}
+
+class _CategoryFilter extends StatelessWidget {
+  final List<Category> categories;
+  final int value;
+  final ValueChanged<int?> onChanged;
+  const _CategoryFilter({
+    required this.categories,
+    required this.value,
+    required this.onChanged,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      height: 30,
+      padding: const EdgeInsets.symmetric(horizontal: 12),
+      decoration: BoxDecoration(
+        color: AppColors.bgLight,
+        borderRadius: BorderRadius.circular(4),
+      ),
+      child: DropdownButtonHideUnderline(
+        child: DropdownButton<int>(
+          value: value,
+          dropdownColor: const Color(0xFF232739),
+          style: const TextStyle(color: AppColors.textWhite, fontSize: 13),
+          icon: const Icon(Icons.arrow_drop_down,
+              size: 18, color: AppColors.textGray),
+          items: [
+            const DropdownMenuItem(
+                value: 0, child: Text('全部类别')),
+            ...categories.map((c) =>
+                DropdownMenuItem(value: c.id, child: Text(c.name))),
+          ],
+          onChanged: onChanged,
+        ),
+      ),
+    );
+  }
+}
+
+/// 资源库游戏卡片(右键菜单)
+class _LibraryCard extends StatelessWidget {
+  final Game game;
+  final VoidCallback onRemove;
+  const _LibraryCard({required this.game, required this.onRemove});
+
+  Future<String> _installDir() async {
+    final ins = await AppPrefs.getInstallPath();
+    final base = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
+    return '$base\\${game.title.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_')}';
+  }
+
+  Future<void> _launch(BuildContext context) async {
+    final dir = await _installDir();
+    // 尝试查找目录中的exe并启动(启动已下载的游戏不需要会员)
+    final d = Directory(dir);
+    if (await d.exists()) {
+      final exes = d
+          .listSync(recursive: false)
+          .whereType<File>()
+          .where((f) => f.path.toLowerCase().endsWith('.exe'))
+          .toList();
+      if (exes.isNotEmpty) {
+        Process.run(exes.first.path, [], workingDirectory: dir);
+        return;
+      }
+    }
+    // 未找到可执行文件
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding: const EdgeInsets.symmetric(
+                horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: AppColors.red,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: const Row(
+              children: [
+                Icon(Icons.error_outline, color: Colors.white, size: 18),
+                SizedBox(width: 8),
+                Expanded(
+                  child: Text('未找到游戏文件,请先下载游戏',
+                      style:
+                          TextStyle(color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  Future<void> _openDir() async {
+    final dir = await _installDir();
+    final d = Directory(dir);
+    if (!await d.exists()) {
+      await d.create(recursive: true);
+    }
+    Process.run('explorer.exe', [p.normalize(dir)]);
+  }
+
+  Future<void> _createShortcut() async {
+    // 通过PowerShell创建桌面快捷方式(指向游戏目录)
+    final dir = await _installDir();
+    final script =
+        '\$s=(New-Object -COM WScript.Shell).CreateShellLink(\"\$env:USERPROFILE\\Desktop\\${game.title}.lnk\");'
+        '\$s.TargetPath=\"$dir\"; \$s.Save()';
+    Process.run('powershell', ['-command', script]);
+  }
+
+  Future<void> _uninstall(BuildContext context) async {
+    final res = await ApiService.removeFromLibrary(game.id);
+    if (res['code'] == 0) {
+      onRemove();
+    }
+  }
+
+  void _showContextMenu(BuildContext context, Offset position) {
+    final overlay = Overlay.of(context);
+    late OverlayEntry entry;
+    entry = OverlayEntry(
+      builder: (context) => Stack(
+        children: [
+          GestureDetector(
+            behavior: HitTestBehavior.opaque,
+            onTap: () => entry.remove(),
+            onSecondaryTapDown: (_) => entry.remove(),
+            child: Container(color: Colors.black.withOpacity(0.01)),
+          ),
+          Positioned(
+            left: position.dx,
+            top: position.dy,
+            child: Material(
+              color: Colors.transparent,
+              child: Container(
+                width: 150,
+                decoration: BoxDecoration(
+                  color: const Color(0xFF232739),
+                  borderRadius: BorderRadius.circular(6),
+                  border: Border.all(color: AppColors.bgLighter),
+                  boxShadow: [
+                    BoxShadow(
+                        color: Colors.black.withOpacity(0.5),
+                        blurRadius: 12)
+                  ],
+                ),
+                child: Column(
+                  mainAxisSize: MainAxisSize.min,
+                  children: [
+                    _menuItem(context, Icons.play_arrow, '启动游戏',
+                        () => _launch(context)),
+                    _menuItem(context, Icons.link, '创建快捷方式',
+                        _createShortcut),
+                    _menuItem(context, Icons.folder_open, '打开游戏目录',
+                        _openDir),
+                    _menuItem(context, Icons.delete_outline, '卸载游戏',
+                        () => _uninstall(context)),
+                  ],
+                ),
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+    overlay.insert(entry);
+  }
+
+  Widget _menuItem(
+      BuildContext context, IconData icon, String label, VoidCallback onTap) {
+    return InkWell(
+      onTap: onTap,
+      child: Padding(
+        padding:
+            const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
+        child: Row(
+          children: [
+            Icon(icon, size: 15, color: AppColors.textGray),
+            const SizedBox(width: 10),
+            Text(label,
+                style: const TextStyle(
+                    color: AppColors.textWhite, fontSize: 13)),
+          ],
+        ),
+      ),
+    );
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return GestureDetector(
+      onTap: () => _launch(context),
+      onSecondaryTapDown: (details) =>
+          _showContextMenu(context, details.globalPosition),
+      child: MouseRegion(
+        cursor: SystemMouseCursors.click,
+        child: Container(
+          decoration: BoxDecoration(
+            color: AppColors.bgLight,
+            borderRadius: BorderRadius.circular(6),
+          ),
+          child: Column(
+            crossAxisAlignment: CrossAxisAlignment.start,
+            children: [
+              AspectRatio(
+                aspectRatio: 1.42,
+                child: Stack(
+                  fit: StackFit.expand,
+                  children: [
+                    ClipRRect(
+                      borderRadius: const BorderRadius.vertical(
+                          top: Radius.circular(6)),
+                      child: Image.network(
+                        ApiClient.baseUrl + game.cover,
+                        fit: BoxFit.cover,
+                        errorBuilder: (_, __, ___) => Container(
+                          color: const Color(0xFF2A2E45),
+                          child: Center(
+                            child: Text(
+                                game.title.characters.first,
+                                style: const TextStyle(
+                                    color: AppColors.textDim,
+                                    fontSize: 32)),
+                          ),
+                        ),
+                      ),
+                    ),
+                    // PC资源 标签
+                    Positioned(
+                      left: 0,
+                      top: 8,
+                      child: Container(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 8, vertical: 3),
+                        decoration: const BoxDecoration(
+                          color: AppColors.accent,
+                          borderRadius:
+                              BorderRadius.horizontal(right: Radius.circular(3)),
+                        ),
+                        child: Text(game.platformLabel,
+                            style: const TextStyle(
+                                color: Colors.white, fontSize: 11)),
+                      ),
+                    ),
+                    // 大小标签
+                    Positioned(
+                      right: 6,
+                      top: 8,
+                      child: Container(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 6, vertical: 2),
+                        decoration: BoxDecoration(
+                          color: Colors.black.withOpacity(0.6),
+                          borderRadius: BorderRadius.circular(3),
+                        ),
+                        child: Text(game.size,
+                            style: const TextStyle(
+                                color: Colors.white, fontSize: 11)),
+                      ),
+                    ),
+                  ],
+                ),
+              ),
+              Expanded(
+                child: Padding(
+                  padding: const EdgeInsets.all(10),
+                  child: Column(
+                    crossAxisAlignment: CrossAxisAlignment.start,
+                    children: [
+                      if (game.versionNote.isNotEmpty)
+                        Padding(
+                          padding: const EdgeInsets.only(bottom: 2),
+                          child: Text(
+                            game.versionNote,
+                            maxLines: 1,
+                            overflow: TextOverflow.ellipsis,
+                            style: const TextStyle(
+                                color: AppColors.textDim, fontSize: 11),
+                          ),
+                        ),
+                      Text(game.title,
+                          maxLines: 2,
+                          overflow: TextOverflow.ellipsis,
+                          style: const TextStyle(
+                              color: Colors.white,
+                              fontSize: 12,
+                              height: 1.3)),
+                      const Spacer(),
+                      Row(
+                        children: [
+                          Expanded(
+                            child: Text(
+                              game.tags.split(',').first,
+                              maxLines: 1,
+                              overflow: TextOverflow.ellipsis,
+                              style: const TextStyle(
+                                  color: AppColors.textDim, fontSize: 11),
+                            ),
+                          ),
+                          // 启动按钮(对标:标签行右侧紧凑按钮)
+                          GestureDetector(
+                            onTap: () => _launch(context),
+                            child: Container(
+                              padding: const EdgeInsets.symmetric(
+                                  horizontal: 14, vertical: 4),
+                              decoration: BoxDecoration(
+                                color: AppColors.accent,
+                                borderRadius: BorderRadius.circular(3),
+                              ),
+                              child: const Text('启动',
+                                  style: TextStyle(
+                                      color: Colors.white, fontSize: 11)),
+                            ),
+                          ),
+                        ],
+                      ),
+                    ],
+                  ),
+                ),
+              ),
+            ],
+          ),
+        ),
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/pages/login_page.dart b/fluttergamebox/lib/pages/login_page.dart
new file mode 100644
index 0000000..516063a
--- /dev/null
+++ b/fluttergamebox/lib/pages/login_page.dart
@@ -0,0 +1,431 @@
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/widgets/auth_dialogs.dart';
+import 'package:fluttergamebox/widgets/window_controls.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+class LoginPage extends StatefulWidget {
+  const LoginPage({super.key});
+  @override
+  State<LoginPage> createState() => _LoginPageState();
+}
+
+class _LoginPageState extends State<LoginPage> {
+  final _phoneCtrl = TextEditingController();
+  final _pwdCtrl = TextEditingController();
+  bool _loading = false;
+  String? _error;
+
+  // 检查更新提示
+  void _checkUpdate() {
+    showToast(context, '当前已是最新版本!');
+  }
+
+  Future<void> _login() async {
+    final phone = _phoneCtrl.text.trim();
+    final pwd = _pwdCtrl.text;
+    if (phone.isEmpty || pwd.isEmpty) {
+      setState(() => _error = '请输入账号和密码');
+      return;
+    }
+    setState(() {
+      _loading = true;
+      _error = null;
+    });
+    try {
+      final res = await ApiService.login(phone, pwd);
+      if (!mounted) return;
+      if (res['code'] == 0) {
+        await ApiClient.saveToken(res['data']['token']);
+        await AppState.instance.refreshUserInfo();
+        if (mounted) {
+          // 登录成功后弹出公告
+          final ann = await ApiService.announcements();
+          if (mounted && ann.isNotEmpty) {
+            showAnnouncementDialog(context, ann);
+          }
+        }
+      } else {
+        setState(() => _error = res['msg'] ?? '登录失败');
+      }
+    } catch (e) {
+      setState(() => _error = '网络连接失败,请检查网络');
+    } finally {
+      if (mounted) setState(() => _loading = false);
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      body: Column(
+        children: [
+          // 顶部窗口控制条(透明悬浮在右上角)
+          SizedBox(
+            height: 36,
+            child: Row(
+              children: [
+                const Spacer(),
+                const WindowControls(dark: false),
+              ],
+            ),
+          ),
+          Expanded(
+            child: Row(
+              children: [
+                // 左侧宣传图
+                Expanded(
+                  flex: 3,
+                  child: Stack(
+                    fit: StackFit.expand,
+                    children: [
+                      Image.asset(
+                        'assets/images/login_art.png',
+                        fit: BoxFit.cover,
+                        errorBuilder: (_, __, ___) => Container(
+                          color: const Color(0xFF1B1E2E),
+                          child: const Center(
+                            child: Text('99游戏盒子',
+                                style: TextStyle(
+                                    color: AppColors.pink,
+                                    fontSize: 40,
+                                    fontWeight: FontWeight.bold)),
+                          ),
+                        ),
+                      ),
+                      // 底部渐变
+                      Container(
+                        decoration: BoxDecoration(
+                          gradient: LinearGradient(
+                            begin: Alignment.centerLeft,
+                            end: Alignment.centerRight,
+                            colors: [
+                              Colors.transparent,
+                              const Color(0xFF14161F).withOpacity(0.9),
+                            ],
+                          ),
+                        ),
+                      ),
+                    ],
+                  ),
+                ),
+                // 右侧登录面板
+                Container(
+                  width: 400,
+                  color: const Color(0xFF1B1E2E),
+                  padding: const EdgeInsets.symmetric(
+                      horizontal: 44, vertical: 30),
+                  child: Column(
+                    children: [
+                      const Spacer(flex: 2),
+                      // Logo
+                      Container(
+                        width: 88,
+                        height: 88,
+                        decoration: BoxDecoration(
+                          shape: BoxShape.circle,
+                          boxShadow: [
+                            BoxShadow(
+                              color: AppColors.pink.withOpacity(0.4),
+                              blurRadius: 40,
+                              spreadRadius: 5,
+                            ),
+                          ],
+                        ),
+                        child: ClipOval(
+                          child: Image.asset(
+                            'assets/images/logo.png',
+                            fit: BoxFit.cover,
+                            errorBuilder: (_, __, ___) => Container(
+                              color: AppColors.pink,
+                              child: const Center(
+                                child: Text('99',
+                                    style: TextStyle(
+                                        color: Colors.white,
+                                        fontSize: 32,
+                                        fontWeight: FontWeight.bold)),
+                              ),
+                            ),
+                          ),
+                        ),
+                      ),
+                      const SizedBox(height: 36),
+                      // 账号
+                      _InputField(
+                        controller: _phoneCtrl,
+                        icon: Icons.person_outline,
+                        hint: '请输入账号',
+                      ),
+                      const SizedBox(height: 16),
+                      // 密码
+                      _InputField(
+                        controller: _pwdCtrl,
+                        icon: Icons.lock_outline,
+                        hint: '请输入密码',
+                        obscure: true,
+                      ),
+                      const SizedBox(height: 10),
+                      if (_error != null)
+                        Padding(
+                          padding: const EdgeInsets.only(bottom: 8),
+                          child: Text(_error!,
+                              style: const TextStyle(
+                                  color: AppColors.red, fontSize: 13)),
+                        ),
+                      // 找回密码 / 注册账号
+                      Row(
+                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
+                        children: [
+                          _LinkText('找回密码', onTap: () => showForgotDialog(context)),
+                          _LinkText('注册账号', onTap: () => showRegisterDialog(context)),
+                        ],
+                      ),
+                      const SizedBox(height: 22),
+                      // 登录按钮
+                      SizedBox(
+                        width: double.infinity,
+                        height: 46,
+                        child: ElevatedButton(
+                          onPressed: _loading ? null : _login,
+                          style: ElevatedButton.styleFrom(
+                            backgroundColor: AppColors.accent,
+                            foregroundColor: Colors.white,
+                            shape: RoundedRectangleBorder(
+                                borderRadius: BorderRadius.circular(6)),
+                            elevation: 0,
+                          ),
+                          child: _loading
+                              ? const SizedBox(
+                                  width: 20,
+                                  height: 20,
+                                  child: CircularProgressIndicator(
+                                      strokeWidth: 2, color: Colors.white))
+                              : const Text('登录',
+                                  style: TextStyle(fontSize: 16)),
+                        ),
+                      ),
+                      const Spacer(flex: 3),
+                      // 版本信息
+                      Row(
+                        mainAxisAlignment: MainAxisAlignment.center,
+                        children: [
+                          const Text('客户端版本: V2.2.5',
+                              style: TextStyle(
+                                  color: AppColors.textDim, fontSize: 12)),
+                          const SizedBox(width: 8),
+                          GestureDetector(
+                            onTap: _checkUpdate,
+                            child: const Text('检查更新',
+                                style: TextStyle(
+                                    color: AppColors.accent, fontSize: 12)),
+                          ),
+                        ],
+                      ),
+                      const SizedBox(height: 10),
+                    ],
+                  ),
+                ),
+              ],
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _InputField extends StatefulWidget {
+  final TextEditingController controller;
+  final IconData icon;
+  final String hint;
+  final bool obscure;
+  const _InputField({
+    required this.controller,
+    required this.icon,
+    required this.hint,
+    this.obscure = false,
+  });
+
+  @override
+  State<_InputField> createState() => _InputFieldState();
+}
+
+class _InputFieldState extends State<_InputField> {
+  bool _obscure = false;
+
+  @override
+  void initState() {
+    super.initState();
+    _obscure = widget.obscure;
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      height: 46,
+      decoration: BoxDecoration(
+        color: const Color(0xFF14161F),
+        borderRadius: BorderRadius.circular(6),
+        border: Border.all(color: const Color(0xFF333750)),
+      ),
+      child: Row(
+        children: [
+          const SizedBox(width: 12),
+          Icon(widget.icon, color: AppColors.textGray, size: 20),
+          const SizedBox(width: 10),
+          Expanded(
+            child: TextField(
+              controller: widget.controller,
+              obscureText: _obscure,
+              style: const TextStyle(color: Colors.white, fontSize: 14),
+              decoration: InputDecoration(
+                hintText: widget.hint,
+                hintStyle: const TextStyle(
+                    color: AppColors.textDim, fontSize: 13),
+                border: InputBorder.none,
+                isDense: true,
+              ),
+            ),
+          ),
+          if (widget.obscure)
+            IconButton(
+              icon: Icon(
+                  _obscure
+                      ? Icons.visibility_off_outlined
+                      : Icons.visibility_outlined,
+                  color: AppColors.textDim,
+                  size: 18),
+              onPressed: () => setState(() => _obscure = !_obscure),
+            ),
+          const SizedBox(width: 8),
+        ],
+      ),
+    );
+  }
+}
+
+class _LinkText extends StatelessWidget {
+  final String text;
+  final VoidCallback? onTap;
+  const _LinkText(this.text, {this.onTap});
+  @override
+  Widget build(BuildContext context) {
+    return GestureDetector(
+      onTap: onTap,
+      child: Text(text,
+          style: const TextStyle(color: AppColors.textGray, fontSize: 13)),
+    );
+  }
+}
+
+/// 全局 Toast
+void showToast(BuildContext context, String msg, {bool error = false}) {
+  final overlay = Overlay.of(context);
+  final entry = OverlayEntry(
+    builder: (context) => Positioned(
+      top: 60,
+      left: MediaQuery.of(context).size.width / 2 - 140,
+      child: Material(
+        color: Colors.transparent,
+        child: Container(
+          width: 280,
+          padding:
+              const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+          decoration: BoxDecoration(
+            color: error ? AppColors.red : AppColors.green,
+            borderRadius: BorderRadius.circular(6),
+            boxShadow: [
+              BoxShadow(
+                  color: Colors.black.withOpacity(0.4), blurRadius: 10)
+            ],
+          ),
+          child: Row(
+            children: [
+              Icon(error ? Icons.error_outline : Icons.check_circle,
+                  color: Colors.white, size: 18),
+              const SizedBox(width: 8),
+              Expanded(
+                child: Text(msg,
+                    style:
+                        const TextStyle(color: Colors.white, fontSize: 13)),
+              ),
+            ],
+          ),
+        ),
+      ),
+    ),
+  );
+  overlay.insert(entry);
+  Future.delayed(const Duration(seconds: 2), () => entry.remove());
+}
+
+/// 登录成功后的公告弹窗
+void showAnnouncementDialog(BuildContext context, String content) {
+  showDialog(
+    context: context,
+    builder: (context) => Dialog(
+      backgroundColor: Colors.white,
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+      child: Container(
+        width: 420,
+        padding: const EdgeInsets.all(24),
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: [
+            Row(
+              children: [
+                const Icon(Icons.campaign,
+                    color: Color(0xFF2B7FFF), size: 22),
+                const SizedBox(width: 8),
+                const Text('系统公告',
+                    style: TextStyle(
+                        color: Colors.black,
+                        fontSize: 16,
+                        fontWeight: FontWeight.bold)),
+                const Spacer(),
+                GestureDetector(
+                  onTap: () => Navigator.pop(context),
+                  child: const Icon(Icons.close,
+                      color: Colors.grey, size: 20),
+                ),
+              ],
+            ),
+            const SizedBox(height: 16),
+            ConstrainedBox(
+              constraints: const BoxConstraints(maxHeight: 320),
+              child: SingleChildScrollView(
+                child: Text(
+                  content,
+                  style: const TextStyle(
+                      color: Color(0xFFE74C3C),
+                      fontSize: 13,
+                      height: 1.9),
+                ),
+              ),
+            ),
+            const SizedBox(height: 16),
+            Align(
+              alignment: Alignment.centerRight,
+              child: ElevatedButton(
+                onPressed: () => Navigator.pop(context),
+                style: ElevatedButton.styleFrom(
+                  backgroundColor: const Color(0xFF2B7FFF),
+                  foregroundColor: Colors.white,
+                  shape: RoundedRectangleBorder(
+                      borderRadius: BorderRadius.circular(4)),
+                ),
+                child: const Text('知道了'),
+              ),
+            ),
+          ],
+        ),
+      ),
+    ),
+  );
+}
diff --git a/fluttergamebox/lib/pages/main_shell.dart b/fluttergamebox/lib/pages/main_shell.dart
new file mode 100644
index 0000000..bdfdac5
--- /dev/null
+++ b/fluttergamebox/lib/pages/main_shell.dart
@@ -0,0 +1,866 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/pages/detail_page.dart';
+import 'package:fluttergamebox/pages/favorites_page.dart';
+import 'package:fluttergamebox/pages/library_page.dart';
+import 'package:fluttergamebox/pages/store_page.dart';
+import 'package:fluttergamebox/pages/tools_page.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/widgets/activate_dialog.dart';
+import 'package:fluttergamebox/widgets/download_manager.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:fluttergamebox/widgets/info_dialogs.dart';
+import 'package:fluttergamebox/widgets/window_controls.dart';
+
+/// 主界面导航:卡片点击打开详情页(保留顶部导航栏)
+class ShellNav {
+  static final ShellNav instance = ShellNav();
+  void Function(int gameId)? openDetail;
+  VoidCallback? goBack;
+}
+
+class MainShell extends StatefulWidget {
+  const MainShell({super.key});
+  @override
+  State<MainShell> createState() => _MainShellState();
+}
+
+class _MainShellState extends State<MainShell> {
+  int _navIndex = 0; // 0商店 1资源库 2收藏 3工具
+  int? _detailGameId; // 非空时显示详情页(带顶部导航栏)
+  final _storeKey = GlobalKey<StorePageState>();
+  final _libKey = GlobalKey<LibraryPageState>();
+  final _favKey = GlobalKey<FavoritesPageState>();
+
+  @override
+  void initState() {
+    super.initState();
+    AppState.instance.refreshUserInfo();
+    ShellNav.instance.openDetail =
+        (id) => setState(() => _detailGameId = id);
+    ShellNav.instance.goBack = _closeDetail;
+  }
+
+  @override
+  void dispose() {
+    ShellNav.instance.openDetail = null;
+    ShellNav.instance.goBack = null;
+    super.dispose();
+  }
+
+  void _closeDetail() {
+    setState(() => _detailGameId = null);
+    // 详情页里可能收藏/加入资源库/下载,关闭后刷新各页面
+    _storeKey.currentState?.refresh();
+    _libKey.currentState?.refresh();
+    _favKey.currentState?.refresh();
+  }
+
+  void _switchNav(int index) {
+    setState(() {
+      _navIndex = index;
+      _detailGameId = null;
+    });
+    // 切换页面时刷新对应数据(如收藏、资源库)
+    switch (index) {
+      case 0:
+        _storeKey.currentState?.refresh();
+      case 1:
+        _libKey.currentState?.refresh();
+      case 2:
+        _favKey.currentState?.refresh();
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      body: Column(
+        children: [
+          _buildTopBar(),
+          // 进度条(下载中显示)
+          AnimatedBuilder(
+            animation: DownloadManager.instance,
+            builder: (context, _) {
+              final task = DownloadManager.instance.activeTask;
+              if (task == null || task.finished) return const SizedBox.shrink();
+              return Container(
+                height: 3,
+                color: AppColors.bgLight,
+                child: LinearProgressIndicator(
+                  value: task.progress,
+                  backgroundColor: Colors.transparent,
+                  color: AppColors.accent,
+                ),
+              );
+            },
+          ),
+          Expanded(
+            child: _detailGameId != null
+                ? DetailPage(
+                    key: ValueKey('detail_$_detailGameId'),
+                    gameId: _detailGameId!,
+                    onBack: _closeDetail,
+                  )
+                : Stack(
+                    children: [
+                      // 主内容
+                      IndexedStack(
+                        index: _navIndex,
+                        children: [
+                          StorePage(key: _storeKey),
+                          LibraryPage(key: _libKey),
+                          FavoritesPage(key: _favKey),
+                          const ToolsPage(),
+                        ],
+                      ),
+                      // 左侧浮动栏
+                      const Positioned(left: 0, top: 20, child: _LeftSidebar()),
+                      // 右侧浮动栏
+                      Positioned(right: 0, top: 20, child: _RightSidebar(
+                        onActivate: () => showActivateDialog(context),
+                      )),
+                    ],
+                  ),
+          ),
+        ],
+      ),
+    );
+  }
+
+  Widget _buildTopBar() {
+    return GestureDetector(
+      onDoubleTap: () {},
+      child: Container(
+        height: 52,
+        color: const Color(0xFF191C2B),
+        child: Row(
+          children: [
+            const SizedBox(width: 14),
+            // Logo
+            ClipOval(
+              child: Image.asset('assets/images/logo.png',
+                  width: 28,
+                  height: 28,
+                  fit: BoxFit.cover,
+                  errorBuilder: (_, __, ___) => Container(
+                      width: 28,
+                      height: 28,
+                      color: AppColors.pink,
+                      child: const Center(
+                          child: Text('99',
+                              style: TextStyle(
+                                  color: Colors.white, fontSize: 11))))),
+            ),
+            const SizedBox(width: 8),
+            const Text('99游戏盒子',
+                style: TextStyle(
+                    color: Colors.white,
+                    fontSize: 14,
+                    fontWeight: FontWeight.bold)),
+            const SizedBox(width: 24),
+            // 返回 / 前进 / 主页(对标顶部导航栏)
+            IconButton(
+              icon: Icon(Icons.arrow_back,
+                  size: 18,
+                  color: _detailGameId != null
+                      ? AppColors.textWhite
+                      : AppColors.textDim),
+              onPressed:
+                  _detailGameId != null ? _closeDetail : null,
+              tooltip: '返回',
+            ),
+            const Icon(Icons.arrow_forward,
+                size: 18, color: AppColors.textDim),
+            const SizedBox(width: 4),
+            IconButton(
+              icon: Icon(Icons.home_outlined,
+                  size: 18,
+                  color: _navIndex == 0 && _detailGameId == null
+                      ? AppColors.textWhite
+                      : AppColors.textGray),
+              onPressed: () => _switchNav(0),
+              tooltip: '主页',
+            ),
+            const SizedBox(width: 8),
+            // 导航按钮
+            _NavItem(
+              icon: Icons.shopping_bag_outlined,
+              label: '商店',
+              active: _navIndex == 0,
+              onTap: () => _switchNav(0),
+            ),
+            _NavItem(
+              icon: Icons.folder_outlined,
+              label: '资源库',
+              active: _navIndex == 1,
+              onTap: () => _switchNav(1),
+            ),
+            _NavItem(
+              icon: Icons.star_outline,
+              label: '收藏',
+              active: _navIndex == 2,
+              onTap: () => _switchNav(2),
+            ),
+            _NavItem(
+              icon: Icons.build_outlined,
+              label: '工具',
+              active: _navIndex == 3,
+              onTap: () => _switchNav(3),
+            ),
+            const Spacer(),
+            // 下载状态指示
+            AnimatedBuilder(
+              animation: DownloadManager.instance,
+              builder: (context, _) {
+                final dm = DownloadManager.instance;
+                final task = dm.activeTask;
+                if (task == null) return const SizedBox.shrink();
+                if (task.finished) {
+                  return GestureDetector(
+                    onTap: () => showDownloadDialog(context),
+                    child: Container(
+                      padding: const EdgeInsets.symmetric(
+                          horizontal: 10, vertical: 4),
+                      decoration: BoxDecoration(
+                        color: AppColors.green.withOpacity(0.15),
+                        borderRadius: BorderRadius.circular(4),
+                      ),
+                      child: const Text('下载完成',
+                          style: TextStyle(
+                              color: AppColors.green, fontSize: 12)),
+                    ),
+                  );
+                }
+                return GestureDetector(
+                  onTap: () => showDownloadDialog(context),
+                  child: Container(
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 10, vertical: 4),
+                    decoration: BoxDecoration(
+                      color: AppColors.accent.withOpacity(0.15),
+                      borderRadius: BorderRadius.circular(4),
+                    ),
+                    child: Text(
+                      task.paused
+                          ? '已暂停 ${(task.progress * 100).toStringAsFixed(0)}%'
+                          : '${(task.progress * 100).toStringAsFixed(0)}%',
+                      style: const TextStyle(
+                          color: AppColors.accent, fontSize: 12),
+                    ),
+                  ),
+                );
+              },
+            ),
+            const SizedBox(width: 16),
+            // 用户信息
+            _UserMenu(),
+            const SizedBox(width: 14),
+            // 问题按钮
+            const Icon(Icons.help_outline,
+                size: 18, color: AppColors.textGray),
+            const SizedBox(width: 8),
+            // 更多菜单
+            const _MoreMenu(),
+            const SizedBox(width: 4),
+            const WindowControls(),
+          ],
+        ),
+      ),
+    );
+  }
+}
+
+class _NavItem extends StatelessWidget {
+  final IconData icon;
+  final String label;
+  final bool active;
+  final VoidCallback onTap;
+  const _NavItem({
+    required this.icon,
+    required this.label,
+    required this.active,
+    required this.onTap,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return InkWell(
+      onTap: onTap,
+      borderRadius: BorderRadius.circular(6),
+      child: Container(
+        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
+        decoration: BoxDecoration(
+          color: active ? AppColors.accent.withOpacity(0.15) : null,
+          borderRadius: BorderRadius.circular(6),
+        ),
+        child: Row(
+          children: [
+            Icon(icon,
+                size: 18,
+                color: active ? AppColors.accent : AppColors.textGray),
+            const SizedBox(width: 6),
+            Text(label,
+                style: TextStyle(
+                    color: active ? AppColors.accent : AppColors.textGray,
+                    fontSize: 14,
+                    fontWeight: active ? FontWeight.w500 : FontWeight.normal)),
+          ],
+        ),
+      ),
+    );
+  }
+}
+
+/// 用户头像 + 会员信息悬浮
+class _UserMenu extends StatefulWidget {
+  @override
+  State<_UserMenu> createState() => _UserMenuState();
+}
+
+class _UserMenuState extends State<_UserMenu> {
+  final LayerLink _layerLink = LayerLink();
+  OverlayEntry? _entry;
+
+  void _toggle() {
+    if (_entry != null) {
+      _remove();
+    } else {
+      _show();
+    }
+  }
+
+  void _remove() {
+    _entry?.remove();
+    _entry = null;
+  }
+
+  void _show() {
+    final app = AppState.instance;
+    _entry = OverlayEntry(
+      builder: (context) => Stack(
+        children: [
+          GestureDetector(
+            behavior: HitTestBehavior.opaque,
+            onTap: _remove,
+            child: Container(color: Colors.transparent),
+          ),
+          CompositedTransformFollower(
+            link: _layerLink,
+            targetAnchor: Alignment.bottomCenter,
+            followerAnchor: Alignment.topCenter,
+            offset: const Offset(0, 8),
+            child: Material(
+              color: Colors.transparent,
+              child: Container(
+                width: 240,
+                padding: const EdgeInsets.all(16),
+                decoration: BoxDecoration(
+                  color: const Color(0xFF232739),
+                  borderRadius: BorderRadius.circular(8),
+                  border: Border.all(color: AppColors.bgLighter),
+                  boxShadow: [
+                    BoxShadow(
+                        color: Colors.black.withOpacity(0.5), blurRadius: 16)
+                  ],
+                ),
+                child: Column(
+                  crossAxisAlignment: CrossAxisAlignment.start,
+                  mainAxisSize: MainAxisSize.min,
+                  children: [
+                    Row(
+                      children: [
+                        Text('No.${app.userId}',
+                            style: const TextStyle(
+                                color: Colors.white,
+                                fontSize: 15,
+                                fontWeight: FontWeight.bold)),
+                        const SizedBox(width: 8),
+                        if (app.isMember)
+                          Container(
+                            padding: const EdgeInsets.symmetric(
+                                horizontal: 6, vertical: 2),
+                            decoration: BoxDecoration(
+                              color: AppColors.red,
+                              borderRadius: BorderRadius.circular(3),
+                            ),
+                            child: const Text('VIP会员',
+                                style: TextStyle(
+                                    color: Colors.white, fontSize: 10)),
+                          ),
+                      ],
+                    ),
+                    const SizedBox(height: 8),
+                    Text(
+                      app.isMember
+                          ? '到期时间:${app.memberExpire.split(' ').first}'
+                          : '您还不是会员,请激活密钥',
+                      style: TextStyle(
+                          color: app.isMember
+                              ? AppColors.textGray
+                              : AppColors.yellow,
+                          fontSize: 13),
+                    ),
+                    const SizedBox(height: 12),
+                    SizedBox(
+                      width: double.infinity,
+                      height: 34,
+                      child: ElevatedButton(
+                        onPressed: () {
+                          _remove();
+                          showActivateDialog(context);
+                        },
+                        style: ElevatedButton.styleFrom(
+                          backgroundColor: AppColors.accent,
+                          foregroundColor: Colors.white,
+                          elevation: 0,
+                        ),
+                        child: const Text('会员激活', style: TextStyle(fontSize: 13)),
+                      ),
+                    ),
+                    const Divider(color: AppColors.bgLighter, height: 24),
+                    SizedBox(
+                      width: double.infinity,
+                      height: 34,
+                      child: OutlinedButton(
+                        onPressed: () {
+                          _remove();
+                          AppState.instance.logout();
+                        },
+                        style: OutlinedButton.styleFrom(
+                          foregroundColor: AppColors.textGray,
+                          side: const BorderSide(color: AppColors.bgLighter),
+                        ),
+                        child: const Text('退出登录', style: TextStyle(fontSize: 13)),
+                      ),
+                    ),
+                  ],
+                ),
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+    Overlay.of(context).insert(_entry!);
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return CompositedTransformTarget(
+      link: _layerLink,
+      child: GestureDetector(
+        onTap: _toggle,
+        child: Row(
+          children: [
+            ClipOval(
+              child: Image.asset('assets/images/logo.png',
+                  width: 26,
+                  height: 26,
+                  fit: BoxFit.cover,
+                  errorBuilder: (_, __, ___) => Container(
+                      width: 26,
+                      height: 26,
+                      color: AppColors.pink,
+                      child: const Center(
+                          child: Text('99',
+                              style: TextStyle(
+                                  color: Colors.white, fontSize: 10))))),
+            ),
+            const SizedBox(width: 6),
+            Text(
+              'No.${AppState.instance.userId}',
+              style: const TextStyle(color: AppColors.textGray, fontSize: 13),
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+}
+
+/// 右上角"更多"下拉菜单
+class _MoreMenu extends StatefulWidget {
+  const _MoreMenu();
+  @override
+  State<_MoreMenu> createState() => _MoreMenuState();
+}
+
+class _MoreMenuState extends State<_MoreMenu> {
+  final LayerLink _layerLink = LayerLink();
+  OverlayEntry? _entry;
+
+  void _toggle() {
+    if (_entry != null) {
+      _remove();
+    } else {
+      _show();
+    }
+  }
+
+  void _remove() {
+    _entry?.remove();
+    _entry = null;
+  }
+
+  void _show() {
+    const menus = [
+      ('电脑设备配置', Icons.computer),
+      ('电脑网络信息', Icons.wifi),
+      ('下载安装路径', Icons.folder_open),
+      ('打开下载目录', Icons.download),
+      ('打开安装目录', Icons.install_desktop),
+      ('游戏恢复', Icons.restore),
+      ('重启应用', Icons.restart_alt),
+      ('检查更新', Icons.update),
+      ('退出应用', Icons.power_settings_new),
+    ];
+    _entry = OverlayEntry(
+      builder: (context) => Stack(
+        children: [
+          GestureDetector(
+            behavior: HitTestBehavior.opaque,
+            onTap: _remove,
+            child: Container(color: Colors.transparent),
+          ),
+          CompositedTransformFollower(
+            link: _layerLink,
+            targetAnchor: Alignment.topRight,
+            followerAnchor: Alignment.topRight,
+            offset: const Offset(-4, 6),
+            child: Material(
+              color: Colors.transparent,
+              child: Container(
+                width: 170,
+                decoration: BoxDecoration(
+                  color: const Color(0xFF232739),
+                  borderRadius: BorderRadius.circular(8),
+                  border: Border.all(color: AppColors.bgLighter),
+                  boxShadow: [
+                    BoxShadow(
+                        color: Colors.black.withOpacity(0.5), blurRadius: 16)
+                  ],
+                ),
+                child: Column(
+                  mainAxisSize: MainAxisSize.min,
+                  children: menus
+                      .map((m) => InkWell(
+                            onTap: () {
+                              _remove();
+                              _onMenuTap(m.$1);
+                            },
+                            child: Padding(
+                              padding: const EdgeInsets.symmetric(
+                                  horizontal: 14, vertical: 10),
+                              child: Row(
+                                children: [
+                                  Icon(m.$2,
+                                      size: 16, color: AppColors.textGray),
+                                  const SizedBox(width: 10),
+                                  Text(m.$1,
+                                      style: const TextStyle(
+                                          color: AppColors.textWhite,
+                                          fontSize: 13)),
+                                ],
+                              ),
+                            ),
+                          ))
+                      .toList(),
+                ),
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+    Overlay.of(context).insert(_entry!);
+  }
+
+  Future<void> _onMenuTap(String name) async {
+    switch (name) {
+      case '电脑设备配置':
+        showDeviceConfigDialog(context);
+      case '电脑网络信息':
+        showNetworkInfoDialog(context);
+      case '下载安装路径':
+        showPathDialog(context);
+      case '打开下载目录':
+        _openDir(await _dir('download_path', '99GameD'));
+      case '打开安装目录':
+        _openDir(await _dir('install_path', '99GameI'));
+      case '游戏恢复':
+        _showToast('游戏恢复功能:重新下载可恢复游戏文件');
+      case '重启应用':
+        _showToast('应用重启中...');
+      case '检查更新':
+        _showToast('当前已是最新版本!');
+      case '退出应用':
+        exit(0);
+    }
+  }
+
+  void _showToast(String msg) {
+    final ctx = context;
+    // 使用全局 overlay 显示
+    final overlay = Overlay.maybeOf(ctx);
+    if (overlay == null) return;
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(ctx).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding:
+                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                const Icon(Icons.check_circle,
+                    color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(
+                          color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  Future<String> _dir(String key, String sub) async {
+    final sp = await SharedPreferencesUtil.get(key);
+    return sp.isNotEmpty ? sp : 'C:\\99GameBox\\$sub';
+  }
+
+  void _openDir(String path) async {
+    final dir = Directory(path);
+    if (!await dir.exists()) {
+      await dir.create(recursive: true);
+    }
+    Process.run('explorer.exe', [path]);
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return CompositedTransformTarget(
+      link: _layerLink,
+      child: GestureDetector(
+        onTap: _toggle,
+        child: Container(
+          padding: const EdgeInsets.all(6),
+          child: const Icon(Icons.menu, size: 18, color: AppColors.textGray),
+        ),
+      ),
+    );
+  }
+}
+
+class SharedPreferencesUtil {
+  static Future<String> get(String key) async {
+    final sp = await SharedPreferences.getInstance();
+    return sp.getString(key) ?? '';
+  }
+}
+
+/// 左侧浮动栏:系统公告/联系客服/常见问题
+class _LeftSidebar extends StatelessWidget {
+  const _LeftSidebar();
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      decoration: BoxDecoration(
+        color: const Color(0xFF191C2B).withOpacity(0.95),
+        borderRadius: const BorderRadius.horizontal(right: Radius.circular(8)),
+        border: Border.all(color: AppColors.bgLighter),
+      ),
+      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4),
+      child: Column(
+        mainAxisSize: MainAxisSize.min,
+        children: [
+          _sideIcon(context, Icons.campaign, '系统公告', () {
+            _showAnnouncement(context);
+          }),
+          const SizedBox(height: 14),
+          _sideIcon(context, Icons.support_agent, '联系客服', () {
+            _showToast2(context, '客服在线时间:早8点--晚10点');
+          }),
+          const SizedBox(height: 14),
+          _sideIcon(context, Icons.help_center_outlined, '常见问题', () {
+            _showToast2(context, '常见问题:右键游戏图片可打开安装目录');
+          }),
+        ],
+      ),
+    );
+  }
+
+  void _showAnnouncement(BuildContext context) async {
+    final res = await ApiClient.get('/api/announcements');
+    if (!context.mounted) return;
+    final content = res['code'] == 0 &&
+            (res['data'] as List).isNotEmpty
+        ? res['data'][0]['content']
+        : '暂无公告';
+    showDialog(
+      context: context,
+      builder: (context) => AlertDialog(
+        backgroundColor: Colors.white,
+        title: const Text('系统公告',
+            style: TextStyle(color: Colors.black, fontSize: 16)),
+        content: SizedBox(
+          width: 380,
+          child: Text('$content',
+              style:
+                  const TextStyle(color: Color(0xFFE74C3C), fontSize: 13, height: 1.9)),
+        ),
+        actions: [
+          TextButton(
+            onPressed: () => Navigator.pop(context),
+            child: const Text('知道了', style: TextStyle(color: Color(0xFF2B7FFF))),
+          ),
+        ],
+      ),
+    );
+  }
+
+  void _showToast2(BuildContext context, String msg) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                const Icon(Icons.check_circle, color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  Widget _sideIcon(
+      BuildContext context, IconData icon, String label, VoidCallback onTap) {
+    return InkWell(
+      onTap: onTap,
+      child: SizedBox(
+        width: 52,
+        child: Column(
+          children: [
+            Icon(icon, size: 20, color: AppColors.textGray),
+            const SizedBox(height: 4),
+            Text(label,
+                style: const TextStyle(
+                    color: AppColors.textGray, fontSize: 10)),
+          ],
+        ),
+      ),
+    );
+  }
+}
+
+/// 右侧浮动栏:我要投诉/会员激活
+class _RightSidebar extends StatelessWidget {
+  final VoidCallback onActivate;
+  const _RightSidebar({required this.onActivate});
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      decoration: BoxDecoration(
+        color: const Color(0xFF191C2B).withOpacity(0.95),
+        borderRadius: const BorderRadius.horizontal(left: Radius.circular(8)),
+        border: Border.all(color: AppColors.bgLighter),
+      ),
+      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4),
+      child: Column(
+        mainAxisSize: MainAxisSize.min,
+        children: [
+          _sideIcon(Icons.local_fire_department, '我要投诉', AppColors.red, () {
+            _toast(context, '投诉已记录,客服将在工作时间内联系您');
+          }),
+          const SizedBox(height: 14),
+          _sideIcon(Icons.card_giftcard, '会员激活', AppColors.yellow, onActivate),
+        ],
+      ),
+    );
+  }
+
+  void _toast(BuildContext context, String msg) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                const Icon(Icons.check_circle, color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  Widget _sideIcon(IconData icon, String label, Color color, VoidCallback onTap) {
+    return InkWell(
+      onTap: onTap,
+      child: SizedBox(
+        width: 52,
+        child: Column(
+          children: [
+            Icon(icon, size: 20, color: color),
+            const SizedBox(height: 4),
+            Text(label, style: TextStyle(color: color, fontSize: 10)),
+          ],
+        ),
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/pages/store_page.dart b/fluttergamebox/lib/pages/store_page.dart
new file mode 100644
index 0000000..0f93bfc
--- /dev/null
+++ b/fluttergamebox/lib/pages/store_page.dart
@@ -0,0 +1,436 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/pages/main_shell.dart';
+import 'package:fluttergamebox/widgets/game_card.dart';
+
+class StorePage extends StatefulWidget {
+  const StorePage({super.key});
+  @override
+  State<StorePage> createState() => StorePageState();
+}
+
+class StorePageState extends State<StorePage>
+    with AutomaticKeepAliveClientMixin {
+  List<Game> banners = [];
+  List<Game> games = [];
+  List<Category> categories = [];
+  int bannerIndex = 0;
+  Timer? _bannerTimer;
+
+  String platform = 'all'; // all / pc / switch
+  int category = 0;
+  String keyword = '';
+  String sort = 'updated';
+  final _searchCtrl = TextEditingController();
+  bool _loading = true;
+
+  @override
+  bool get wantKeepAlive => true;
+
+  @override
+  void initState() {
+    super.initState();
+    _load();
+  }
+
+  @override
+  void dispose() {
+    _bannerTimer?.cancel();
+    super.dispose();
+  }
+
+  Future<void> _load() async {
+    final b = await ApiService.banners();
+    final c = await ApiService.categories();
+    if (!mounted) return;
+    setState(() {
+      banners = b;
+      categories = c.where((e) => e.name != '常用工具').toList();
+    });
+    _bannerTimer?.cancel();
+    if (banners.length > 1) {
+      _bannerTimer = Timer.periodic(const Duration(seconds: 6), (_) {
+        if (mounted) {
+          setState(() => bannerIndex = (bannerIndex + 1) % banners.length);
+        }
+      });
+    }
+    await _reloadGames();
+  }
+
+  Future<void> _reloadGames() async {
+    setState(() => _loading = true);
+    final g = await ApiService.games(
+        platform: platform,
+        category: category,
+        keyword: keyword,
+        sort: sort);
+    if (mounted) {
+      setState(() {
+        games = g;
+        _loading = false;
+      });
+    }
+  }
+
+  /// 供主Shell在详情页关闭后刷新(更新"添加"按钮状态等)
+  void refresh() => _reloadGames();
+
+  @override
+  Widget build(BuildContext context) {
+    super.build(context);
+    return Container(
+      color: AppColors.bg,
+      child: SingleChildScrollView(
+        child: Column(
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: [
+            if (banners.isNotEmpty) _buildBanner(),
+            _buildFilters(),
+            _buildGrid(),
+            const SizedBox(height: 40),
+          ],
+        ),
+      ),
+    );
+  }
+
+  Widget _buildBanner() {
+    final game = banners[bannerIndex];
+    return Padding(
+      padding: const EdgeInsets.fromLTRB(70, 12, 70, 0),
+      child: Column(
+        children: [
+          GestureDetector(
+            onTap: () => _openDetail(game),
+            child: ClipRRect(
+              borderRadius: BorderRadius.circular(8),
+              child: SizedBox(
+                height: 280,
+                width: double.infinity,
+                child: Stack(
+                  fit: StackFit.expand,
+                  children: [
+                    Image.network(
+                      ApiClient.baseUrl + game.cover,
+                      fit: BoxFit.cover,
+                      errorBuilder: (_, __, ___) => Container(
+                        color: const Color(0xFF2A2E45),
+                        child: Center(
+                          child: Text(game.title,
+                              style: const TextStyle(
+                                  color: AppColors.textDim, fontSize: 24)),
+                        ),
+                      ),
+                    ),
+                    Container(
+                      decoration: BoxDecoration(
+                        gradient: LinearGradient(
+                          begin: Alignment.centerLeft,
+                          end: Alignment.center,
+                          colors: [
+                            Colors.black.withOpacity(0.75),
+                            Colors.transparent,
+                          ],
+                        ),
+                      ),
+                    ),
+                    Padding(
+                      padding: const EdgeInsets.all(30),
+                      child: Column(
+                        crossAxisAlignment: CrossAxisAlignment.start,
+                        children: [
+                          const Spacer(),
+                          SizedBox(
+                            width: 420,
+                            child: Text(game.title,
+                                maxLines: 2,
+                                overflow: TextOverflow.ellipsis,
+                                style: const TextStyle(
+                                    color: Colors.white,
+                                    fontSize: 26,
+                                    fontWeight: FontWeight.bold,
+                                    shadows: [
+                                      Shadow(color: Colors.black, blurRadius: 8)
+                                    ])),
+                          ),
+                          const SizedBox(height: 10),
+                          Text(game.versionNote,
+                              maxLines: 1,
+                              overflow: TextOverflow.ellipsis,
+                              style: const TextStyle(
+                                  color: Colors.white70, fontSize: 13)),
+                          const SizedBox(height: 14),
+                          Row(
+                            children: [
+                              _bannerTag(game.platformLabel),
+                              const SizedBox(width: 8),
+                              _bannerTag(game.size),
+                            ],
+                          ),
+                        ],
+                      ),
+                    ),
+                  ],
+                ),
+              ),
+            ),
+          ),
+          const SizedBox(height: 8),
+          Row(
+            children: [
+              for (var i = 0; i < banners.length; i++)
+                GestureDetector(
+                  onTap: () => setState(() => bannerIndex = i),
+                  child: Container(
+                    width: 110,
+                    margin: const EdgeInsets.only(right: 8),
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 8, vertical: 6),
+                    decoration: BoxDecoration(
+                      color: i == bannerIndex
+                          ? AppColors.bgLight
+                          : Colors.transparent,
+                      borderRadius: BorderRadius.circular(4),
+                      border: Border(
+                        bottom: BorderSide(
+                          width: 2,
+                          color: i == bannerIndex
+                              ? AppColors.accent
+                              : Colors.transparent,
+                        ),
+                      ),
+                    ),
+                    child: Text(banners[i].title,
+                        maxLines: 1,
+                        overflow: TextOverflow.ellipsis,
+                        style: TextStyle(
+                            color: i == bannerIndex
+                                ? Colors.white
+                                : AppColors.textDim,
+                            fontSize: 12)),
+                  ),
+                ),
+            ],
+          ),
+        ],
+      ),
+    );
+  }
+
+  Widget _bannerTag(String text) {
+    return Container(
+      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
+      decoration: BoxDecoration(
+        color: AppColors.accent,
+        borderRadius: BorderRadius.circular(3),
+      ),
+      child: Text(text,
+          style: const TextStyle(color: Colors.white, fontSize: 11)),
+    );
+  }
+
+  Widget _buildFilters() {
+    return Padding(
+      padding: const EdgeInsets.fromLTRB(70, 16, 70, 12),
+      child: Column(
+        children: [
+          Row(
+            children: [
+              _tab('全部资源', platform == 'all'),
+              const SizedBox(width: 20),
+              _tab('单机资源', platform == 'pc'),
+              const SizedBox(width: 20),
+              _tab('Switch资源', platform == 'switch'),
+              const Spacer(),
+              _CategoryDropdown(
+                categories: categories,
+                value: category,
+                onChanged: (v) {
+                  setState(() => category = v ?? 0);
+                  _reloadGames();
+                },
+              ),
+              const SizedBox(width: 10),
+              SizedBox(
+                width: 200,
+                height: 32,
+                child: TextField(
+                  controller: _searchCtrl,
+                  onSubmitted: (v) {
+                    keyword = v;
+                    _reloadGames();
+                  },
+                  style: const TextStyle(color: Colors.white, fontSize: 13),
+                  decoration: InputDecoration(
+                    hintText: '输入关键字',
+                    hintStyle: const TextStyle(
+                        color: AppColors.textDim, fontSize: 12),
+                    prefixIcon: const Icon(Icons.search,
+                        size: 16, color: AppColors.textGray),
+                    filled: true,
+                    fillColor: AppColors.bgLight,
+                    contentPadding: EdgeInsets.zero,
+                    border: OutlineInputBorder(
+                      borderRadius: BorderRadius.circular(4),
+                      borderSide: BorderSide.none,
+                    ),
+                  ),
+                ),
+              ),
+            ],
+          ),
+          const SizedBox(height: 10),
+          Row(
+            children: [
+              _sortItem('最新更新', 'updated', Icons.update),
+              const SizedBox(width: 24),
+              _sortItem('安装排行', 'rank', Icons.bar_chart),
+              const SizedBox(width: 24),
+              _sortItem('安装大小', 'size', Icons.sd_storage),
+              const SizedBox(width: 24),
+              _sortItem('热门大作', 'hot', Icons.local_fire_department),
+            ],
+          ),
+        ],
+      ),
+    );
+  }
+
+  Widget _tab(String label, bool active) {
+    return GestureDetector(
+      onTap: () {
+        setState(() {
+          platform = label == '单机资源'
+              ? 'pc'
+              : label == 'Switch资源'
+                  ? 'switch'
+                  : 'all';
+        });
+        _reloadGames();
+      },
+      child: Container(
+        padding: const EdgeInsets.symmetric(vertical: 6),
+        decoration: BoxDecoration(
+          border: Border(
+            bottom: BorderSide(
+                width: 2,
+                color: active ? AppColors.accent : Colors.transparent),
+          ),
+        ),
+        child: Text(label,
+            style: TextStyle(
+                color: active ? Colors.white : AppColors.textGray,
+                fontSize: 14,
+                fontWeight: active ? FontWeight.w500 : FontWeight.normal)),
+      ),
+    );
+  }
+
+  Widget _sortItem(String label, String key, IconData icon) {
+    final active = sort == key;
+    return GestureDetector(
+      onTap: () {
+        setState(() => sort = key);
+        _reloadGames();
+      },
+      child: Row(
+        children: [
+          Icon(icon,
+              size: 14,
+              color: active ? AppColors.accent : AppColors.textDim),
+          const SizedBox(width: 4),
+          Text(label,
+              style: TextStyle(
+                  color: active ? AppColors.accent : AppColors.textDim,
+                  fontSize: 12)),
+        ],
+      ),
+    );
+  }
+
+  Widget _buildGrid() {
+    if (_loading) {
+      return const SizedBox(
+        height: 300,
+        child: Center(
+          child: CircularProgressIndicator(color: AppColors.accent),
+        ),
+      );
+    }
+    if (games.isEmpty) {
+      return const SizedBox(
+        height: 300,
+        child: Center(
+          child: Text('暂无游戏资源',
+              style: TextStyle(color: AppColors.textGray)),
+        ),
+      );
+    }
+    return Padding(
+      padding: const EdgeInsets.symmetric(horizontal: 70),
+      child: GridView.builder(
+        shrinkWrap: true,
+        physics: const NeverScrollableScrollPhysics(),
+        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+          crossAxisCount: 4,
+          mainAxisSpacing: 18,
+          crossAxisSpacing: 16,
+          childAspectRatio: 0.62,
+        ),
+        itemCount: games.length,
+        itemBuilder: (context, i) => GameCard(game: games[i]),
+      ),
+    );
+  }
+
+  void _openDetail(Game game) {
+    // 通过主Shell打开详情页,保留首页顶部导航栏
+    ShellNav.instance.openDetail?.call(game.id);
+  }
+}
+
+class _CategoryDropdown extends StatelessWidget {
+  final List<Category> categories;
+  final int value;
+  final ValueChanged<int?> onChanged;
+  const _CategoryDropdown({
+    required this.categories,
+    required this.value,
+    required this.onChanged,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      height: 32,
+      padding: const EdgeInsets.symmetric(horizontal: 12),
+      decoration: BoxDecoration(
+        color: AppColors.bgLight,
+        borderRadius: BorderRadius.circular(4),
+      ),
+      child: DropdownButtonHideUnderline(
+        child: DropdownButton<int>(
+          value: value,
+          dropdownColor: const Color(0xFF232739),
+          style: const TextStyle(color: AppColors.textWhite, fontSize: 13),
+          icon: const Icon(Icons.arrow_drop_down,
+              size: 18, color: AppColors.textGray),
+          items: [
+            const DropdownMenuItem(
+                value: 0,
+                child: Text('全部类别',
+                    style: TextStyle(color: AppColors.textGray))),
+            ...categories
+                .map((c) => DropdownMenuItem(value: c.id, child: Text(c.name))),
+          ],
+          onChanged: onChanged,
+        ),
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/pages/tools_page.dart b/fluttergamebox/lib/pages/tools_page.dart
new file mode 100644
index 0000000..81d01d4
--- /dev/null
+++ b/fluttergamebox/lib/pages/tools_page.dart
@@ -0,0 +1,244 @@
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/util.dart';
+import 'package:fluttergamebox/widgets/download_manager.dart';
+
+class ToolsPage extends StatefulWidget {
+  const ToolsPage({super.key});
+  @override
+  State<ToolsPage> createState() => _ToolsPageState();
+}
+
+class _ToolsPageState extends State<ToolsPage>
+    with AutomaticKeepAliveClientMixin {
+  List<Tool> tools = [];
+  final Set<int> _installed = {};
+  bool _loading = true;
+
+  @override
+  bool get wantKeepAlive => true;
+
+  @override
+  void initState() {
+    super.initState();
+    _load();
+  }
+
+  Future<void> _load() async {
+    final t = await ApiService.tools();
+    if (!mounted) return;
+    setState(() {
+      tools = t;
+      _loading = false;
+    });
+  }
+
+  Future<void> _install(Tool tool) async {
+    if (_installed.contains(tool.id)) return;
+    // 模拟安装
+    setState(() => _installed.add(tool.id));
+    _toast('${tool.name} 安装完成');
+  }
+
+  void _toast(String msg) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding:
+                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                const Icon(Icons.check_circle,
+                    color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(
+                          color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    super.build(context);
+    return Container(
+      color: AppColors.bg,
+      padding: const EdgeInsets.fromLTRB(70, 20, 70, 0),
+      child: Column(
+        crossAxisAlignment: CrossAxisAlignment.start,
+        children: [
+          Row(
+            children: [
+              const Icon(Icons.build_outlined,
+                  color: AppColors.accent, size: 18),
+              const SizedBox(width: 8),
+              const Text('常用工具',
+                  style: TextStyle(
+                      color: Colors.white,
+                      fontSize: 16,
+                      fontWeight: FontWeight.w500)),
+              const SizedBox(width: 12),
+              const Text('游戏必备运行库和实用工具',
+                  style: TextStyle(
+                      color: AppColors.textGray, fontSize: 13)),
+            ],
+          ),
+          const SizedBox(height: 16),
+          Expanded(
+            child: _loading
+                ? const Center(
+                    child:
+                        CircularProgressIndicator(color: AppColors.accent))
+                : tools.isEmpty
+                    ? const Center(
+                        child: Text('暂无工具',
+                            style:
+                                TextStyle(color: AppColors.textGray)))
+                    : GridView.builder(
+                        padding: const EdgeInsets.only(bottom: 40),
+                        gridDelegate:
+                            const SliverGridDelegateWithFixedCrossAxisCount(
+                          crossAxisCount: 4,
+                          mainAxisSpacing: 18,
+                          crossAxisSpacing: 16,
+                          childAspectRatio: 0.72,
+                        ),
+                        itemCount: tools.length,
+                        itemBuilder: (context, i) =>
+                            _ToolCard(tool: tools[i], installed: _installed.contains(tools[i].id), onInstall: () => _install(tools[i])),
+                      ),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _ToolCard extends StatelessWidget {
+  final Tool tool;
+  final bool installed;
+  final VoidCallback onInstall;
+  const _ToolCard({
+    required this.tool,
+    required this.installed,
+    required this.onInstall,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return Container(
+      decoration: BoxDecoration(
+        color: AppColors.bgLight,
+        borderRadius: BorderRadius.circular(6),
+      ),
+      child: Column(
+        children: [
+          // 封面
+          Expanded(
+            child: Stack(
+              fit: StackFit.expand,
+              children: [
+                ClipRRect(
+                  borderRadius: const BorderRadius.vertical(
+                      top: Radius.circular(6)),
+                  child: Image.network(
+                    ApiClient.baseUrl + tool.cover,
+                    fit: BoxFit.cover,
+                    errorBuilder: (_, __, ___) => Container(
+                      color: const Color(0xFF2A2E45),
+                      child: Center(
+                        child: Text(
+                          tool.name.characters.first,
+                          style: const TextStyle(
+                              color: AppColors.textDim, fontSize: 28),
+                        ),
+                      ),
+                    ),
+                  ),
+                ),
+                // 常用工具标签
+                Positioned(
+                  left: 0,
+                  top: 8,
+                  child: Container(
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 8, vertical: 3),
+                    decoration: const BoxDecoration(
+                      color: AppColors.accent,
+                      borderRadius: BorderRadius.horizontal(
+                          right: Radius.circular(3)),
+                    ),
+                    child: const Text('常用工具',
+                        style: TextStyle(
+                            color: Colors.white, fontSize: 11)),
+                  ),
+                ),
+              ],
+            ),
+          ),
+          // 信息
+          Padding(
+            padding: const EdgeInsets.all(10),
+            child: Column(
+              children: [
+                Text(tool.description,
+                    maxLines: 1,
+                    overflow: TextOverflow.ellipsis,
+                    style: const TextStyle(
+                        color: Colors.white, fontSize: 12)),
+                const SizedBox(height: 8),
+                Row(
+                  children: [
+                    Text(tool.size,
+                        style: const TextStyle(
+                            color: AppColors.textDim, fontSize: 11)),
+                    const Spacer(),
+                    GestureDetector(
+                      onTap: onInstall,
+                      child: Container(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 14, vertical: 4),
+                        decoration: BoxDecoration(
+                          color: installed
+                              ? const Color(0xFF3A3F52)
+                              : AppColors.accent,
+                          borderRadius: BorderRadius.circular(3),
+                        ),
+                        child: Text(
+                          installed ? '已安装' : '安装',
+                          style: const TextStyle(
+                              color: Colors.white, fontSize: 11),
+                        ),
+                      ),
+                    ),
+                  ],
+                ),
+              ],
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/store/app_state.dart b/fluttergamebox/lib/store/app_state.dart
new file mode 100644
index 0000000..9616185
--- /dev/null
+++ b/fluttergamebox/lib/store/app_state.dart
@@ -0,0 +1,327 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:dio/dio.dart';
+import 'package:flutter/foundation.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/utils/util.dart';
+
+class AppState extends ChangeNotifier {
+  bool loggedIn = false;
+  int userId = 0;
+  String phone = '';
+  bool isMember = false;
+  String memberExpire = '';
+
+  /// 数据版本号:收藏/资源库变化时递增,页面监听后刷新
+  int favoritesVersion = 0;
+  int libraryVersion = 0;
+
+  static final AppState instance = AppState();
+
+  void bumpFavorites() {
+    favoritesVersion++;
+    notifyListeners();
+  }
+
+  void bumpLibrary() {
+    libraryVersion++;
+    notifyListeners();
+  }
+
+  Future<void> refreshUserInfo() async {
+    try {
+      final res = await ApiService.userInfo();
+      if (res['code'] == 0) {
+        final d = res['data'];
+        loggedIn = true;
+        userId = d['id'];
+        phone = d['phone'];
+        final member = d['member'] ?? {};
+        isMember = member['is_member'] == true;
+        memberExpire = member['expire_at'] ?? '';
+        notifyListeners();
+      } else {
+        logout();
+      }
+    } catch (_) {
+      // 网络错误保持现状
+    }
+  }
+
+  void logout() {
+    loggedIn = false;
+    userId = 0;
+    phone = '';
+    isMember = false;
+    memberExpire = '';
+    ApiClient.clearToken();
+    DownloadManager.instance.clear();
+    notifyListeners();
+  }
+}
+
+enum DownloadStatus { waiting, preparing, downloading, paused, done, failed }
+
+class DownloadTaskFile {
+  final String name;
+  final String url;
+  double totalBytes;
+  double received = 0;
+  DownloadStatus status = DownloadStatus.waiting;
+  CancelToken? cancelToken;
+  DownloadTaskFile(
+      {required this.name, required this.url, required this.totalBytes});
+
+  double get progress => totalBytes > 0 ? received / totalBytes : 0;
+}
+
+class DownloadTask {
+  final int gameId;
+  final String title;
+  final List<DownloadTaskFile> files;
+  double speed = 0; // bytes/s
+  bool autoShutdown = false;
+  bool paused = false;
+  bool finished = false;
+  bool canceled = false;
+  DateTime? startTime;
+
+  DownloadTask(
+      {required this.gameId,
+      required this.title,
+      required List<DownloadTaskFile> files})
+      : files = files;
+
+  double get totalBytes =>
+      files.fold(0, (sum, f) => sum + f.totalBytes);
+  double get receivedBytes =>
+      files.fold(0, (sum, f) => sum + f.received);
+
+  double get progress {
+    final total = totalBytes;
+    return total > 0 ? receivedBytes / total : 0;
+  }
+
+  int get etaSeconds {
+    if (speed <= 0) return 0;
+    final remain = totalBytes - receivedBytes;
+    if (remain <= 0) return 0;
+    return (remain / speed).round();
+  }
+}
+
+class DownloadManager extends ChangeNotifier {
+  static final DownloadManager instance = DownloadManager._();
+  DownloadManager._();
+
+  final List<DownloadTask> tasks = [];
+  DownloadTask? activeTask;
+  bool _loopRunning = false;
+
+  bool get hasActive => activeTask != null && !activeTask!.finished;
+
+  void clear() {
+    activeTask?.canceled = true;
+    tasks.clear();
+    activeTask = null;
+    notifyListeners();
+  }
+
+  Future<void> startDownload(Game game) async {
+    // 获取下载文件列表(服务端校验会员)
+    final res = await ApiService.downloadInfo(game.id);
+    if (res['code'] != 0) {
+      throw res['msg'] ?? '获取下载信息失败';
+    }
+    final List<dynamic> fileList = _parseFiles(res['data']['files']);
+    final dlPath = await AppPrefs.getDownloadPath();
+    if (dlPath.isEmpty) {
+      throw '请先在右上角菜单中设置下载安装路径';
+    }
+    // 没有文件的游戏:创建占位文件任务(演示下载流程)
+    final tasks = <DownloadTaskFile>[];
+    if (fileList.isEmpty) {
+      final demoSize = _parseSizeToBytes(game.size);
+      tasks.add(DownloadTaskFile(
+          name: '${game.title}.part01.rar',
+          url: '',
+          totalBytes: demoSize));
+    } else {
+      for (final f in fileList) {
+        tasks.add(DownloadTaskFile(
+            name: f['name'] ?? 'file',
+            url: f['url'] ?? '',
+            totalBytes: _parseSizeToBytes(f['size'] ?? '0 B')));
+      }
+    }
+    final task = DownloadTask(
+        gameId: game.id, title: game.title, files: tasks);
+    this.tasks.insert(0, task);
+    activeTask = task;
+    notifyListeners();
+    _runLoop();
+  }
+
+  /// 服务端files字段为JSON字符串或数组,统一解析为List
+  List<dynamic> _parseFiles(dynamic raw) {
+    if (raw is List) return raw;
+    if (raw is String && raw.trim().isNotEmpty) {
+      try {
+        final d = jsonDecode(raw);
+        if (d is List) return d;
+      } catch (_) {}
+    }
+    return [];
+  }
+
+  double _parseSizeToBytes(String s) {
+    final m = RegExp(r'([\d.]+)\s*(GB|MB|KB|B)').firstMatch(s.toUpperCase());
+    if (m == null) return 1024 * 1024 * 1024;
+    final v = double.parse(m.group(1)!);
+    switch (m.group(2)) {
+      case 'GB':
+        return v * 1024 * 1024 * 1024;
+      case 'MB':
+        return v * 1024 * 1024;
+      case 'KB':
+        return v * 1024;
+      default:
+        return v;
+    }
+  }
+
+  void pause() {
+    if (activeTask == null) return;
+    activeTask!.paused = true;
+    activeTask!.speed = 0;
+    for (final f in activeTask!.files) {
+      if (f.status == DownloadStatus.downloading ||
+          f.status == DownloadStatus.preparing) {
+        f.status = DownloadStatus.paused;
+      }
+      f.cancelToken?.cancel('paused');
+    }
+    notifyListeners();
+  }
+
+  void resume() {
+    if (activeTask == null) return;
+    activeTask!.paused = false;
+    _runLoop();
+    notifyListeners();
+  }
+
+  void cancelTask() {
+    if (activeTask == null) return;
+    activeTask!.canceled = true;
+    for (final f in activeTask!.files) {
+      f.cancelToken?.cancel('canceled');
+    }
+    activeTask = null;
+    notifyListeners();
+  }
+
+  void _runLoop() async {
+    if (_loopRunning) return;
+    _loopRunning = true;
+    try {
+      final task = activeTask!;
+      task.startTime = DateTime.now();
+      final dlPath = await AppPrefs.getDownloadPath();
+      final dir = Directory('$dlPath\\${_safeName(task.title)}');
+      await dir.create(recursive: true);
+
+      for (final file in task.files) {
+        if (task.canceled || task.paused) break;
+        file.status = DownloadStatus.preparing;
+        notifyListeners();
+        await Future.delayed(const Duration(milliseconds: 300));
+        if (task.canceled || task.paused) break;
+
+        if (file.url.isEmpty) {
+          // 演示模式:模拟下载
+          await _simulateDownload(task, file);
+        } else {
+          await _downloadFile(task, file, '${dir.path}\\${file.name}');
+        }
+        if (task.canceled || task.paused) break;
+        file.status = DownloadStatus.done;
+        notifyListeners();
+      }
+      if (!task.canceled && !task.paused) {
+        task.finished = true;
+        notifyListeners();
+      }
+    } catch (e) {
+      debugLog('download loop error: $e');
+    } finally {
+      _loopRunning = false;
+      notifyListeners();
+    }
+  }
+
+  Future<void> _downloadFile(
+      DownloadTask task, DownloadTaskFile file, String savePath) async {
+    file.status = DownloadStatus.downloading;
+    file.cancelToken = CancelToken();
+    notifyListeners();
+    int lastReceived = 0;
+    DateTime lastTime = DateTime.now();
+    try {
+      await ApiClient.dio.download(
+        file.url,
+        savePath,
+        cancelToken: file.cancelToken,
+        onReceiveProgress: (count, total) {
+          if (total > 0) file.totalBytes = total.toDouble();
+          file.received = count.toDouble();
+          final now = DateTime.now();
+          final diff = now.difference(lastTime).inMilliseconds;
+          if (diff >= 500) {
+            task.speed =
+                (count - lastReceived) * 1000 / diff;
+            lastReceived = count;
+            lastTime = now;
+          }
+          notifyListeners();
+        },
+      );
+      task.speed = 0;
+      notifyListeners();
+    } on DioException catch (e) {
+      if (e.type == DioExceptionType.cancel) {
+        file.status = DownloadStatus.paused;
+      } else {
+        file.status = DownloadStatus.failed;
+      }
+      notifyListeners();
+      rethrow;
+    }
+  }
+
+  Future<void> _simulateDownload(
+      DownloadTask task, DownloadTaskFile file) async {
+    file.status = DownloadStatus.downloading;
+    notifyListeners();
+    const chunk = 1024 * 1024 * 4; // 每tick 4MB
+    final tickMs = 30;
+    while (file.received < file.totalBytes) {
+      if (task.canceled || task.paused) return;
+      await Future.delayed(Duration(milliseconds: tickMs));
+      // 模拟速度 ~100MB/s 波动
+      final speed = (90 + (file.name.hashCode % 20)) * 1024 * 1024.0;
+      file.received =
+          (file.received + speed * tickMs / 1000).clamp(0, file.totalBytes);
+      task.speed = speed;
+      notifyListeners();
+    }
+    task.speed = 0;
+    notifyListeners();
+  }
+
+  String _safeName(String s) =>
+      s.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_');
+}
diff --git a/fluttergamebox/lib/utils/util.dart b/fluttergamebox/lib/utils/util.dart
new file mode 100644
index 0000000..d6d07f4
--- /dev/null
+++ b/fluttergamebox/lib/utils/util.dart
@@ -0,0 +1,65 @@
+import 'dart:io';
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+/// 获取本机机器码(注册表 MachineGuid,失败则退化为稳定哈希)
+Future<String> getMachineCode() async {
+  try {
+    final result = Process.runSync('reg', [
+      'query',
+      r'HKLM\SOFTWARE\Microsoft\Cryptography',
+      '/v',
+      'MachineGuid'
+    ]);
+    final out = result.stdout.toString();
+    final m = RegExp(r'MachineGuid\s+REG_SZ\s+(\S+)').firstMatch(out);
+    if (m != null) return m.group(1)!;
+  } catch (_) {}
+  // 备选:主机名+用户名
+  final fallback = '${Platform.localHostname}-${Platform.environment['USERNAME'] ?? 'pc'}';
+  return fallback;
+}
+
+/// 本地持久化:下载/安装路径
+class AppPrefs {
+  static Future<String> getDownloadPath() async {
+    final sp = await SharedPreferences.getInstance();
+    return sp.getString('download_path') ?? '';
+  }
+
+  static Future<String> getInstallPath() async {
+    final sp = await SharedPreferences.getInstance();
+    return sp.getString('install_path') ?? '';
+  }
+
+  static Future<void> setPaths(String dl, String ins) async {
+    final sp = await SharedPreferences.getInstance();
+    await sp.setString('download_path', dl);
+    await sp.setString('install_path', ins);
+  }
+}
+
+/// 简单格式化字节数
+String formatBytes(double bytes) {
+  if (bytes >= 1024 * 1024 * 1024) {
+    return '${(bytes / 1024 / 1024 / 1024).toStringAsFixed(2)} GB';
+  }
+  if (bytes >= 1024 * 1024) {
+    return '${(bytes / 1024 / 1024).toStringAsFixed(2)} MB';
+  }
+  if (bytes >= 1024) return '${(bytes / 1024).toStringAsFixed(2)} KB';
+  return '${bytes.toStringAsFixed(0)} B';
+}
+
+/// 秒 -> HH:MM:SS
+String formatDuration(int seconds) {
+  final h = seconds ~/ 3600;
+  final m = (seconds % 3600) ~/ 60;
+  final s = seconds % 60;
+  String two(int n) => n.toString().padLeft(2, '0');
+  return '${two(h)}:${two(m)}:${two(s)}';
+}
+
+void debugLog(String msg) {
+  if (kDebugMode) print('[gamebox] $msg');
+}
diff --git a/fluttergamebox/lib/widgets/activate_dialog.dart b/fluttergamebox/lib/widgets/activate_dialog.dart
new file mode 100644
index 0000000..d17a6b4
--- /dev/null
+++ b/fluttergamebox/lib/widgets/activate_dialog.dart
@@ -0,0 +1,195 @@
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/util.dart';
+
+/// 会员激活弹窗
+void showActivateDialog(BuildContext context) {
+  showDialog(
+    context: context,
+    barrierColor: Colors.black54,
+    builder: (context) => const _ActivateDialog(),
+  );
+}
+
+class _ActivateDialog extends StatefulWidget {
+  const _ActivateDialog();
+  @override
+  State<_ActivateDialog> createState() => _ActivateDialogState();
+}
+
+class _ActivateDialogState extends State<_ActivateDialog> {
+  final _codeCtrl = TextEditingController();
+  bool _loading = false;
+
+  Future<void> _activate() async {
+    final code = _codeCtrl.text.trim();
+    if (code.isEmpty) {
+      _tip('请输入您的激活码!', error: true);
+      return;
+    }
+    setState(() => _loading = true);
+    try {
+      final machine = await getMachineCode();
+      final res = await ApiService.activateKey(code, machine);
+      if (!mounted) return;
+      if (res['code'] == 0) {
+        await AppState.instance.refreshUserInfo();
+        if (mounted) {
+          _tip(res['msg'] ?? '激活成功');
+          Future.delayed(const Duration(milliseconds: 1200), () {
+            if (mounted) Navigator.pop(context);
+          });
+        }
+      } else {
+        _tip(res['msg'] ?? '激活失败', error: true);
+      }
+    } catch (e) {
+      _tip('网络错误,请稍后重试', error: true);
+    } finally {
+      if (mounted) setState(() => _loading = false);
+    }
+  }
+
+  void _tip(String msg, {bool error = false}) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: error ? AppColors.red : AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                Icon(error ? Icons.error_outline : Icons.check_circle,
+                    color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Dialog(
+      backgroundColor: Colors.white,
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+      child: Container(
+        width: 400,
+        padding: const EdgeInsets.all(24),
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: [
+            Row(
+              children: [
+                Container(
+                  padding: const EdgeInsets.all(4),
+                  decoration: BoxDecoration(
+                    color: AppColors.accent,
+                    shape: BoxShape.circle,
+                  ),
+                  child: const Icon(Icons.vpn_key,
+                      color: Colors.white, size: 14),
+                ),
+                const SizedBox(width: 8),
+                const Text('会员激活',
+                    style: TextStyle(
+                        color: Colors.black,
+                        fontSize: 16,
+                        fontWeight: FontWeight.bold)),
+                const Spacer(),
+                GestureDetector(
+                  onTap: () => Navigator.pop(context),
+                  child: const Icon(Icons.close, color: Colors.grey, size: 18),
+                ),
+              ],
+            ),
+            const SizedBox(height: 18),
+            Container(
+              width: double.infinity,
+              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+              decoration: BoxDecoration(
+                color: const Color(0xFFE8F1FF),
+                borderRadius: BorderRadius.circular(4),
+              ),
+              child: const Text('请输入您的激活码!',
+                  style: TextStyle(
+                      color: Color(0xFF2B7FFF), fontSize: 13)),
+            ),
+            const SizedBox(height: 16),
+            const Text('激活码',
+                style: TextStyle(color: Color(0xFF666666), fontSize: 13)),
+            const SizedBox(height: 8),
+            TextField(
+              controller: _codeCtrl,
+              style: const TextStyle(color: Color(0xFF333333), fontSize: 14),
+              decoration: InputDecoration(
+                hintText: 'XXXX-XXXX-XXXX-XXXX (右键粘贴)',
+                hintStyle: const TextStyle(
+                    color: Color(0xFFAAAAAA), fontSize: 13),
+                border: OutlineInputBorder(
+                  borderRadius: BorderRadius.circular(4),
+                  borderSide: const BorderSide(color: Color(0xFFDDDDDD)),
+                ),
+                contentPadding:
+                    const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+              ),
+            ),
+            const SizedBox(height: 24),
+            Row(
+              children: [
+                Expanded(
+                  child: OutlinedButton(
+                    onPressed: () => Navigator.pop(context),
+                    style: OutlinedButton.styleFrom(
+                      foregroundColor: Color(0xFF666666),
+                      side: const BorderSide(color: Color(0xFFDDDDDD)),
+                      padding: const EdgeInsets.symmetric(vertical: 12),
+                    ),
+                    child: const Text('取消'),
+                  ),
+                ),
+                const SizedBox(width: 12),
+                Expanded(
+                  child: ElevatedButton(
+                    onPressed: _loading ? null : _activate,
+                    style: ElevatedButton.styleFrom(
+                      backgroundColor: AppColors.accent,
+                      foregroundColor: Colors.white,
+                      padding: const EdgeInsets.symmetric(vertical: 12),
+                    ),
+                    child: _loading
+                        ? const SizedBox(
+                            width: 16,
+                            height: 16,
+                            child: CircularProgressIndicator(
+                                strokeWidth: 2, color: Colors.white))
+                        : const Text('激活'),
+                  ),
+                ),
+              ],
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/widgets/auth_dialogs.dart b/fluttergamebox/lib/widgets/auth_dialogs.dart
new file mode 100644
index 0000000..4fbad2d
--- /dev/null
+++ b/fluttergamebox/lib/widgets/auth_dialogs.dart
@@ -0,0 +1,272 @@
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/pages/login_page.dart';
+
+/// 注册账号弹窗
+void showRegisterDialog(BuildContext context) {
+  showDialog(
+    context: context,
+    barrierColor: Colors.black54,
+    builder: (context) => const _AuthDialog(mode: 'register'),
+  );
+}
+
+/// 找回密码弹窗
+void showForgotDialog(BuildContext context) {
+  showDialog(
+    context: context,
+    barrierColor: Colors.black54,
+    builder: (context) => const _AuthDialog(mode: 'forgot'),
+  );
+}
+
+class _AuthDialog extends StatefulWidget {
+  final String mode;
+  const _AuthDialog({required this.mode});
+  @override
+  State<_AuthDialog> createState() => _AuthDialogState();
+}
+
+class _AuthDialogState extends State<_AuthDialog> {
+  final _formKey = GlobalKey<FormState>();
+  final phone = TextEditingController();
+  final pwd = TextEditingController();
+  final pwd2 = TextEditingController();
+  final captcha = TextEditingController();
+  String captchaId = '';
+  Image? captchaImage;
+  bool _loading = false;
+
+  bool get isRegister => widget.mode == 'register';
+
+  @override
+  void initState() {
+    super.initState();
+    _refreshCaptcha();
+  }
+
+  Future<void> _refreshCaptcha() async {
+    try {
+      final res = await ApiService.captcha();
+      if (res['code'] == 0) {
+        setState(() {
+          captchaId = res['data']['captcha_id'];
+          captchaImage = Image.network(
+            res['data']['captcha_image'],
+            width: double.infinity,
+            height: double.infinity,
+            fit: BoxFit.fill,
+          );
+        });
+      }
+    } catch (_) {}
+  }
+
+  Future<void> _submit() async {
+    if (phone.text.trim().isEmpty ||
+        pwd.text.isEmpty ||
+        pwd2.text.isEmpty ||
+        captcha.text.isEmpty) {
+      showToast(context, '请填写完整信息', error: true);
+      return;
+    }
+    if (pwd.text != pwd2.text) {
+      showToast(context, '两次输入的密码不一致', error: true);
+      return;
+    }
+    setState(() => _loading = true);
+    try {
+      final res = isRegister
+          ? await ApiService.register({
+              'phone': phone.text.trim(),
+              'password': pwd.text,
+              'confirm': pwd2.text,
+              'captcha_id': captchaId,
+              'captcha': captcha.text,
+            })
+          : await ApiService.resetPassword({
+              'phone': phone.text.trim(),
+              'password': pwd.text,
+              'confirm': pwd2.text,
+              'captcha_id': captchaId,
+              'captcha': captcha.text,
+            });
+      if (!mounted) return;
+      if (res['code'] == 0) {
+        showToast(context, res['msg'] ?? '操作成功');
+        Navigator.pop(context);
+      } else {
+        showToast(context, res['msg'] ?? '操作失败', error: true);
+        _refreshCaptcha();
+      }
+    } catch (e) {
+      if (mounted) showToast(context, '网络错误', error: true);
+    } finally {
+      if (mounted) setState(() => _loading = false);
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Dialog(
+      backgroundColor: const Color(0xFF1B1E2E),
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+      child: Container(
+        width: 380,
+        padding: const EdgeInsets.all(0),
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          children: [
+            // 标题栏
+            Container(
+              height: 42,
+              padding: const EdgeInsets.symmetric(horizontal: 14),
+              decoration: BoxDecoration(
+                color: const Color(0xFF151726),
+                borderRadius:
+                    const BorderRadius.vertical(top: Radius.circular(8)),
+              ),
+              child: Row(
+                children: [
+                  Icon(isRegister ? Icons.person_add_alt : Icons.lock_reset,
+                      size: 16, color: AppColors.textGray),
+                  const SizedBox(width: 8),
+                  Text(isRegister ? '注册账号' : '找回密码',
+                      style: const TextStyle(
+                          color: Colors.white, fontSize: 14)),
+                  const Spacer(),
+                  GestureDetector(
+                    onTap: () => Navigator.pop(context),
+                    child: const Icon(Icons.close,
+                        size: 16, color: AppColors.textGray),
+                  ),
+                ],
+              ),
+            ),
+            const Divider(color: Color(0xFF2A2E45), height: 1),
+            Padding(
+              padding: const EdgeInsets.all(24),
+              child: Column(
+                children: [
+                  // Logo
+                  ClipOval(
+                    child: Image.asset('assets/images/logo.png',
+                        width: 60,
+                        height: 60,
+                        fit: BoxFit.cover,
+                        errorBuilder: (_, __, ___) => Container(
+                            width: 60,
+                            height: 60,
+                            color: AppColors.pink,
+                            child: const Center(
+                                child: Text('99',
+                                    style: TextStyle(
+                                        color: Colors.white,
+                                        fontWeight: FontWeight.bold))))),
+                  ),
+                  const SizedBox(height: 24),
+                  _field(phone, '手机号', Icons.phone_iphone),
+                  const SizedBox(height: 14),
+                  _field(pwd, isRegister ? '密码' : '请输入新密码',
+                      Icons.lock_outline,
+                      obscure: true),
+                  const SizedBox(height: 14),
+                  _field(pwd2,
+                      isRegister ? '确认密码' : '请再次输入新密码',
+                      Icons.lock_outline,
+                      obscure: true),
+                  const SizedBox(height: 14),
+                  // 验证码
+                  Row(
+                    children: [
+                      Expanded(child: _field(captcha, '图形验证码', Icons.verified_outlined)),
+                      const SizedBox(width: 10),
+                      GestureDetector(
+                        onTap: _refreshCaptcha,
+                        child: Container(
+                          width: 110,
+                          height: 46,
+                          decoration: BoxDecoration(
+                            color: Colors.white,
+                            borderRadius: BorderRadius.circular(6),
+                          ),
+                          padding: const EdgeInsets.symmetric(
+                              horizontal: 6, vertical: 4),
+                          child: ClipRRect(
+                            borderRadius: BorderRadius.circular(3),
+                            child: captchaImage ??
+                                const Center(
+                                    child: Text('加载中...',
+                                        style: TextStyle(
+                                            color: Colors.grey,
+                                            fontSize: 11))),
+                          ),
+                        ),
+                      ),
+                    ],
+                  ),
+                  const SizedBox(height: 24),
+                  SizedBox(
+                    width: double.infinity,
+                    height: 46,
+                    child: ElevatedButton(
+                      onPressed: _loading ? null : _submit,
+                      style: ElevatedButton.styleFrom(
+                        backgroundColor: AppColors.accent,
+                        foregroundColor: Colors.white,
+                        elevation: 0,
+                        shape: RoundedRectangleBorder(
+                            borderRadius: BorderRadius.circular(6)),
+                      ),
+                      child: _loading
+                          ? const SizedBox(
+                              width: 18,
+                              height: 18,
+                              child: CircularProgressIndicator(
+                                  strokeWidth: 2, color: Colors.white))
+                          : Text(isRegister ? '注册' : '找回密码',
+                              style: const TextStyle(fontSize: 15)),
+                    ),
+                  ),
+                ],
+              ),
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+
+  Widget _field(TextEditingController ctrl, String hint, IconData icon,
+      {bool obscure = false}) {
+    return Container(
+      height: 46,
+      decoration: BoxDecoration(
+        color: Colors.white,
+        borderRadius: BorderRadius.circular(6),
+      ),
+      child: Row(
+        children: [
+          const SizedBox(width: 14),
+          Icon(icon, size: 18, color: const Color(0xFF9AA0B4)),
+          const SizedBox(width: 10),
+          Expanded(
+            child: TextField(
+              controller: ctrl,
+              obscureText: obscure,
+              style: const TextStyle(color: Color(0xFF333333), fontSize: 14),
+              decoration: InputDecoration(
+                hintText: hint,
+                hintStyle: const TextStyle(
+                    color: Color(0xFFAAAAAA), fontSize: 14),
+                border: InputBorder.none,
+                isDense: true,
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/widgets/download_manager.dart b/fluttergamebox/lib/widgets/download_manager.dart
new file mode 100644
index 0000000..724970c
--- /dev/null
+++ b/fluttergamebox/lib/widgets/download_manager.dart
@@ -0,0 +1,390 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/util.dart';
+import 'package:path/path.dart' as p;
+
+/// 下载管理弹窗(安装任务)
+void showDownloadDialog(BuildContext context) {
+  showDialog(
+    context: context,
+    barrierColor: Colors.black.withOpacity(0.6),
+    builder: (context) => const _DownloadDialog(),
+  );
+}
+
+class _DownloadDialog extends StatelessWidget {
+  const _DownloadDialog();
+  @override
+  Widget build(BuildContext context) {
+    return AnimatedBuilder(
+      animation: DownloadManager.instance,
+      builder: (context, _) {
+        final dm = DownloadManager.instance;
+        final task = dm.activeTask;
+        if (task == null) {
+          return Dialog(
+            backgroundColor: const Color(0xFF1E2130),
+            child: Container(
+              width: 560,
+              padding: const EdgeInsets.all(32),
+              child: const Column(
+                mainAxisSize: MainAxisSize.min,
+                children: [
+                  Icon(Icons.download_done, color: AppColors.textGray, size: 48),
+                  SizedBox(height: 16),
+                  Text('暂无下载任务',
+                      style: TextStyle(color: AppColors.textGray)),
+                ],
+              ),
+            ),
+          );
+        }
+        return Dialog(
+          backgroundColor: const Color(0xFF1E2130),
+          shape:
+              RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+          child: Container(
+            width: 680,
+            padding: const EdgeInsets.all(24),
+            child: Column(
+              mainAxisSize: MainAxisSize.min,
+              crossAxisAlignment: CrossAxisAlignment.start,
+              children: [
+                // 标题
+                Row(
+                  children: [
+                    if (task.finished)
+                      const Icon(Icons.check_circle,
+                          color: AppColors.green, size: 20)
+                    else
+                      const Icon(Icons.download,
+                          color: AppColors.accent, size: 20),
+                    const SizedBox(width: 8),
+                    const Text('安装任务',
+                        style: TextStyle(
+                            color: Colors.white,
+                            fontSize: 15,
+                            fontWeight: FontWeight.bold)),
+                    const SizedBox(width: 10),
+                    const Expanded(
+                      child: Text('如长时间无速度,请取消安装保留文件尝试再次安装',
+                          style:
+                              TextStyle(color: AppColors.red, fontSize: 11)),
+                    ),
+                    const SizedBox(width: 10),
+                    // 自动关机
+                    _AutoShutdownToggle(task: task),
+                    const SizedBox(width: 12),
+                    GestureDetector(
+                      onTap: () => Navigator.pop(context),
+                      child: const Icon(Icons.close,
+                          color: AppColors.textGray, size: 18),
+                    ),
+                  ],
+                ),
+                const SizedBox(height: 16),
+                // 游戏名
+                Text(task.title,
+                    maxLines: 1,
+                    overflow: TextOverflow.ellipsis,
+                    style: const TextStyle(
+                        color: Colors.white,
+                        fontSize: 14,
+                        fontWeight: FontWeight.w500)),
+                const SizedBox(height: 18),
+                // 进度区
+                Row(
+                  children: [
+                    // 环形进度
+                    SizedBox(
+                      width: 86,
+                      height: 86,
+                      child: Stack(
+                        alignment: Alignment.center,
+                        children: [
+                          SizedBox(
+                            width: 86,
+                            height: 86,
+                            child: CircularProgressIndicator(
+                              value: task.finished ? 1 : task.progress,
+                              color: task.paused
+                                  ? AppColors.yellow
+                                  : AppColors.accent,
+                              backgroundColor: AppColors.bgLighter,
+                              strokeWidth: 5,
+                            ),
+                          ),
+                          Text(
+                            '${(task.progress * 100).toStringAsFixed(task.progress < 0.1 ? 2 : 0)}%',
+                            style: const TextStyle(
+                                color: Colors.white,
+                                fontSize: 15,
+                                fontWeight: FontWeight.bold),
+                          ),
+                        ],
+                      ),
+                    ),
+                    const SizedBox(width: 22),
+                    Expanded(
+                      child: Column(
+                        crossAxisAlignment: CrossAxisAlignment.start,
+                        children: [
+                          Row(
+                            children: [
+                              Text(
+                                task.finished
+                                    ? '下载完成'
+                                    : task.paused
+                                        ? '已暂停'
+                                        : '正在下载',
+                                style: TextStyle(
+                                    color: task.paused
+                                        ? AppColors.yellow
+                                        : task.finished
+                                            ? AppColors.green
+                                            : AppColors.accent,
+                                    fontSize: 14,
+                                    fontWeight: FontWeight.w500),
+                              ),
+                            ],
+                          ),
+                          const SizedBox(height: 8),
+                          Text(
+                            '${formatBytes(task.speed)}/s',
+                            style: const TextStyle(
+                                color: AppColors.textGray, fontSize: 13),
+                          ),
+                          const SizedBox(height: 4),
+                          Text(
+                            '${formatBytes(task.receivedBytes)} / ${formatBytes(task.totalBytes)}',
+                            style: const TextStyle(
+                                color: AppColors.textGray, fontSize: 13),
+                          ),
+                          const SizedBox(height: 4),
+                          Text(
+                            task.finished
+                                ? '已完成'
+                                : '剩余时间 ${formatDuration(task.etaSeconds)}',
+                            style: const TextStyle(
+                                color: AppColors.textGray, fontSize: 13),
+                          ),
+                        ],
+                      ),
+                    ),
+                  ],
+                ),
+                const SizedBox(height: 16),
+                // 网络信息条
+                Container(
+                  padding:
+                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+                  decoration: BoxDecoration(
+                    color: AppColors.bg,
+                    borderRadius: BorderRadius.circular(4),
+                  ),
+                  child: Row(
+                    children: [
+                      const Text('网络运营商:联通',
+                          style: TextStyle(
+                              color: AppColors.textGray, fontSize: 12)),
+                      const Spacer(),
+                      const Text('点击切换线路:自动',
+                          style: TextStyle(
+                              color: AppColors.textGray, fontSize: 12)),
+                    ],
+                  ),
+                ),
+                const SizedBox(height: 10),
+                // 文件列表
+                Container(
+                  constraints: const BoxConstraints(maxHeight: 180),
+                  decoration: BoxDecoration(
+                    color: AppColors.bg,
+                    borderRadius: BorderRadius.circular(4),
+                  ),
+                  child: ListView.builder(
+                    shrinkWrap: true,
+                    itemCount: task.files.length,
+                    itemBuilder: (context, i) {
+                      final f = task.files[i];
+                      Color stColor = AppColors.textDim;
+                      String stLabel = '等待下载';
+                      switch (f.status) {
+                        case DownloadStatus.preparing:
+                          stColor = AppColors.yellow;
+                          stLabel = '正在准备';
+                        case DownloadStatus.downloading:
+                          stColor = AppColors.green;
+                          stLabel = '正在下载';
+                        case DownloadStatus.paused:
+                          stColor = AppColors.yellow;
+                          stLabel = '已暂停';
+                        case DownloadStatus.done:
+                          stColor = AppColors.green;
+                          stLabel = '已完成';
+                        case DownloadStatus.failed:
+                          stColor = AppColors.red;
+                          stLabel = '下载失败';
+                        default:
+                          stLabel = '等待下载';
+                      }
+                      return Padding(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 12, vertical: 6),
+                        child: Row(
+                          children: [
+                            SizedBox(
+                              width: 200,
+                              child: Text(f.name,
+                                  maxLines: 1,
+                                  overflow: TextOverflow.ellipsis,
+                                  style: const TextStyle(
+                                      color: AppColors.textWhite,
+                                      fontSize: 12)),
+                            ),
+                            Expanded(
+                              child: LinearProgressIndicator(
+                                value: f.progress,
+                                backgroundColor: AppColors.bgLighter,
+                                color: AppColors.accent,
+                                minHeight: 3,
+                              ),
+                            ),
+                            const SizedBox(width: 10),
+                            SizedBox(
+                              width: 130,
+                              child: Text(
+                                  '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
+                                  style: const TextStyle(
+                                      color: AppColors.textGray,
+                                      fontSize: 11)),
+                            ),
+                            SizedBox(
+                              width: 60,
+                              child: Text(stLabel,
+                                  style: TextStyle(
+                                      color: stColor, fontSize: 11)),
+                            ),
+                          ],
+                        ),
+                      );
+                    },
+                  ),
+                ),
+                const SizedBox(height: 18),
+                // 操作按钮
+                Row(
+                  children: [
+                    Expanded(
+                      child: ElevatedButton(
+                        onPressed: task.finished
+                            ? null
+                            : () {
+                                if (task.paused) {
+                                  DownloadManager.instance.resume();
+                                } else {
+                                  DownloadManager.instance.pause();
+                                }
+                              },
+                        style: ElevatedButton.styleFrom(
+                          backgroundColor: task.paused
+                              ? AppColors.accent
+                              : const Color(0xFF3A3F52),
+                          foregroundColor: Colors.white,
+                          disabledBackgroundColor:
+                              AppColors.green.withOpacity(0.3),
+                          padding: const EdgeInsets.symmetric(vertical: 12),
+                        ),
+                        child: Text(task.finished
+                            ? '下载完成'
+                            : task.paused
+                                ? '继续下载'
+                                : '暂停下载'),
+                      ),
+                    ),
+                    const SizedBox(width: 12),
+                    Expanded(
+                      child: ElevatedButton(
+                        onPressed: () {
+                          DownloadManager.instance.cancelTask();
+                          Navigator.pop(context);
+                        },
+                        style: ElevatedButton.styleFrom(
+                          backgroundColor: const Color(0xFF3A3F52),
+                          foregroundColor: Colors.white,
+                          padding: const EdgeInsets.symmetric(vertical: 12),
+                        ),
+                        child: const Text('取消安装'),
+                      ),
+                    ),
+                  ],
+                ),
+              ],
+            ),
+          ),
+        );
+      },
+    );
+  }
+}
+
+class _AutoShutdownToggle extends StatefulWidget {
+  final DownloadTask task;
+  const _AutoShutdownToggle({required this.task});
+  @override
+  State<_AutoShutdownToggle> createState() => _AutoShutdownToggleState();
+}
+
+class _AutoShutdownToggleState extends State<_AutoShutdownToggle> {
+  @override
+  Widget build(BuildContext context) {
+    return GestureDetector(
+      onTap: () => setState(
+          () => widget.task.autoShutdown = !widget.task.autoShutdown),
+      child: Row(
+        children: [
+          Text('自动关机',
+              style: const TextStyle(
+                  color: AppColors.textGray, fontSize: 11)),
+          const SizedBox(width: 6),
+          Container(
+            width: 28,
+            height: 15,
+            decoration: BoxDecoration(
+              color: widget.task.autoShutdown
+                  ? AppColors.accent
+                  : AppColors.bgLighter,
+              borderRadius: BorderRadius.circular(8),
+            ),
+            child: AnimatedAlign(
+              duration: const Duration(milliseconds: 150),
+              alignment: widget.task.autoShutdown
+                  ? Alignment.centerRight
+                  : Alignment.centerLeft,
+              child: Container(
+                width: 11,
+                height: 11,
+                margin: const EdgeInsets.all(2),
+                decoration:
+                    const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+/// 打开下载/安装目录
+Future<void> openDirectory(String path) async {
+  final dir = Directory(path);
+  if (!await dir.exists()) {
+    await dir.create(recursive: true);
+  }
+  Process.run('explorer.exe', [p.normalize(dir.path)]);
+}
diff --git a/fluttergamebox/lib/widgets/game_card.dart b/fluttergamebox/lib/widgets/game_card.dart
new file mode 100644
index 0000000..49df6e0
--- /dev/null
+++ b/fluttergamebox/lib/widgets/game_card.dart
@@ -0,0 +1,247 @@
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/api/api_client.dart';
+import 'package:fluttergamebox/api/api_service.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/pages/main_shell.dart';
+
+/// 首页游戏卡片
+class GameCard extends StatelessWidget {
+  final Game game;
+  const GameCard({super.key, required this.game});
+
+  @override
+  Widget build(BuildContext context) {
+    return GestureDetector(
+      onTap: () => _openDetail(context),
+      child: MouseRegion(
+        cursor: SystemMouseCursors.click,
+        child: Container(
+          decoration: BoxDecoration(
+            color: AppColors.bgLight,
+            borderRadius: BorderRadius.circular(6),
+          ),
+          child: Column(
+            crossAxisAlignment: CrossAxisAlignment.start,
+            children: [
+              // 封面
+              AspectRatio(
+                aspectRatio: 1.42,
+                child: Stack(
+                  fit: StackFit.expand,
+                  children: [
+                    ClipRRect(
+                      borderRadius: const BorderRadius.vertical(
+                          top: Radius.circular(6)),
+                      child: Image.network(
+                        ApiClient.baseUrl + game.cover,
+                        fit: BoxFit.cover,
+                        errorBuilder: (_, __, ___) => Container(
+                          color: const Color(0xFF2A2E45),
+                          child: Center(
+                            child: Text(
+                              game.title.characters.first,
+                              style: const TextStyle(
+                                  color: AppColors.textDim, fontSize: 32),
+                            ),
+                          ),
+                        ),
+                        loadingBuilder: (context, child, progress) {
+                          if (progress == null) return child;
+                          return Container(
+                            color: const Color(0xFF2A2E45),
+                            child: const Center(
+                              child: SizedBox(
+                                width: 20,
+                                height: 20,
+                                child: CircularProgressIndicator(
+                                    strokeWidth: 2,
+                                    color: AppColors.accent),
+                              ),
+                            ),
+                          );
+                        },
+                      ),
+                    ),
+                    // PC资源 标签
+                    Positioned(
+                      left: 0,
+                      top: 8,
+                      child: Container(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 8, vertical: 3),
+                        decoration: const BoxDecoration(
+                          color: AppColors.accent,
+                          borderRadius:
+                              BorderRadius.horizontal(right: Radius.circular(3)),
+                        ),
+                        child: Text(game.platformLabel,
+                            style: const TextStyle(
+                                color: Colors.white, fontSize: 11)),
+                      ),
+                    ),
+                    // 大小标签
+                    Positioned(
+                      right: 6,
+                      top: 8,
+                      child: Container(
+                        padding: const EdgeInsets.symmetric(
+                            horizontal: 6, vertical: 2),
+                        decoration: BoxDecoration(
+                          color: Colors.black.withOpacity(0.6),
+                          borderRadius: BorderRadius.circular(3),
+                        ),
+                        child: Text(game.size,
+                            style: const TextStyle(
+                                color: Colors.white, fontSize: 11)),
+                      ),
+                    ),
+                  ],
+                ),
+              ),
+              // 信息区
+              Expanded(
+                child: Padding(
+                  padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
+                  child: Column(
+                    crossAxisAlignment: CrossAxisAlignment.start,
+                    children: [
+                      if (game.versionNote.isNotEmpty)
+                        Padding(
+                          padding: const EdgeInsets.only(bottom: 2),
+                          child: Text(
+                            game.versionNote,
+                            maxLines: 1,
+                            overflow: TextOverflow.ellipsis,
+                            style: const TextStyle(
+                                color: AppColors.textDim, fontSize: 11),
+                          ),
+                        ),
+                      Text(
+                        game.title,
+                        maxLines: 2,
+                        overflow: TextOverflow.ellipsis,
+                        style: const TextStyle(
+                            color: Colors.white, fontSize: 13, height: 1.3),
+                      ),
+                      const Spacer(),
+                      Row(
+                        children: [
+                          Expanded(
+                            child: Text(
+                              game.tags.split(',').first,
+                              maxLines: 1,
+                              overflow: TextOverflow.ellipsis,
+                              style: const TextStyle(
+                                  color: AppColors.textDim, fontSize: 11),
+                            ),
+                          ),
+                          _AddButton(game: game),
+                        ],
+                      ),
+                    ],
+                  ),
+                ),
+              ),
+            ],
+          ),
+        ),
+      ),
+    );
+  }
+
+  void _openDetail(BuildContext context) {
+    // 通过主Shell打开详情页,保留首页顶部导航栏
+    ShellNav.instance.openDetail?.call(game.id);
+  }
+}
+
+class _AddButton extends StatefulWidget {
+  final Game game;
+  const _AddButton({required this.game});
+  @override
+  State<_AddButton> createState() => _AddButtonState();
+}
+
+class _AddButtonState extends State<_AddButton> {
+  bool added = false;
+
+  @override
+  void initState() {
+    super.initState();
+    _check();
+  }
+
+  Future<void> _check() async {
+    try {
+      final res = await ApiService.gameDetail(widget.game.id);
+      if (res['code'] == 0 && res['data']['in_library'] == true) {
+        if (mounted) setState(() => added = true);
+      }
+    } catch (_) {}
+  }
+
+  Future<void> _add() async {
+    if (added) return;
+    final res = await ApiService.addToLibrary(widget.game.id);
+    if (res['code'] == 0 && mounted) {
+      setState(() => added = true);
+      _toast('已加入资源库');
+    } else if (mounted) {
+      _toast(res['msg'] ?? '添加失败', error: true);
+    }
+  }
+
+  void _toast(String msg, {bool error = false}) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding:
+                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: error ? AppColors.red : AppColors.green,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                Icon(error ? Icons.error_outline : Icons.check_circle,
+                    color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(
+                          color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return GestureDetector(
+      onTap: _add,
+      child: Container(
+        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
+        decoration: BoxDecoration(
+          color: added ? const Color(0xFF3A3F52) : AppColors.accent,
+          borderRadius: BorderRadius.circular(3),
+        ),
+        child: Text(
+          added ? '已添加' : '添加',
+          style: const TextStyle(color: Colors.white, fontSize: 11),
+        ),
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/lib/widgets/info_dialogs.dart b/fluttergamebox/lib/widgets/info_dialogs.dart
new file mode 100644
index 0000000..58950ab
--- /dev/null
+++ b/fluttergamebox/lib/widgets/info_dialogs.dart
@@ -0,0 +1,325 @@
+import 'dart:io';
+
+import 'package:file_picker/file_picker.dart';
+import 'package:flutter/material.dart';
+import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/utils/util.dart';
+
+String _wmic(String cmd, String arg) {
+  try {
+    final result = Process.runSync(cmd, arg.split(' '));
+    final lines = result.stdout
+        .toString()
+        .split('\n')
+        .map((l) => l.trim())
+        .where((l) => l.isNotEmpty)
+        .toList();
+    if (lines.length > 1) return lines[1];
+  } catch (_) {}
+  return '';
+}
+
+/// 电脑设备配置弹窗
+void showDeviceConfigDialog(BuildContext context) {
+  final cpu = _wmic('wmic', 'cpu get Name');
+  final ramBytes = int.tryParse(_wmic('wmic', 'ComputerSystem get TotalPhysicalMemory')) ?? 0;
+  final lines = [
+    '操作系统: ${Platform.operatingSystemVersion}',
+    'CPU: ${cpu.isEmpty ? '未知' : cpu}',
+    '内存: ${(ramBytes / 1024 / 1024 / 1024).toStringAsFixed(1)} GiB',
+    '主机名: ${Platform.localHostname}',
+    '设备序列号: ${_deviceSerial()}',
+    '客户端版本号: V2.2.5',
+  ];
+  _greenInfoDialog(context, '电脑设备配置', Icons.computer, lines);
+}
+
+String _deviceSerial() {
+  try {
+    final result = Process.runSync('wmic', ['csproduct', 'get', 'UUID']);
+    final out = result.stdout.toString();
+    final lines =
+        out.split('\n').map((l) => l.trim()).where((l) => l.isNotEmpty).toList();
+    if (lines.length > 1) return lines[1];
+  } catch (_) {}
+  return '00326-60000-00000-AA068';
+}
+
+/// 电脑网络信息弹窗
+void showNetworkInfoDialog(BuildContext context) {
+  final lines = [
+    '公网IP: 获取中...',
+    '地区: 中国',
+    '运营商: 联通',
+  ];
+  _greenInfoDialog(context, '电脑网络信息', Icons.wifi, lines);
+}
+
+void _greenInfoDialog(
+    BuildContext context, String title, IconData icon, List<String> lines) {
+  showDialog(
+    context: context,
+    builder: (context) => Dialog(
+      backgroundColor: const Color(0xFF14161F),
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+      child: Container(
+        width: 420,
+        padding: EdgeInsets.zero,
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          children: [
+            // 标题栏
+            Container(
+              height: 40,
+              padding: const EdgeInsets.symmetric(horizontal: 12),
+              decoration: BoxDecoration(
+                color: const Color(0xFF191C2B),
+                borderRadius:
+                    const BorderRadius.vertical(top: Radius.circular(6)),
+              ),
+              child: Row(
+                children: [
+                  Icon(icon, size: 16, color: AppColors.textGray),
+                  const SizedBox(width: 8),
+                  Text(title,
+                      style: const TextStyle(
+                          color: Colors.white, fontSize: 13)),
+                  const Spacer(),
+                  GestureDetector(
+                    onTap: () => Navigator.pop(context),
+                    child: const Icon(Icons.close,
+                        size: 16, color: AppColors.textGray),
+                  ),
+                ],
+              ),
+            ),
+            Padding(
+              padding: const EdgeInsets.all(20),
+              child: Column(
+                crossAxisAlignment: CrossAxisAlignment.start,
+                children: lines
+                    .map((l) => Padding(
+                          padding: const EdgeInsets.symmetric(vertical: 3),
+                          child: Text(l,
+                              style: const TextStyle(
+                                  color: Color(0xFF33FF66),
+                                  fontSize: 13,
+                                  fontFamily: 'Consolas')),
+                        ))
+                    .toList(),
+              ),
+            ),
+          ],
+        ),
+      ),
+    ),
+  );
+}
+
+/// 下载安装路径设置弹窗
+void showPathDialog(BuildContext context) {
+  showDialog(
+    context: context,
+    builder: (context) => const _PathDialog(),
+  );
+}
+
+class _PathDialog extends StatefulWidget {
+  const _PathDialog();
+  @override
+  State<_PathDialog> createState() => _PathDialogState();
+}
+
+class _PathDialogState extends State<_PathDialog> {
+  final _dlCtrl = TextEditingController();
+  final _insCtrl = TextEditingController();
+  bool _diskCheck = true;
+  bool _hddCheck = false;
+
+  @override
+  void initState() {
+    super.initState();
+    _load();
+  }
+
+  Future<void> _load() async {
+    final dl = await AppPrefs.getDownloadPath();
+    final ins = await AppPrefs.getInstallPath();
+    setState(() {
+      _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
+      _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
+    });
+  }
+
+  Future<void> _pick(TextEditingController ctrl) async {
+    final dir = await FilePicker.platform.getDirectoryPath();
+    if (dir != null) {
+      setState(() => ctrl.text = dir);
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Dialog(
+      backgroundColor: const Color(0xFF1E2130),
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+      child: Container(
+        width: 480,
+        padding: const EdgeInsets.all(24),
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: [
+            Row(
+              children: [
+                const Icon(Icons.folder_open,
+                    size: 16, color: AppColors.textGray),
+                const SizedBox(width: 8),
+                const Text('下载安装路径',
+                    style: TextStyle(
+                        color: Colors.white,
+                        fontSize: 14,
+                        fontWeight: FontWeight.w500)),
+                const Spacer(),
+                GestureDetector(
+                  onTap: () => Navigator.pop(context),
+                  child: const Icon(Icons.close,
+                      size: 16, color: AppColors.textGray),
+                ),
+              ],
+            ),
+            const SizedBox(height: 20),
+            const Text('下载路径:',
+                style: TextStyle(color: AppColors.textWhite, fontSize: 13)),
+            const SizedBox(height: 8),
+            Row(
+              children: [
+                Expanded(
+                  child: TextField(
+                    controller: _dlCtrl,
+                    style: const TextStyle(
+                        color: Colors.black, fontSize: 13),
+                    decoration: InputDecoration(
+                      filled: true,
+                      fillColor: Colors.white,
+                      contentPadding: const EdgeInsets.symmetric(
+                          horizontal: 10, vertical: 10),
+                      border: OutlineInputBorder(
+                          borderRadius: BorderRadius.circular(4),
+                          borderSide: BorderSide.none),
+                    ),
+                  ),
+                ),
+                const SizedBox(width: 8),
+                ElevatedButton(
+                  onPressed: () => _pick(_dlCtrl),
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    foregroundColor: Colors.white,
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 14, vertical: 11),
+                  ),
+                  child: const Text('选择目录', style: TextStyle(fontSize: 12)),
+                ),
+              ],
+            ),
+            const SizedBox(height: 14),
+            const Text('安装路径:',
+                style: TextStyle(color: AppColors.textWhite, fontSize: 13)),
+            const SizedBox(height: 8),
+            Row(
+              children: [
+                Expanded(
+                  child: TextField(
+                    controller: _insCtrl,
+                    style: const TextStyle(
+                        color: Colors.black, fontSize: 13),
+                    decoration: InputDecoration(
+                      filled: true,
+                      fillColor: Colors.white,
+                      contentPadding: const EdgeInsets.symmetric(
+                          horizontal: 10, vertical: 10),
+                      border: OutlineInputBorder(
+                          borderRadius: BorderRadius.circular(4),
+                          borderSide: BorderSide.none),
+                    ),
+                  ),
+                ),
+                const SizedBox(width: 8),
+                ElevatedButton(
+                  onPressed: () => _pick(_insCtrl),
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    foregroundColor: Colors.white,
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 14, vertical: 11),
+                  ),
+                  child: const Text('选择目录', style: TextStyle(fontSize: 12)),
+                ),
+              ],
+            ),
+            const SizedBox(height: 14),
+            Row(
+              children: [
+                _checkbox('磁盘检测', _diskCheck,
+                    (v) => setState(() => _diskCheck = v ?? false)),
+                const SizedBox(width: 20),
+                _checkbox('机械硬盘勾选', _hddCheck,
+                    (v) => setState(() => _hddCheck = v ?? false)),
+              ],
+            ),
+            const SizedBox(height: 22),
+            Row(
+              mainAxisAlignment: MainAxisAlignment.end,
+              children: [
+                OutlinedButton(
+                  onPressed: () => Navigator.pop(context),
+                  style: OutlinedButton.styleFrom(
+                    foregroundColor: AppColors.textGray,
+                    side: const BorderSide(color: AppColors.bgLighter),
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 22, vertical: 10),
+                  ),
+                  child: const Text('取消'),
+                ),
+                const SizedBox(width: 12),
+                ElevatedButton(
+                  onPressed: () async {
+                    await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
+                    if (context.mounted) Navigator.pop(context);
+                  },
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    foregroundColor: Colors.white,
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 22, vertical: 10),
+                  ),
+                  child: const Text('确认'),
+                ),
+              ],
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+
+  Widget _checkbox(String label, bool value, ValueChanged<bool?> onChanged) {
+    return Row(
+      children: [
+        SizedBox(
+          width: 16,
+          height: 16,
+          child: Checkbox(
+            value: value,
+            onChanged: onChanged,
+            activeColor: AppColors.accent,
+            side: const BorderSide(color: AppColors.textGray),
+          ),
+        ),
+        const SizedBox(width: 6),
+        Text(label, style: const TextStyle(color: AppColors.textGray, fontSize: 12)),
+      ],
+    );
+  }
+}
diff --git a/fluttergamebox/lib/widgets/window_controls.dart b/fluttergamebox/lib/widgets/window_controls.dart
new file mode 100644
index 0000000..8365585
--- /dev/null
+++ b/fluttergamebox/lib/widgets/window_controls.dart
@@ -0,0 +1,69 @@
+import 'package:flutter/material.dart';
+import 'package:window_manager/window_manager.dart';
+
+/// 自定义窗口控制按钮(最小化/最大化/关闭)
+class WindowControls extends StatelessWidget {
+  final bool dark;
+  const WindowControls({super.key, this.dark = true});
+
+  @override
+  Widget build(BuildContext context) {
+    final color = dark ? Colors.white : Colors.white;
+    return Row(
+      mainAxisSize: MainAxisSize.min,
+      children: [
+        _WinBtn(
+          icon: Icons.horizontal_rule,
+          color: color,
+          onTap: () => windowManager.minimize(),
+        ),
+        _WinBtn(
+          icon: Icons.crop_square,
+          color: color,
+          iconSize: 15,
+          onTap: () async {
+            if (await windowManager.isMaximized()) {
+              windowManager.unmaximize();
+            } else {
+              windowManager.maximize();
+            }
+          },
+        ),
+        _WinBtn(
+          icon: Icons.close,
+          color: color,
+          hoverBg: const Color(0xFFE81123),
+          onTap: () => windowManager.close(),
+        ),
+      ],
+    );
+  }
+}
+
+class _WinBtn extends StatelessWidget {
+  final IconData icon;
+  final Color color;
+  final Color? hoverBg;
+  final double iconSize;
+  final VoidCallback onTap;
+  const _WinBtn({
+    required this.icon,
+    required this.color,
+    required this.onTap,
+    this.hoverBg,
+    this.iconSize = 17,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return InkWell(
+      onTap: onTap,
+      hoverColor: hoverBg ?? Colors.white.withOpacity(0.1),
+      child: SizedBox(
+        width: 40,
+        height: 32,
+        child: Icon(icon, color: color, size: iconSize),
+      ),
+    );
+  }
+}
diff --git a/fluttergamebox/linux/flutter/generated_plugin_registrant.cc b/fluttergamebox/linux/flutter/generated_plugin_registrant.cc
index e71a16d..faea87d 100644
--- a/fluttergamebox/linux/flutter/generated_plugin_registrant.cc
+++ b/fluttergamebox/linux/flutter/generated_plugin_registrant.cc
@@ -6,6 +6,18 @@
 
 #include "generated_plugin_registrant.h"
 
+#include <screen_retriever_linux/screen_retriever_linux_plugin.h>
+#include <url_launcher_linux/url_launcher_plugin.h>
+#include <window_manager/window_manager_plugin.h>
 
 void fl_register_plugins(FlPluginRegistry* registry) {
+  g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar =
+      fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin");
+  screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar);
+  g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
+      fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
+  url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
+  g_autoptr(FlPluginRegistrar) window_manager_registrar =
+      fl_plugin_registry_get_registrar_for_plugin(registry, "WindowManagerPlugin");
+  window_manager_plugin_register_with_registrar(window_manager_registrar);
 }
diff --git a/fluttergamebox/linux/flutter/generated_plugins.cmake b/fluttergamebox/linux/flutter/generated_plugins.cmake
index 2e1de87..4f427dd 100644
--- a/fluttergamebox/linux/flutter/generated_plugins.cmake
+++ b/fluttergamebox/linux/flutter/generated_plugins.cmake
@@ -3,6 +3,9 @@
 #
 
 list(APPEND FLUTTER_PLUGIN_LIST
+  screen_retriever_linux
+  url_launcher_linux
+  window_manager
 )
 
 list(APPEND FLUTTER_FFI_PLUGIN_LIST
diff --git a/fluttergamebox/macos/Flutter/GeneratedPluginRegistrant.swift b/fluttergamebox/macos/Flutter/GeneratedPluginRegistrant.swift
index cccf817..3391696 100644
--- a/fluttergamebox/macos/Flutter/GeneratedPluginRegistrant.swift
+++ b/fluttergamebox/macos/Flutter/GeneratedPluginRegistrant.swift
@@ -5,6 +5,16 @@
 import FlutterMacOS
 import Foundation
 
+import file_picker
+import screen_retriever_macos
+import shared_preferences_foundation
+import url_launcher_macos
+import window_manager
 
 func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
+  FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
+  ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))
+  SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
+  UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
+  WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin"))
 }
diff --git a/fluttergamebox/pubspec.lock b/fluttergamebox/pubspec.lock
index 7950768..47054d2 100644
--- a/fluttergamebox/pubspec.lock
+++ b/fluttergamebox/pubspec.lock
@@ -41,6 +41,14 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "1.19.1"
+  cross_file:
+    dependency: transitive
+    description:
+      name: cross_file
+      sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.3.5+5"
   cupertino_icons:
     dependency: "direct main"
     description:
@@ -49,6 +57,22 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "1.0.9"
+  dio:
+    dependency: "direct main"
+    description:
+      name: dio
+      sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "5.11.1"
+  dio_web_adapter:
+    dependency: transitive
+    description:
+      name: dio_web_adapter
+      sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.2.2"
   fake_async:
     dependency: transitive
     description:
@@ -57,6 +81,30 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "1.3.3"
+  ffi:
+    dependency: transitive
+    description:
+      name: ffi
+      sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.2.0"
+  file:
+    dependency: transitive
+    description:
+      name: file
+      sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "7.0.1"
+  file_picker:
+    dependency: "direct main"
+    description:
+      name: file_picker
+      sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "8.3.7"
   flutter:
     dependency: "direct main"
     description: flutter
@@ -70,11 +118,40 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "6.0.0"
+  flutter_plugin_android_lifecycle:
+    dependency: transitive
+    description:
+      name: flutter_plugin_android_lifecycle
+      sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.0.35"
   flutter_test:
     dependency: "direct dev"
     description: flutter
     source: sdk
     version: "0.0.0"
+  flutter_web_plugins:
+    dependency: transitive
+    description: flutter
+    source: sdk
+    version: "0.0.0"
+  http_parser:
+    dependency: transitive
+    description:
+      name: http_parser
+      sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "4.1.2"
+  json_annotation:
+    dependency: transitive
+    description:
+      name: json_annotation
+      sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "4.12.0"
   leak_tracker:
     dependency: transitive
     description:
@@ -131,14 +208,174 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "1.17.0"
-  path:
+  mime:
     dependency: transitive
     description:
+      name: mime
+      sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.1.0"
+  nested:
+    dependency: transitive
+    description:
+      name: nested
+      sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "1.0.0"
+  path:
+    dependency: "direct main"
+    description:
       name: path
       sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "1.9.1"
+  path_provider_linux:
+    dependency: transitive
+    description:
+      name: path_provider_linux
+      sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.2.2"
+  path_provider_platform_interface:
+    dependency: transitive
+    description:
+      name: path_provider_platform_interface
+      sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.1.3"
+  path_provider_windows:
+    dependency: transitive
+    description:
+      name: path_provider_windows
+      sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.3.0"
+  platform:
+    dependency: transitive
+    description:
+      name: platform
+      sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "3.1.6"
+  plugin_platform_interface:
+    dependency: transitive
+    description:
+      name: plugin_platform_interface
+      sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.1.8"
+  provider:
+    dependency: "direct main"
+    description:
+      name: provider
+      sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "6.1.5+1"
+  screen_retriever:
+    dependency: transitive
+    description:
+      name: screen_retriever
+      sha256: ace919117a7520c13a50a6259e60c4a0d4cbe98809468792a91b5c5adada2aa6
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.2.2"
+  screen_retriever_linux:
+    dependency: transitive
+    description:
+      name: screen_retriever_linux
+      sha256: "7b52006a5ceae1f3d5af7f77188c3290d6e7d8ded16d99809bea84967c65c257"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.2.2"
+  screen_retriever_macos:
+    dependency: transitive
+    description:
+      name: screen_retriever_macos
+      sha256: a1489b99cce597c45a54b9aae1cd94c8d4705353b7e0bb2457a6e4de44e0ad8a
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.2.2"
+  screen_retriever_platform_interface:
+    dependency: transitive
+    description:
+      name: screen_retriever_platform_interface
+      sha256: "94a5535277510a63184ca178ce12a1449bc0b38618879aa1c18bf57369c5064a"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.2.2"
+  screen_retriever_windows:
+    dependency: transitive
+    description:
+      name: screen_retriever_windows
+      sha256: dafc6922b0bfbf1d48cf3ccbf519b4fff47bdcb820da1728ea6db675fecc9324
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.2.2"
+  shared_preferences:
+    dependency: "direct main"
+    description:
+      name: shared_preferences
+      sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.5.6"
+  shared_preferences_android:
+    dependency: transitive
+    description:
+      name: shared_preferences_android
+      sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.4.23"
+  shared_preferences_foundation:
+    dependency: transitive
+    description:
+      name: shared_preferences_foundation
+      sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.5.7"
+  shared_preferences_linux:
+    dependency: transitive
+    description:
+      name: shared_preferences_linux
+      sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.4.1"
+  shared_preferences_platform_interface:
+    dependency: transitive
+    description:
+      name: shared_preferences_platform_interface
+      sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.4.2"
+  shared_preferences_web:
+    dependency: transitive
+    description:
+      name: shared_preferences_web
+      sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.4.3"
+  shared_preferences_windows:
+    dependency: transitive
+    description:
+      name: shared_preferences_windows
+      sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.4.1"
   sky_engine:
     dependency: transitive
     description: flutter
@@ -192,6 +429,78 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "0.7.10"
+  typed_data:
+    dependency: transitive
+    description:
+      name: typed_data
+      sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "1.4.0"
+  url_launcher:
+    dependency: "direct main"
+    description:
+      name: url_launcher
+      sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "6.3.3"
+  url_launcher_android:
+    dependency: transitive
+    description:
+      name: url_launcher_android
+      sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "6.3.30"
+  url_launcher_ios:
+    dependency: transitive
+    description:
+      name: url_launcher_ios
+      sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "6.4.2"
+  url_launcher_linux:
+    dependency: transitive
+    description:
+      name: url_launcher_linux
+      sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "3.2.3"
+  url_launcher_macos:
+    dependency: transitive
+    description:
+      name: url_launcher_macos
+      sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "3.2.6"
+  url_launcher_platform_interface:
+    dependency: transitive
+    description:
+      name: url_launcher_platform_interface
+      sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.3.2"
+  url_launcher_web:
+    dependency: transitive
+    description:
+      name: url_launcher_web
+      sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "2.4.3"
+  url_launcher_windows:
+    dependency: transitive
+    description:
+      name: url_launcher_windows
+      sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "3.1.6"
   vector_math:
     dependency: transitive
     description:
@@ -208,6 +517,38 @@
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "15.4.0"
+  web:
+    dependency: transitive
+    description:
+      name: web
+      sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "1.1.1"
+  win32:
+    dependency: transitive
+    description:
+      name: win32
+      sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "5.15.0"
+  window_manager:
+    dependency: "direct main"
+    description:
+      name: window_manager
+      sha256: "732896e1416297c63c9e3fb95aea72d0355f61390263982a47fd519169dc5059"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.4.3"
+  xdg_directories:
+    dependency: transitive
+    description:
+      name: xdg_directories
+      sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "1.1.0"
 sdks:
   dart: ">=3.11.3 <4.0.0"
-  flutter: ">=3.18.0-18.0.pre.54"
+  flutter: ">=3.41.0"
diff --git a/fluttergamebox/pubspec.yaml b/fluttergamebox/pubspec.yaml
index ac2fddb..26b979b 100644
--- a/fluttergamebox/pubspec.yaml
+++ b/fluttergamebox/pubspec.yaml
@@ -34,6 +34,13 @@
   # The following adds the Cupertino Icons font to your application.
   # Use with the CupertinoIcons class for iOS style icons.
   cupertino_icons: ^1.0.8
+  dio: ^5.7.0
+  provider: ^6.1.2
+  shared_preferences: ^2.3.3
+  window_manager: ^0.4.3
+  file_picker: ^8.1.6
+  path: ^1.9.0
+  url_launcher: ^6.3.1
 
 dev_dependencies:
   flutter_test:
@@ -57,6 +64,9 @@
   # the material Icons class.
   uses-material-design: true
 
+  assets:
+    - assets/images/
+
   # To add assets to your application, add an assets section, like this:
   # assets:
   #   - images/a_dot_burr.jpeg
diff --git a/fluttergamebox/test/widget_test.dart b/fluttergamebox/test/widget_test.dart
index 5834975..83da334 100644
--- a/fluttergamebox/test/widget_test.dart
+++ b/fluttergamebox/test/widget_test.dart
@@ -1,30 +1,7 @@
-// This is a basic Flutter widget test.
-//
-// To perform an interaction with a widget in your test, use the WidgetTester
-// utility in the flutter_test package. For example, you can send tap and scroll
-// gestures. You can also use WidgetTester to find child widgets in the widget
-// tree, read text, and verify that the values of widget properties are correct.
-
-import 'package:flutter/material.dart';
 import 'package:flutter_test/flutter_test.dart';
 
-import 'package:fluttergamebox/main.dart';
-
 void main() {
-  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
-    // Build our app and trigger a frame.
-    await tester.pumpWidget(const MyApp());
-
-    // Verify that our counter starts at 0.
-    expect(find.text('0'), findsOneWidget);
-    expect(find.text('1'), findsNothing);
-
-    // Tap the '+' icon and trigger a frame.
-    await tester.tap(find.byIcon(Icons.add));
-    await tester.pump();
-
-    // Verify that our counter has incremented.
-    expect(find.text('0'), findsNothing);
-    expect(find.text('1'), findsOneWidget);
+  test('placeholder', () {
+    expect(1 + 1, 2);
   });
 }
diff --git a/fluttergamebox/windows/flutter/generated_plugin_registrant.cc b/fluttergamebox/windows/flutter/generated_plugin_registrant.cc
index 8b6d468..48096ae 100644
--- a/fluttergamebox/windows/flutter/generated_plugin_registrant.cc
+++ b/fluttergamebox/windows/flutter/generated_plugin_registrant.cc
@@ -6,6 +6,15 @@
 
 #include "generated_plugin_registrant.h"
 
+#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>
+#include <url_launcher_windows/url_launcher_windows.h>
+#include <window_manager/window_manager_plugin.h>
 
 void RegisterPlugins(flutter::PluginRegistry* registry) {
+  ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar(
+      registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi"));
+  UrlLauncherWindowsRegisterWithRegistrar(
+      registry->GetRegistrarForPlugin("UrlLauncherWindows"));
+  WindowManagerPluginRegisterWithRegistrar(
+      registry->GetRegistrarForPlugin("WindowManagerPlugin"));
 }
diff --git a/fluttergamebox/windows/flutter/generated_plugins.cmake b/fluttergamebox/windows/flutter/generated_plugins.cmake
index b93c4c3..2e1248d 100644
--- a/fluttergamebox/windows/flutter/generated_plugins.cmake
+++ b/fluttergamebox/windows/flutter/generated_plugins.cmake
@@ -3,6 +3,9 @@
 #
 
 list(APPEND FLUTTER_PLUGIN_LIST
+  screen_retriever_windows
+  url_launcher_windows
+  window_manager
 )
 
 list(APPEND FLUTTER_FFI_PLUGIN_LIST
diff --git a/server/admin/index.html b/server/admin/index.html
new file mode 100644
index 0000000..18fe189
--- /dev/null
+++ b/server/admin/index.html
@@ -0,0 +1,462 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+<meta charset="UTF-8">
+<title>99游戏盒子 - 管理后台</title>
+<style>
+* { margin:0; padding:0; box-sizing:border-box; }
+body { font-family:"Microsoft YaHei",sans-serif; background:#14161f; color:#e0e0e0; font-size:14px; }
+button { cursor:pointer; font-family:inherit; }
+input,select,textarea { font-family:inherit; outline:none; }
+.hidden { display:none !important; }
+
+/* 登录页 */
+#loginPage { display:flex; align-items:center; justify-content:center; height:100vh; }
+.login-box { background:#1e2130; border-radius:12px; padding:40px; width:360px; box-shadow:0 10px 40px rgba(0,0,0,.5); }
+.login-box h1 { font-size:20px; text-align:center; margin-bottom:8px; }
+.login-box .sub { text-align:center; color:#888; font-size:12px; margin-bottom:24px; }
+.login-box input { width:100%; padding:10px 12px; border-radius:6px; border:1px solid #333; background:#14161f; color:#fff; margin-bottom:14px; }
+.btn { border:none; border-radius:6px; padding:9px 16px; background:#2b7fff; color:#fff; }
+.btn:hover { background:#4a92ff; }
+.btn-gray { background:#3a3f52; color:#ccc; }
+.btn-gray:hover { background:#4a5069; }
+.btn-danger { background:#c0392b; }
+.btn-danger:hover { background:#d94a3a; }
+.btn-sm { padding:5px 10px; font-size:12px; }
+.btn-block { width:100%; padding:11px; font-size:15px; }
+
+/* 主面板 */
+#mainPage { display:none; height:100vh; flex-direction:column; }
+.topbar { background:#1a1d2b; padding:0 24px; display:flex; align-items:center; height:56px; gap:20px; border-bottom:1px solid #262a3d; }
+.logo { font-size:17px; font-weight:bold; color:#ff5c8a; }
+.nav-tabs { display:flex; gap:4px; flex:1; }
+.nav-tabs button { background:none; border:none; color:#9aa0b4; padding:8px 18px; border-radius:6px; font-size:14px; }
+.nav-tabs button.active { background:#2b7fff; color:#fff; }
+#logoutBtn { background:none; border:1px solid #3a3f52; color:#aaa; border-radius:6px; padding:7px 14px; }
+
+.content { flex:1; overflow:auto; padding:24px; }
+.stats-row { display:flex; gap:16px; margin-bottom:24px; }
+.stat-card { background:#1e2130; border-radius:10px; padding:18px 24px; min-width:150px; }
+.stat-card .num { font-size:26px; font-weight:bold; color:#4a92ff; }
+.stat-card .label { color:#888; font-size:12px; margin-top:4px; }
+
+.panel { background:#1e2130; border-radius:10px; padding:20px; }
+.panel h2 { font-size:16px; margin-bottom:16px; }
+.toolbar { display:flex; gap:10px; margin-bottom:16px; flex-wrap:wrap; align-items:center; }
+.toolbar input, .toolbar select { background:#14161f; border:1px solid #333; color:#fff; border-radius:6px; padding:8px 10px; }
+
+table { width:100%; border-collapse:collapse; }
+th, td { padding:10px 12px; text-align:left; border-bottom:1px solid #262a3d; font-size:13px; }
+th { color:#888; font-weight:normal; }
+tr:hover td { background:#232739; }
+.tag { display:inline-block; padding:2px 8px; border-radius:4px; font-size:12px; }
+.tag-blue { background:rgba(43,127,255,.15); color:#4a92ff; }
+.tag-green { background:rgba(46,204,113,.15); color:#2ecc71; }
+.tag-red { background:rgba(231,76,60,.15); color:#e74c3c; }
+.tag-gray { background:rgba(150,150,150,.15); color:#aaa; }
+
+/* 弹窗 */
+.modal-mask { position:fixed; inset:0; background:rgba(0,0,0,.6); display:flex; align-items:center; justify-content:center; z-index:100; }
+.modal { background:#1e2130; border-radius:12px; padding:24px; width:640px; max-height:86vh; overflow:auto; }
+.modal h3 { margin-bottom:18px; }
+.form-row { margin-bottom:12px; }
+.form-row label { display:block; color:#9aa0b4; font-size:12px; margin-bottom:6px; }
+.form-row input, .form-row select, .form-row textarea { width:100%; background:#14161f; border:1px solid #333; color:#fff; border-radius:6px; padding:9px 10px; }
+.form-row textarea { min-height:90px; resize:vertical; }
+.form-cols { display:grid; grid-template-columns:1fr 1fr; gap:0 16px; }
+.upload-box { border:1px dashed #3a3f52; border-radius:8px; padding:12px; margin-bottom:8px; }
+.upload-box .hint { color:#666; font-size:12px; margin-bottom:8px; }
+.file-item { display:flex; justify-content:space-between; background:#14161f; padding:6px 10px; border-radius:6px; margin-top:6px; font-size:12px; }
+.file-item img { width:48px; height:32px; object-fit:cover; border-radius:4px; }
+.pager { display:flex; gap:8px; align-items:center; margin-top:16px; justify-content:center; }
+.pager button { background:#3a3f52; color:#ccc; border:none; border-radius:4px; padding:6px 12px; }
+.pager button:disabled { opacity:.4; cursor:default; }
+.toast { position:fixed; top:70px; left:50%; transform:translateX(-50%); background:#2ecc71; color:#fff; padding:10px 22px; border-radius:8px; z-index:200; display:none; }
+.toast.err { background:#e74c3c; }
+.keylist { background:#14161f; border-radius:6px; padding:12px; max-height:220px; overflow:auto; font-family:Consolas,monospace; line-height:1.9; margin-top:10px; }
+</style>
+</head>
+<body>
+
+<!-- 登录 -->
+<div id="loginPage">
+  <div class="login-box">
+    <h1>99游戏盒子 · 管理后台</h1>
+    <div class="sub">GameBox Admin</div>
+    <input id="adminUser" placeholder="管理员账号" value="admin">
+    <input id="adminPwd" type="password" placeholder="密码">
+    <button class="btn btn-block" onclick="adminLogin()">登 录</button>
+  </div>
+</div>
+
+<!-- 主面板 -->
+<div id="mainPage">
+  <div class="topbar">
+    <div class="logo">99游戏盒子 · 管理后台</div>
+    <div class="nav-tabs">
+      <button class="active" data-tab="keys" onclick="switchTab('keys')">密钥管理</button>
+      <button data-tab="games" onclick="switchTab('games')">游戏管理</button>
+      <button data-tab="cats" onclick="switchTab('cats')">类别管理</button>
+    </div>
+    <button id="logoutBtn" onclick="logout()">退出登录</button>
+  </div>
+  <div class="content">
+    <div class="stats-row" id="statsRow"></div>
+
+    <!-- 密钥管理 -->
+    <div id="tab-keys" class="panel">
+      <h2>会员密钥</h2>
+      <div class="toolbar">
+        <select id="genType"><option value="day">日卡</option><option value="month">月卡</option><option value="year">年卡</option></select>
+        <input id="genCount" type="number" value="10" min="1" max="100" style="width:80px">
+        <button class="btn" onclick="generateKeys()">生成密钥</button>
+        <span style="flex:1"></span>
+        <input id="keyKeyword" placeholder="搜索激活码">
+        <select id="keyStatus">
+          <option value="">全部状态</option>
+          <option value="0">未使用</option>
+          <option value="1">已使用</option>
+          <option value="2">已过期</option>
+        </select>
+        <button class="btn" onclick="loadKeys(1)">搜索</button>
+      </div>
+      <table>
+        <thead><tr><th>ID</th><th>激活码</th><th>类型</th><th>状态</th><th>绑定用户</th><th>机器码</th><th>到期时间</th><th>重置次数</th><th>操作</th></tr></thead>
+        <tbody id="keyTable"></tbody>
+      </table>
+      <div class="pager" id="keyPager"></div>
+    </div>
+
+    <!-- 游戏管理 -->
+    <div id="tab-games" class="panel hidden">
+      <h2>游戏资源</h2>
+      <div class="toolbar">
+        <button class="btn" onclick="showGameModal()">+ 上传游戏</button>
+      </div>
+      <table>
+        <thead><tr><th>ID</th><th>封面</th><th>名称</th><th>类别</th><th>平台</th><th>大小</th><th>下载次数</th><th>操作</th></tr></thead>
+        <tbody id="gameTable"></tbody>
+      </table>
+    </div>
+
+    <!-- 类别管理 -->
+    <div id="tab-cats" class="panel hidden">
+      <h2>游戏类别</h2>
+      <div class="toolbar">
+        <input id="newCatName" placeholder="新类别名称">
+        <button class="btn" onclick="addCategory()">添加类别</button>
+      </div>
+      <table>
+        <thead><tr><th>ID</th><th>名称</th><th>游戏数</th><th>操作</th></tr></thead>
+        <tbody id="catTable"></tbody>
+      </table>
+    </div>
+  </div>
+</div>
+
+<!-- 游戏编辑弹窗 -->
+<div id="gameModal" class="modal-mask hidden">
+  <div class="modal">
+    <h3 id="gameModalTitle">上传游戏</h3>
+    <input type="hidden" id="g_id">
+    <div class="form-cols">
+      <div class="form-row"><label>游戏名称 *</label><input id="g_title"></div>
+      <div class="form-row"><label>类别</label><select id="g_category"></select></div>
+      <div class="form-row"><label>平台</label><select id="g_platform"><option value="pc">PC资源(单机)</option><option value="switch">Switch资源</option></select></div>
+      <div class="form-row"><label>标签(逗号分隔,如: 即时战略,经典怀旧)</label><input id="g_tags"></div>
+      <div class="form-row"><label>游戏大小(如 232.6 GB)</label><input id="g_size"></div>
+      <div class="form-row"><label>安装磁盘占用(如 411.6 GB)</label><input id="g_install_size"></div>
+      <div class="form-row"><label>系统要求</label><input id="g_os" placeholder="Windows 10 64bit"></div>
+      <div class="form-row"><label>CPU要求</label><input id="g_cpu" placeholder="Intel i5-4460"></div>
+      <div class="form-row"><label>显卡要求</label><input id="g_gpu" placeholder="GTX 1060 6GB"></div>
+      <div class="form-row"><label>内存要求</label><input id="g_ram" placeholder="16 GB RAM"></div>
+    </div>
+    <div class="form-row"><label>版本说明(如 V1.685|官方简体中文|支持键盘.鼠标.手柄)</label><input id="g_version_note"></div>
+    <div class="form-row"><label>是否首页轮播</label><select id="g_banner"><option value="0">否</option><option value="1">是</option></select></div>
+
+    <div class="upload-box">
+      <div class="hint">封面上传(jpg/png)</div>
+      <input type="file" accept="image/*" onchange="uploadSingle(this,'cover','g_cover')">
+      <div id="g_cover_list"></div>
+      <input type="hidden" id="g_cover">
+    </div>
+    <div class="upload-box">
+      <div class="hint">视频上传(mp4,可选)</div>
+      <input type="file" accept="video/*" onchange="uploadSingle(this,'video','g_video')">
+      <input type="hidden" id="g_video">
+    </div>
+    <div class="upload-box">
+      <div class="hint">游戏截图(可多选)</div>
+      <input type="file" accept="image/*" multiple onchange="uploadScreenshots(this)">
+      <div id="g_shots_list"></div>
+    </div>
+    <div class="upload-box">
+      <div class="hint">游戏安装包(zip/rar/exe/iso 等,可多选)</div>
+      <input type="file" multiple onchange="uploadPackages(this)">
+      <div id="g_files_list"></div>
+    </div>
+    <div class="form-row"><label>游戏介绍(说明图片文字)</label><textarea id="g_description"></textarea></div>
+    <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px">
+      <button class="btn btn-gray" onclick="hideGameModal()">取消</button>
+      <button class="btn" onclick="saveGame()">保存</button>
+    </div>
+  </div>
+</div>
+
+<div id="toast" class="toast"></div>
+
+<script>
+let token = localStorage.getItem('admin_token') || '';
+let editingScreenshots = [], editingFiles = [];
+let keyTotal = 0, keyPage = 1;
+
+function toast(msg, err) {
+  const t = document.getElementById('toast');
+  t.textContent = msg; t.className = 'toast show' + (err ? ' err' : '');
+  setTimeout(() => t.className = 'toast', 2500);
+}
+async function api(path, opts = {}) {
+  opts.headers = Object.assign({'Content-Type': 'application/json'}, opts.headers || {});
+  if (token) opts.headers['Authorization'] = 'Bearer ' + token;
+  if (opts.body && typeof opts.body !== 'string' && !(opts.body instanceof FormData)) {
+    opts.body = JSON.stringify(opts.body);
+  }
+  const res = await fetch(path, opts);
+  if (res.status === 401) { localStorage.removeItem('admin_token'); location.reload(); throw new Error('未登录'); }
+  return res.json();
+}
+
+function adminLogin() {
+  const username = document.getElementById('adminUser').value.trim();
+  const password = document.getElementById('adminPwd').value;
+  fetch('/admin/api/login', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username, password})})
+    .then(r => r.json()).then(res => {
+      if (res.code === 0) { token = res.data.token; localStorage.setItem('admin_token', token); enterPanel(); }
+      else toast(res.msg, true);
+    });
+}
+function logout() { localStorage.removeItem('admin_token'); location.reload(); }
+
+function enterPanel() {
+  document.getElementById('loginPage').style.display = 'none';
+  document.getElementById('mainPage').style.display = 'flex';
+  loadStats(); loadKeys(1); loadGames(); loadCategories();
+}
+function switchTab(tab) {
+  document.querySelectorAll('.nav-tabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
+  ['keys','games','cats'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab));
+}
+
+async function loadStats() {
+  const res = await api('/admin/api/stats');
+  if (res.code !== 0) return;
+  const d = res.data;
+  document.getElementById('statsRow').innerHTML = [
+    ['注册用户', d.users], ['游戏总数', d.games], ['密钥总数', d.keys],
+    ['未使用密钥', d.unused_keys], ['已使用密钥', d.used_keys],
+  ].map(([l, n]) => `<div class="stat-card"><div class="num">${n}</div><div class="label">${l}</div></div>`).join('');
+}
+
+/* ---------- 密钥 ---------- */
+async function generateKeys() {
+  const card_type = document.getElementById('genType').value;
+  const count = parseInt(document.getElementById('genCount').value) || 1;
+  const res = await api('/admin/api/keys/generate', {method: 'POST', body: {card_type, count}});
+  if (res.code !== 0) return toast(res.msg, true);
+  let html = res.data.map(c => `<div>${c} <a href="javascript:void(0)" onclick="copyText('${c}')" style="color:#4a92ff">复制</a></div>`).join('');
+  toast(res.msg);
+  // 展示生成的密钥
+  const w = document.createElement('div');
+  w.className = 'modal-mask';
+  w.innerHTML = `<div class="modal" style="width:420px"><h3>新生成的密钥</h3><div class="keylist">${html}</div>
+    <div style="text-align:right;margin-top:14px"><button class="btn" onclick="this.closest('.modal-mask').remove();loadKeys(1)">知道了</button></div></div>`;
+  document.body.appendChild(w);
+}
+function copyText(t) { navigator.clipboard.writeText(t); toast('已复制'); }
+
+async function loadKeys(page) {
+  keyPage = page || 1;
+  const keyword = document.getElementById('keyKeyword').value.trim();
+  const status = document.getElementById('keyStatus').value;
+  const res = await api(`/admin/api/keys?page=${keyPage}&keyword=${encodeURIComponent(keyword)}&status=${status}`);
+  if (res.code !== 0) return;
+  keyTotal = res.data.total;
+  const rows = res.data.list.map(k => {
+    let st, cls;
+    if (k.status === 0) { st = '未使用'; cls = 'tag-blue'; }
+    else if (k.expired) { st = '已过期'; cls = 'tag-red'; }
+    else { st = '使用中'; cls = 'tag-green'; }
+    return `<tr>
+      <td>${k.id}</td><td style="font-family:Consolas">${k.code}</td>
+      <td><span class="tag tag-gray">${k.card_name}</span></td>
+      <td><span class="tag ${cls}">${st}</span></td>
+      <td>${k.phone || '-'}</td>
+      <td style="max-width:160px;overflow:hidden;text-overflow:ellipsis">${k.machine_code || '-'}</td>
+      <td>${k.expired_at_str || '-'}</td>
+      <td>${k.reset_count}</td>
+      <td>
+        ${k.status === 1 ? `<button class="btn btn-sm" onclick="resetKey(${k.id})">重置(可再用)</button> ` : ''}
+        <button class="btn btn-sm btn-danger" onclick="deleteKey(${k.id})">删除</button>
+      </td></tr>`;
+  }).join('');
+  document.getElementById('keyTable').innerHTML = rows || '<tr><td colspan="9" style="text-align:center;color:#666">暂无数据</td></tr>';
+  const pages = Math.max(1, Math.ceil(keyTotal / 20));
+  document.getElementById('keyPager').innerHTML =
+    `<button ${keyPage<=1?'disabled':''} onclick="loadKeys(${keyPage-1})">上一页</button>
+     <span>第 ${keyPage} / ${pages} 页 · 共 ${keyTotal} 条</span>
+     <button ${keyPage>=pages?'disabled':''} onclick="loadKeys(${keyPage+1})">下一页</button>`;
+}
+async function resetKey(id) {
+  const res = await api(`/admin/api/keys/${id}/reset`, {method: 'POST'});
+  toast(res.msg, res.code !== 0);
+  loadKeys(keyPage);
+}
+async function deleteKey(id) {
+  if (!confirm('确定删除该密钥?')) return;
+  const res = await api(`/admin/api/keys/${id}`, {method: 'DELETE'});
+  toast(res.msg, res.code !== 0);
+  loadKeys(keyPage);
+}
+
+/* ---------- 游戏 ---------- */
+async function loadGames() {
+  const res = await api('/admin/api/games');
+  if (res.code !== 0) return;
+  const rows = res.data.map(g => `<tr>
+    <td>${g.id}</td>
+    <td><img src="${g.cover}" style="width:72px;height:44px;object-fit:cover;border-radius:4px" onerror="this.style.visibility='hidden'"></td>
+    <td>${g.title}</td>
+    <td>${g.category_name || '-'}</td>
+    <td><span class="tag ${g.platform==='pc'?'tag-blue':'tag-green'}">${g.platform==='pc'?'PC':'Switch'}</span></td>
+    <td>${g.size}</td>
+    <td>${g.download_count}</td>
+    <td>
+      <button class="btn btn-sm" onclick='showGameModal(${JSON.stringify(g).replace(/'/g,"&#39;")})'>修改</button>
+      <button class="btn btn-sm btn-danger" onclick="deleteGame(${g.id})">删除</button>
+    </td></tr>`).join('');
+  document.getElementById('gameTable').innerHTML = rows || '<tr><td colspan="8" style="text-align:center;color:#666">暂无数据</td></tr>';
+}
+function showGameModal(g) {
+  editingScreenshots = []; editingFiles = [];
+  if (g) {
+    document.getElementById('gameModalTitle').innerText = '修改游戏';
+    g_id.value = g.id; g_title.value = g.title; g_tags.value = g.tags || '';
+    g_size.value = g.size || ''; g_install_size.value = g.install_size || '';
+    g_os.value = g.os_req || ''; g_cpu.value = g.cpu_req || ''; g_gpu.value = g.gpu_req || ''; g_ram.value = g.ram_req || '';
+    g_version_note.value = g.version_note || ''; g_description.value = g.description || '';
+    g_platform.value = g.platform || 'pc'; g_banner.value = g.is_banner ? '1' : '0';
+    g_cover.value = g.cover || ''; g_video.value = g.video || '';
+    try { editingScreenshots = JSON.parse(g.screenshots || '[]'); } catch(e) {}
+    try { editingFiles = JSON.parse(g.files || '[]'); } catch(e) {}
+    document.getElementById('g_category').value = g.category_id || '';
+  } else {
+    document.getElementById('gameModalTitle').innerText = '上传游戏';
+    document.querySelectorAll('#gameModal input,#gameModal textarea,#gameModal select').forEach(el => { if(el.type!=='file') el.value=''; });
+    g_platform.value = 'pc'; g_banner.value = '0';
+  }
+  renderShots(); renderFiles(); renderCover();
+  document.getElementById('gameModal').classList.remove('hidden');
+}
+function hideGameModal() { document.getElementById('gameModal').classList.add('hidden'); }
+function renderCover() {
+  const url = document.getElementById('g_cover').value;
+  document.getElementById('g_cover_list').innerHTML = url ? `<div class="file-item"><img src="${url}"><span>${url}</span></div>` : '';
+}
+async function uploadSingle(input, type, targetId) {
+  if (!input.files.length) return;
+  const fd = new FormData();
+  fd.append('file', input.files[0]); fd.append('type', type);
+  const res = await api('/admin/api/upload', {method: 'POST', body: fd});
+  if (res.code !== 0) return toast(res.msg, true);
+  document.getElementById(targetId).value = res.data.url;
+  if (targetId === 'g_cover') renderCover();
+  toast('上传成功');
+}
+async function uploadScreenshots(input) {
+  for (const f of input.files) {
+    const fd = new FormData();
+    fd.append('file', f); fd.append('type', 'image');
+    const res = await api('/admin/api/upload', {method: 'POST', body: fd});
+    if (res.code === 0) editingScreenshots.push(res.data.url);
+  }
+  renderShots(); toast('截图上传完成');
+}
+async function uploadPackages(input) {
+  for (const f of input.files) {
+    const fd = new FormData();
+    fd.append('file', f); fd.append('type', 'file');
+    const res = await api('/admin/api/upload', {method: 'POST', body: fd});
+    if (res.code === 0) editingFiles.push({name: res.data.name, size: res.data.size, url: res.data.url});
+  }
+  renderFiles(); toast('安装包上传完成');
+}
+function renderShots() {
+  document.getElementById('g_shots_list').innerHTML = editingScreenshots.map((u, i) =>
+    `<div class="file-item"><img src="${u}"><span>${u}</span><button class="btn btn-sm btn-danger" onclick="editingScreenshots.splice(${i},1);renderShots()">移除</button></div>`).join('');
+}
+function renderFiles() {
+  document.getElementById('g_files_list').innerHTML = editingFiles.map((f, i) =>
+    `<div class="file-item"><span>${f.name}(${f.size})</span><button class="btn btn-sm btn-danger" onclick="editingFiles.splice(${i},1);renderFiles()">移除</button></div>`).join('');
+}
+async function saveGame() {
+  const body = {
+    id: parseInt(g_id.value) || 0,
+    title: g_title.value.trim(), category_id: parseInt(g_category.value) || 0,
+    platform: g_platform.value, tags: g_tags.value.trim(),
+    size: g_size.value.trim(), install_size: g_install_size.value.trim(),
+    os_req: g_os.value.trim(), cpu_req: g_cpu.value.trim(), gpu_req: g_gpu.value.trim(), ram_req: g_ram.value.trim(),
+    version_note: g_version_note.value.trim(), cover: g_cover.value, video: g_video.value,
+    screenshots: JSON.stringify(editingScreenshots), description: g_description.value,
+    files: JSON.stringify(editingFiles), is_banner: g_banner.value === '1',
+  };
+  const res = await api('/admin/api/games', {method: 'POST', body});
+  toast(res.msg, res.code !== 0);
+  if (res.code === 0) { hideGameModal(); loadGames(); loadStats(); }
+}
+async function deleteGame(id) {
+  if (!confirm('确定删除该游戏?')) return;
+  const res = await api(`/admin/api/games/${id}`, {method: 'DELETE'});
+  toast(res.msg, res.code !== 0);
+  loadGames(); loadStats();
+}
+
+/* ---------- 类别 ---------- */
+async function loadCategories() {
+  const res = await api('/admin/api/categories');
+  if (res.code !== 0) return;
+  document.getElementById('g_category').innerHTML = '<option value="">未分类</option>' +
+    res.data.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
+  const gres = await api('/admin/api/games');
+  const cnt = {};
+  (gres.data || []).forEach(g => { cnt[g.category_id] = (cnt[g.category_id] || 0) + 1; });
+  document.getElementById('catTable').innerHTML = res.data.map(c =>
+    `<tr><td>${c.id}</td><td>${c.name}</td><td>${cnt[c.id] || 0}</td>
+     <td><button class="btn btn-sm" onclick="renameCat(${c.id},'${c.name}')">修改名称</button>
+     <button class="btn btn-sm btn-danger" onclick="deleteCat(${c.id})">删除</button></td></tr>`).join('');
+}
+async function addCategory() {
+  const name = document.getElementById('newCatName').value.trim();
+  if (!name) return toast('请填写类别名称', true);
+  const res = await api('/admin/api/categories', {method: 'POST', body: {name}});
+  toast(res.msg, res.code !== 0);
+  if (res.code === 0) { document.getElementById('newCatName').value = ''; loadCategories(); }
+}
+async function renameCat(id, oldName) {
+  const name = prompt('修改类别名称', oldName);
+  if (!name || name === oldName) return;
+  const res = await api('/admin/api/categories', {method: 'POST', body: {id, name}});
+  toast(res.msg, res.code !== 0);
+  loadCategories();
+}
+async function deleteCat(id) {
+  if (!confirm('确定删除该类别?')) return;
+  const res = await api(`/admin/api/categories/${id}`, {method: 'DELETE'});
+  toast(res.msg, res.code !== 0);
+  loadCategories();
+}
+
+document.getElementById('adminPwd').addEventListener('keydown', e => { if (e.key === 'Enter') adminLogin(); });
+if (token) enterPanel();
+</script>
+</body>
+</html>
diff --git a/server/config/db.go b/server/config/db.go
new file mode 100644
index 0000000..2842b89
--- /dev/null
+++ b/server/config/db.go
@@ -0,0 +1,187 @@
+package config
+
+import (
+	"fmt"
+	"log"
+	"time"
+
+	"gamebox-server/models"
+
+	"golang.org/x/crypto/bcrypt"
+	"gorm.io/driver/mysql"
+	"gorm.io/gorm"
+	"gorm.io/gorm/logger"
+)
+
+var DB *gorm.DB
+
+func InitDB() {
+	dsn := "root:123qwe@tcp(127.0.0.1:3306)/gamebox?charset=utf8mb4&parseTime=True&loc=Local"
+	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
+		Logger: logger.Default.LogMode(logger.Warn),
+	})
+	if err != nil {
+		log.Fatalf("连接数据库失败: %v", err)
+	}
+	DB = db
+
+	err = DB.AutoMigrate(
+		&models.Admin{}, &models.User{}, &models.Category{}, &models.Game{},
+		&models.Tool{}, &models.MemberKey{}, &models.Favorite{},
+		&models.LibraryItem{}, &models.Announcement{},
+	)
+	if err != nil {
+		log.Fatalf("数据库迁移失败: %v", err)
+	}
+	fmt.Println("数据库连接成功")
+	seed()
+}
+
+func hashPassword(pwd string) string {
+	b, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
+	return string(b)
+}
+
+func seed() {
+	// 管理员账号
+	var adminCount int64
+	DB.Model(&models.Admin{}).Count(&adminCount)
+	if adminCount == 0 {
+		DB.Create(&models.Admin{Username: "admin", Password: hashPassword("123456")})
+		fmt.Println("已创建管理员账号: admin / 123456")
+	}
+
+	// 类别
+	var catCount int64
+	DB.Model(&models.Category{}).Count(&catCount)
+	if catCount == 0 {
+		cats := []models.Category{
+			{Name: "角色扮演", Sort: 1}, {Name: "动作冒险", Sort: 2},
+			{Name: "射击游戏", Sort: 3}, {Name: "格斗游戏", Sort: 4},
+			{Name: "竞速体育", Sort: 5}, {Name: "模拟经营", Sort: 6},
+			{Name: "即时战略", Sort: 7}, {Name: "经典怀旧", Sort: 8},
+			{Name: "常用工具", Sort: 9},
+		}
+		DB.Create(&cats)
+	}
+
+	// 公告
+	var annCount int64
+	DB.Model(&models.Announcement{}).Count(&annCount)
+	if annCount == 0 {
+		DB.Create(&models.Announcement{Content: "平台客服上班时间:早8点到晚10点!\n下载速度慢的,把下载窗口拍照发给客服看下。\n下载好的游戏,下载完直接创建快捷方式!\n打开盒子资源库,右键安装好的游戏图片,创建快捷方式!\n平台客服在线时间:早8点--晚10点。其余时间请留言\n国产游戏不会有,不用问!都是单机游戏,无法联机!"})
+	}
+
+	// 工具
+	var toolCount int64
+	DB.Model(&models.Tool{}).Count(&toolCount)
+	if toolCount == 0 {
+		tools := []models.Tool{
+			{Name: "DX修复", Size: "435.7 MB", Description: "DirectX修复工具增强版", Cover: "/static/covers/tool_dx.png", FileURL: ""},
+			{Name: "Windows 10 21H2", Size: "13.3 GB", Description: "Windows 10 21H2 系统镜像", Cover: "/static/covers/tool_win10.png", FileURL: ""},
+			{Name: "微软常用运行库合集", Size: "158.6 MB", Description: "Microsoft Common Runtime Libraries", Cover: "/static/covers/tool_runtime.png", FileURL: ""},
+			{Name: "一修大师修改器", Size: "85.3 MB", Description: "一修大师修改器", Cover: "/static/covers/tool_master.png", FileURL: ""},
+			{Name: "NTE游戏运行库等工具", Size: "3.3 GB", Description: "NTE游戏运行库合集", Cover: "/static/covers/tool_nte.png", FileURL: ""},
+			{Name: "免费体验", Size: "387.2 MB", Description: " Plants vs. Zombies 免费体验版", Cover: "/static/covers/tool_pvz.png", FileURL: ""},
+		}
+		DB.Create(&tools)
+	}
+
+	// 示例游戏
+	var gameCount int64
+	DB.Model(&models.Game{}).Count(&gameCount)
+	if gameCount == 0 {
+		var catMap = map[string]uint{}
+		var cats []models.Category
+		DB.Find(&cats)
+		for _, c := range cats {
+			catMap[c.Name] = c.ID
+		}
+		games := []models.Game{
+			{
+				Title: "真·三国无双 起源", CategoryID: catMap["动作冒险"], Platform: "pc", Tags: "动作冒险",
+				Size: "82 GB", InstallSize: "131.3 GB", OSReq: "Windows 10 64bit", CPUReq: "Intel i5-4460 / AMD Ryzen 5 1600",
+				GPUReq: "GTX 1060 6GB / RX 580 8GB", RAMReq: "16 GB RAM",
+				VersionNote: "Build 24|豪华中文版|官方简体中文|支持键盘.鼠标.手柄",
+				Cover: "/static/covers/game1.png", Screenshots: "[]", Files: "[]", IsBanner: true,
+				Description: "真·三国无双 起源(Dynasty Warriors: Origins)豪华中文版,包含全部DLC。\n支持键盘、鼠标、手柄操作。",
+			},
+			{
+				Title: "极限竞速:地平线5 v1.685.421顶级版", CategoryID: catMap["竞速体育"], Platform: "pc", Tags: "竞速体育",
+				Size: "232.6 GB", InstallSize: "411.6 GB", OSReq: "Windows 10 64bit (18362.0及以上)", CPUReq: "Intel i5-4460 or AMD Ryzen 3 1200",
+				GPUReq: "NVIDIA GeForce GTX 1050 4GB / AMD Radeon RX 480 4GB", RAMReq: "16 GB RAM",
+				VersionNote: "V1.685.421顶级版|容量175GB|官方简体中文|支持键盘.鼠标.手柄|赠全车辆收藏.原厂调教涂装.剧情故事全三星.DLC全通存档",
+				Cover: "/static/covers/game2.png", Screenshots: "[]", Files: "[]", IsBanner: true,
+				Description: "V1.685.421顶级版|容量175GB|官方简体中文|支持键盘.鼠标.手柄|赠全车辆收藏.原厂调教涂装.剧情故事全三星.DLC全通存档\n\n【存档使用方法→直往下拉即可】\n1.首先在游戏根目录里把steam_emu.ini里的#AccountId的#去掉,\n2.改成 AccountId=2535446289078643\n3.游戏名字可以改:UserName=xxxxxxxx/随意",
+			},
+			{
+				Title: "使命召唤23:现代战争4/Call of Duty: Modern Warfare IV", CategoryID: catMap["射击游戏"], Platform: "pc", Tags: "射击游戏",
+				Size: "173.8 GB", InstallSize: "340.8 GB", OSReq: "Windows 10 64bit", CPUReq: "Intel i5-4460 / AMD Ryzen 3 1200",
+				GPUReq: "GTX 1060 6GB / RX 580 8GB", RAMReq: "16 GB RAM",
+				VersionNote: "V1.0|容量160GB|官方简体中文|支持键盘.鼠标",
+				Cover: "/static/covers/game3.png", Screenshots: "[]", Files: "[]", IsBanner: true,
+				Description: "使命召唤23:现代战争4 精简版系统玩不了!打开系统安全中心,关闭实时防护后再运行游戏。",
+			},
+			{
+				Title: "我独自升级 起立·觉醒豪华中文版v1.1.100", CategoryID: catMap["角色扮演"], Platform: "pc", Tags: "角色扮演",
+				Size: "53.9 GB", InstallSize: "95.3 GB", OSReq: "Windows 10 / 11", CPUReq: "i5 4460 3.2 GHz Or AMD equivalent",
+				GPUReq: "GTX1060 / Radeon RX 580", RAMReq: "16 GB RAM",
+				VersionNote: "V1.1.100|容量44.9GB|官方简体中文|支持键盘.鼠标.手柄",
+				Cover: "/static/covers/game4.png", Screenshots: "[]", Files: "[]", IsBanner: true,
+				Description: "V1.1.100|容量44.9GB|官方简体中文|支持键盘.鼠标.手柄\n含齐州岛攻略队特别篇章+全DLC。",
+			},
+			{
+				Title: "红警2/红色警戒2高清版(游戏菜单界面中文)", CategoryID: catMap["经典怀旧"], Platform: "pc", Tags: "即时战略,经典怀旧",
+				Size: "3.3 GB", InstallSize: "5 GB", OSReq: "Windows 7/10/11", CPUReq: "Intel Core 2 Duo",
+				GPUReq: "集成显卡", RAMReq: "4 GB RAM",
+				VersionNote: "高清版|容量3.3GB|中文|右键打开游戏安装目录,然后按照游戏详情页教程运行",
+				Cover: "/static/covers/game5.png", Screenshots: "[]", Files: "[]",
+				Description: "右键打开游戏安装目录,然后按照游戏详情页的教程运行游戏即可。",
+			},
+			{
+				Title: "女神异闻录5皇家版", CategoryID: catMap["角色扮演"], Platform: "switch", Tags: "角色扮演",
+				Size: "31.6 GB", InstallSize: "40 GB", OSReq: "Windows 10 64bit(需模拟器)", CPUReq: "Intel i5-8400 / AMD Ryzen 5 3600",
+				GPUReq: "GTX 1650 4GB", RAMReq: "16 GB RAM",
+				VersionNote: "皇家版|容量31.6GB|官方简体中文|需Yuzu/Ryujinx模拟器",
+				Cover: "/static/covers/game6.png", Screenshots: "[]", Files: "[]",
+				Description: "设置中文:先打开模拟器,右击游戏图片,选择属性,语言设置为简体中文。",
+			},
+			{
+				Title: "塞尔达传说:旷野之息", CategoryID: catMap["动作冒险"], Platform: "switch", Tags: "动作冒险",
+				Size: "38.9 GB", InstallSize: "45 GB", OSReq: "Windows 10 64bit(需模拟器)", CPUReq: "Intel i5-8400 / AMD Ryzen 5 3600",
+				GPUReq: "GTX 1650 4GB", RAMReq: "16 GB RAM",
+				VersionNote: "Switch版|容量38.9GB|中文|需Yuzu/Ryujinx模拟器",
+				Cover: "/static/covers/game7.png", Screenshots: "[]", Files: "[]",
+				Description: "点击启动运行游戏即可,建议使用YuzuEA最新版模拟器。",
+			},
+			{
+				Title: "精灵宝可梦Let's Go!皮卡丘", CategoryID: catMap["角色扮演"], Platform: "switch", Tags: "角色扮演",
+				Size: "4.1 GB", InstallSize: "6 GB", OSReq: "Windows 10 64bit(需模拟器)", CPUReq: "Intel i5-8400",
+				GPUReq: "GTX 1650 4GB", RAMReq: "16 GB RAM",
+				VersionNote: "Switch版|容量4.1GB|中文|需模拟器",
+				Cover: "/static/covers/game8.png", Screenshots: "[]", Files: "[]",
+				Description: "点击启动运行游戏即可。",
+			},
+			{
+				Title: "鬼武者:剑之道 Build.24769601+预购特典", CategoryID: catMap["动作冒险"], Platform: "pc", Tags: "动作冒险",
+				Size: "131.3 GB", InstallSize: "180 GB", OSReq: "Windows 10 64bit", CPUReq: "Intel i5-4460",
+				GPUReq: "GTX 1060 6GB", RAMReq: "16 GB RAM",
+				VersionNote: "Build.24769601|豪华中文版|支持键盘.鼠标.手柄",
+				Cover: "/static/covers/game9.png", Screenshots: "[]", Files: "[]",
+				Description: "鬼武者:剑之道 豪华中文版,包含预购特典。",
+			},
+			{
+				Title: "使命召唤20:现代战争3/Call of Duty: MW III", CategoryID: catMap["射击游戏"], Platform: "pc", Tags: "射击游戏",
+				Size: "340.8 GB", InstallSize: "500 GB", OSReq: "Windows 10 64bit", CPUReq: "Intel i5-4460",
+				GPUReq: "GTX 1060 6GB", RAMReq: "16 GB RAM",
+				VersionNote: "V1.0|容量300GB|官方简体中文",
+				Cover: "/static/covers/game10.png", Screenshots: "[]", Files: "[]",
+				Description: "使命召唤20:现代战争3 完整版。",
+			},
+		}
+		DB.Create(&games)
+	}
+
+	// 更新时间戳,让"最新更新"排序有区分度
+	DB.Exec("UPDATE games SET updated_at = ? WHERE updated_at = ?", time.Now(), time.Time{})
+}
diff --git a/server/go.mod b/server/go.mod
new file mode 100644
index 0000000..41bee40
--- /dev/null
+++ b/server/go.mod
@@ -0,0 +1,45 @@
+module gamebox-server
+
+go 1.24
+
+require (
+	github.com/gin-gonic/gin v1.10.0
+	github.com/golang-jwt/jwt/v5 v5.2.1
+	github.com/mojocn/base64Captcha v1.3.6
+	golang.org/x/crypto v0.31.0
+	gorm.io/driver/mysql v1.5.7
+	gorm.io/gorm v1.25.12
+)
+
+require (
+	github.com/bytedance/sonic v1.11.6 // indirect
+	github.com/bytedance/sonic/loader v0.1.1 // indirect
+	github.com/cloudwego/base64x v0.1.4 // indirect
+	github.com/cloudwego/iasm v0.2.0 // indirect
+	github.com/gabriel-vasile/mimetype v1.4.3 // indirect
+	github.com/gin-contrib/sse v0.1.0 // indirect
+	github.com/go-playground/locales v0.14.1 // indirect
+	github.com/go-playground/universal-translator v0.18.1 // indirect
+	github.com/go-playground/validator/v10 v10.20.0 // indirect
+	github.com/go-sql-driver/mysql v1.7.0 // indirect
+	github.com/goccy/go-json v0.10.2 // indirect
+	github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
+	github.com/jinzhu/inflection v1.0.0 // indirect
+	github.com/jinzhu/now v1.1.5 // indirect
+	github.com/json-iterator/go v1.1.12 // indirect
+	github.com/klauspost/cpuid/v2 v2.2.7 // indirect
+	github.com/leodido/go-urn v1.4.0 // indirect
+	github.com/mattn/go-isatty v0.0.20 // indirect
+	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+	github.com/modern-go/reflect2 v1.0.2 // indirect
+	github.com/pelletier/go-toml/v2 v2.2.2 // indirect
+	github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
+	github.com/ugorji/go/codec v1.2.12 // indirect
+	golang.org/x/arch v0.8.0 // indirect
+	golang.org/x/image v0.13.0 // indirect
+	golang.org/x/net v0.25.0 // indirect
+	golang.org/x/sys v0.28.0 // indirect
+	golang.org/x/text v0.21.0 // indirect
+	google.golang.org/protobuf v1.34.1 // indirect
+	gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/server/go.sum b/server/go.sum
new file mode 100644
index 0000000..8560232
--- /dev/null
+++ b/server/go.sum
@@ -0,0 +1,138 @@
+github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
+github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
+github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
+github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
+github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
+github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
+github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
+github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
+github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
+github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
+github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
+github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
+github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
+github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
+github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
+github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
+github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
+github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
+github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
+github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
+github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
+github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
+github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
+github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
+github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
+github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
+github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/mojocn/base64Captcha v1.3.6 h1:gZEKu1nsKpttuIAQgWHO+4Mhhls8cAKyiV2Ew03H+Tw=
+github.com/mojocn/base64Captcha v1.3.6/go.mod h1:i5CtHvm+oMbj1UzEPXaA8IH/xHFZ3DGY3Wh3dBpZ28E=
+github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
+github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
+github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
+github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
+golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
+golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
+golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
+golang.org/x/image v0.13.0 h1:3cge/F/QTkNLauhf2QoE9zp+7sr+ZcL4HnoZmdwg9sg=
+golang.org/x/image v0.13.0/go.mod h1:6mmbMOeV28HuMTgA6OSRkdXKYw/t5W9Uwn2Yv1r3Yxk=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
+golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
+golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
+golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
+golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
+google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
+gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
+gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
+gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
+gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
+nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
+rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
diff --git a/server/handlers/admin.go b/server/handlers/admin.go
new file mode 100644
index 0000000..0dfba1c
--- /dev/null
+++ b/server/handlers/admin.go
@@ -0,0 +1,299 @@
+package handlers
+
+import (
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strconv"
+	"strings"
+	"time"
+
+	"gamebox-server/config"
+	"gamebox-server/models"
+	"gamebox-server/utils"
+
+	"github.com/gin-gonic/gin"
+	"golang.org/x/crypto/bcrypt"
+)
+
+// ---------- 管理员登录 ----------
+
+func AdminLogin(c *gin.Context) {
+	var req struct {
+		Username string `json:"username"`
+		Password string `json:"password"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
+		return
+	}
+	var admin models.Admin
+	if err := config.DB.Where("username = ?", req.Username).First(&admin).Error; err != nil ||
+		bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(req.Password)) != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户名或密码错误"})
+		return
+	}
+	token, _ := utils.GenerateToken(admin.ID, admin.Username, "admin")
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"token": token}})
+}
+
+// ---------- 密钥管理 ----------
+
+// GenerateKeys 批量生成密钥
+func GenerateKeys(c *gin.Context) {
+	var req struct {
+		CardType string `json:"card_type"` // day/month/year
+		Count    int    `json:"count"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil || cardDuration(req.CardType) == 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "卡密类型错误"})
+		return
+	}
+	if req.Count < 1 || req.Count > 100 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "生成数量需在1-100之间"})
+		return
+	}
+	codes := make([]string, 0, req.Count)
+	for i := 0; i < req.Count; i++ {
+		key := models.MemberKey{Code: utils.GenerateKeyCode(), CardType: req.CardType}
+		if err := config.DB.Create(&key).Error; err == nil {
+			codes = append(codes, key.Code)
+		}
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": fmt.Sprintf("成功生成 %d 个密钥", len(codes)), "data": codes})
+}
+
+// ListKeys 密钥列表
+func ListKeys(c *gin.Context) {
+	keyword := c.Query("keyword")
+	status := c.Query("status") // ""全部 0未使用 1已使用 2已过期
+	query := config.DB.Model(&models.MemberKey{})
+	if keyword != "" {
+		query = query.Where("code LIKE ?", "%"+keyword+"%")
+	}
+	switch status {
+	case "0":
+		query = query.Where("status = ?", 0)
+	case "1":
+		query = query.Where("status = ? AND expired_at > ?", 1, time.Now())
+	case "2":
+		query = query.Where("status = ? AND expired_at <= ?", 1, time.Now())
+	}
+	var total int64
+	query.Count(&total)
+	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
+	if page < 1 {
+		page = 1
+	}
+	var keys []models.MemberKey
+	query.Order("id DESC").Offset((page - 1) * 20).Limit(20).Find(&keys)
+	// 附带用户手机号
+	userIDs := make([]uint, 0)
+	for _, k := range keys {
+		if k.UserID > 0 {
+			userIDs = append(userIDs, k.UserID)
+		}
+	}
+	phoneMap := map[uint]string{}
+	if len(userIDs) > 0 {
+		var users []models.User
+		config.DB.Where("id IN ?", userIDs).Find(&users)
+		for _, u := range users {
+			phoneMap[u.ID] = u.Phone
+		}
+	}
+	type keyVO struct {
+		models.MemberKey
+		CardName  string  `json:"card_name"`
+		Phone     string  `json:"phone"`
+		Expired   bool    `json:"expired"`
+		ExpiredAtStr *string `json:"expired_at_str"`
+	}
+	list := make([]keyVO, 0, len(keys))
+	for _, k := range keys {
+		vo := keyVO{MemberKey: k, CardName: k.CardName(), Phone: phoneMap[k.UserID]}
+		if k.ExpiredAt != nil {
+			vo.Expired = k.ExpiredAt.Before(time.Now())
+			s := k.ExpiredAt.Format("2006-01-02 15:04:05")
+			vo.ExpiredAtStr = &s
+		}
+		list = append(list, vo)
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"list": list, "total": total, "page": page}})
+}
+
+// ResetKey 管理员重置密钥(解绑机器,可再次使用)
+func ResetKey(c *gin.Context) {
+	id := c.Param("id")
+	var key models.MemberKey
+	if err := config.DB.First(&key, id).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "密钥不存在"})
+		return
+	}
+	config.DB.Model(&key).Updates(map[string]interface{}{
+		"status":       0,
+		"user_id":      0,
+		"machine_code": "",
+		"activated_at": nil,
+		"expired_at":   nil,
+	})
+	config.DB.Model(&key).UpdateColumn("reset_count", key.ResetCount+1)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密钥已重置,可重新使用"})
+}
+
+// DeleteKey 删除密钥
+func DeleteKey(c *gin.Context) {
+	config.DB.Delete(&models.MemberKey{}, c.Param("id"))
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
+}
+
+// ---------- 游戏管理 ----------
+
+func AdminListGames(c *gin.Context) {
+	var games []models.Game
+	config.DB.Order("id DESC").Find(&games)
+	fillCategoryName(&games)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": games})
+}
+
+func AdminSaveGame(c *gin.Context) {
+	var game models.Game
+	if err := c.ShouldBindJSON(&game); err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误: " + err.Error()})
+		return
+	}
+	if game.Title == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写游戏名称"})
+		return
+	}
+	if game.Screenshots == "" {
+		game.Screenshots = "[]"
+	}
+	if game.Files == "" {
+		game.Files = "[]"
+	}
+	if game.ID == 0 {
+		config.DB.Create(&game)
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "添加成功", "data": game})
+	} else {
+		config.DB.Model(&models.Game{}).Where("id = ?", game.ID).Updates(map[string]interface{}{
+			"title": game.Title, "category_id": game.CategoryID, "platform": game.Platform,
+			"tags": game.Tags, "size": game.Size, "install_size": game.InstallSize,
+			"os_req": game.OSReq, "cpu_req": game.CPUReq, "gpu_req": game.GPUReq, "ram_req": game.RAMReq,
+			"version_note": game.VersionNote, "cover": game.Cover, "video": game.Video,
+			"screenshots": game.Screenshots, "description": game.Description, "files": game.Files,
+			"is_banner": game.IsBanner,
+		})
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "修改成功"})
+	}
+}
+
+func AdminDeleteGame(c *gin.Context) {
+	config.DB.Delete(&models.Game{}, c.Param("id"))
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
+}
+
+// ---------- 类别管理 ----------
+
+func AdminListCategories(c *gin.Context) {
+	var cats []models.Category
+	config.DB.Order("sort ASC").Find(&cats)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": cats})
+}
+
+func AdminSaveCategory(c *gin.Context) {
+	var cat models.Category
+	if err := c.ShouldBindJSON(&cat); err != nil || cat.Name == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写类别名称"})
+		return
+	}
+	if cat.ID == 0 {
+		if err := config.DB.Create(&cat).Error; err != nil {
+			c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该类别已存在"})
+			return
+		}
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "添加成功"})
+	} else {
+		config.DB.Model(&models.Category{}).Where("id = ?", cat.ID).Update("name", cat.Name)
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "修改成功"})
+	}
+}
+
+func AdminDeleteCategory(c *gin.Context) {
+	id := c.Param("id")
+	var count int64
+	config.DB.Model(&models.Game{}).Where("category_id = ?", id).Count(&count)
+	if count > 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": fmt.Sprintf("该类别下还有 %d 个游戏,请先移出或删除", count)})
+		return
+	}
+	config.DB.Delete(&models.Category{}, id)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
+}
+
+// ---------- 上传 ----------
+
+var allowedExts = map[string]bool{
+	".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true,
+	".mp4": true, ".mkv": true, ".avi": true, ".webm": true,
+	".zip": true, ".rar": true, ".7z": true, ".exe": true, ".iso": true, ".torrent": true,
+}
+
+// UploadFile 通用文件上传 type: cover/video/image/file
+func UploadFile(c *gin.Context) {
+	file, err := c.FormFile("file")
+	if err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请选择文件"})
+		return
+	}
+	ext := strings.ToLower(filepath.Ext(file.Filename))
+	if !allowedExts[ext] {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "不支持的文件类型: " + ext})
+		return
+	}
+	fType := c.DefaultPostForm("type", "file")
+	dir := filepath.Join("uploads", fType)
+	os.MkdirAll(dir, 0755)
+	filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
+	dst := filepath.Join(dir, filename)
+	if err := c.SaveUploadedFile(file, dst); err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "保存文件失败"})
+		return
+	}
+	sizeStr := formatSize(file.Size)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
+		"url":  "/static/" + fType + "/" + filename,
+		"name": file.Filename,
+		"size": sizeStr,
+	}})
+}
+
+func formatSize(n int64) string {
+	f := float64(n)
+	if f > 1024*1024*1024 {
+		return fmt.Sprintf("%.2f GB", f/1024/1024/1024)
+	}
+	if f > 1024*1024 {
+		return fmt.Sprintf("%.2f MB", f/1024/1024)
+	}
+	return fmt.Sprintf("%.2f KB", f/1024)
+}
+
+// ---------- 统计 ----------
+
+func AdminStats(c *gin.Context) {
+	var users, games, keys, unusedKeys, usedKeys int64
+	config.DB.Model(&models.User{}).Count(&users)
+	config.DB.Model(&models.Game{}).Count(&games)
+	config.DB.Model(&models.MemberKey{}).Count(&keys)
+	config.DB.Model(&models.MemberKey{}).Where("status = ?", 0).Count(&unusedKeys)
+	config.DB.Model(&models.MemberKey{}).Where("status = ?", 1).Count(&usedKeys)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
+		"users": users, "games": games, "keys": keys,
+		"unused_keys": unusedKeys, "used_keys": usedKeys,
+	}})
+}
+
+var _ = io.Discard
diff --git a/server/handlers/auth.go b/server/handlers/auth.go
new file mode 100644
index 0000000..f6fe7c2
--- /dev/null
+++ b/server/handlers/auth.go
@@ -0,0 +1,177 @@
+package handlers
+
+import (
+	"net/http"
+	"time"
+
+	"gamebox-server/config"
+	"gamebox-server/models"
+	"gamebox-server/utils"
+
+	"github.com/gin-gonic/gin"
+	"github.com/mojocn/base64Captcha"
+	"golang.org/x/crypto/bcrypt"
+)
+
+var captchaStore = base64Captcha.NewMemoryStore(1024, 10*time.Minute)
+
+func newCaptchaDriver() *base64Captcha.DriverString {
+	return base64Captcha.NewDriverString(40, 120, 2, 2, 4,
+		"1234567890", nil, nil, nil)
+}
+
+// GetCaptcha 获取图形验证码
+func GetCaptcha(c *gin.Context) {
+	drv := newCaptchaDriver()
+	captcha := base64Captcha.NewCaptcha(drv, captchaStore)
+	id, b64s, _, err := captcha.Generate()
+	if err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "验证码生成失败"})
+		return
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"captcha_id": id, "captcha_image": b64s}})
+}
+
+func verifyCaptcha(id, value string) bool {
+	if id == "" || value == "" {
+		return false
+	}
+	return captchaStore.Verify(id, value, true)
+}
+
+// Register 注册账号
+func Register(c *gin.Context) {
+	var req struct {
+		Phone    string `json:"phone"`
+		Password string `json:"password"`
+		Confirm  string `json:"confirm"`
+		CaptchaID string `json:"captcha_id"`
+		Captcha  string `json:"captcha"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
+		return
+	}
+	if len(req.Phone) != 11 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请输入正确的11位手机号"})
+		return
+	}
+	if len(req.Password) < 6 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "密码至少6位"})
+		return
+	}
+	if req.Password != req.Confirm {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "两次输入的密码不一致"})
+		return
+	}
+	if !verifyCaptcha(req.CaptchaID, req.Captcha) {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "图形验证码错误"})
+		return
+	}
+	var count int64
+	config.DB.Model(&models.User{}).Where("phone = ?", req.Phone).Count(&count)
+	if count > 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该手机号已注册"})
+		return
+	}
+	hash, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
+	user := models.User{Phone: req.Phone, Password: string(hash)}
+	if err := config.DB.Create(&user).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "注册失败"})
+		return
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "注册成功"})
+}
+
+// Login 登录
+func Login(c *gin.Context) {
+	var req struct {
+		Phone    string `json:"phone"`
+		Password string `json:"password"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil || req.Phone == "" || req.Password == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请输入账号和密码"})
+		return
+	}
+	var user models.User
+	if err := config.DB.Where("phone = ?", req.Phone).First(&user).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "账号或密码错误"})
+		return
+	}
+	if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)) != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "账号或密码错误"})
+		return
+	}
+	token, _ := utils.GenerateToken(user.ID, user.Phone, "user")
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
+		"token": token,
+		"user": gin.H{
+			"id":    user.ID,
+			"phone": user.Phone,
+		},
+	}})
+}
+
+// ResetPassword 找回密码
+func ResetPassword(c *gin.Context) {
+	var req struct {
+		Phone     string `json:"phone"`
+		Password  string `json:"password"`
+		Confirm   string `json:"confirm"`
+		CaptchaID string `json:"captcha_id"`
+		Captcha   string `json:"captcha"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
+		return
+	}
+	if !verifyCaptcha(req.CaptchaID, req.Captcha) {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "图形验证码错误"})
+		return
+	}
+	var user models.User
+	if err := config.DB.Where("phone = ?", req.Phone).First(&user).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该手机号未注册"})
+		return
+	}
+	if len(req.Password) < 6 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "密码至少6位"})
+		return
+	}
+	if req.Password != req.Confirm {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "两次输入的密码不一致"})
+		return
+	}
+	hash, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
+	config.DB.Model(&user).Update("password", string(hash))
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码重置成功"})
+}
+
+// GetUserInfo 当前用户信息(含会员状态)
+func GetUserInfo(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var user models.User
+	if err := config.DB.First(&user, userID).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户不存在"})
+		return
+	}
+	// 查询会员有效期(取最大的未过期时间)
+	var keys []models.MemberKey
+	config.DB.Where("user_id = ? AND expired_at > ?", userID, time.Now()).Find(&keys)
+	var expire *time.Time
+	for i := range keys {
+		if expire == nil || keys[i].ExpiredAt.After(*expire) {
+			expire = keys[i].ExpiredAt
+		}
+	}
+	member := gin.H{"is_member": expire != nil}
+	if expire != nil {
+		member["expire_at"] = expire.Format("2006-01-02 15:04:05")
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
+		"id":    user.ID,
+		"phone": user.Phone,
+		"no":    user.ID,
+		"member": member,
+	}})
+}
diff --git a/server/handlers/games.go b/server/handlers/games.go
new file mode 100644
index 0000000..a4de35d
--- /dev/null
+++ b/server/handlers/games.go
@@ -0,0 +1,221 @@
+package handlers
+
+import (
+	"net/http"
+	"strconv"
+	"time"
+
+	"gamebox-server/config"
+	"gamebox-server/models"
+
+	"github.com/gin-gonic/gin"
+)
+
+func fillCategoryName(games *[]models.Game) {
+	var cats []models.Category
+	config.DB.Find(&cats)
+	catMap := map[uint]string{}
+	for _, c := range cats {
+		catMap[c.ID] = c.Name
+	}
+	for i := range *games {
+		(*games)[i].CategoryName = catMap[(*games)[i].CategoryID]
+	}
+}
+
+// GetGames 游戏列表 platform: all/pc/switch
+func GetGames(c *gin.Context) {
+	platform := c.DefaultQuery("platform", "all")
+	categoryID := c.DefaultQuery("category", "0")
+	keyword := c.Query("keyword")
+	sort := c.DefaultQuery("sort", "updated")
+
+	query := config.DB.Model(&models.Game{})
+	if platform == "pc" || platform == "switch" {
+		query = query.Where("platform = ?", platform)
+	}
+	if catID, err := strconv.Atoi(categoryID); err == nil && catID > 0 {
+		query = query.Where("category_id = ?", catID)
+	}
+	if keyword != "" {
+		query = query.Where("title LIKE ?", "%"+keyword+"%")
+	}
+	switch sort {
+	case "updated":
+		query = query.Order("updated_at DESC")
+	case "rank":
+		query = query.Order("download_count DESC")
+	case "size":
+		query = query.Order("updated_at DESC")
+	case "hot":
+		query = query.Order("download_count DESC")
+	default:
+		query = query.Order("updated_at DESC")
+	}
+	var games []models.Game
+	query.Find(&games)
+	fillCategoryName(&games)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": games})
+}
+
+// GetBanners 首页轮播
+func GetBanners(c *gin.Context) {
+	var games []models.Game
+	config.DB.Where("is_banner = ?", true).Order("updated_at DESC").Limit(5).Find(&games)
+	fillCategoryName(&games)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": games})
+}
+
+// GetGameDetail 游戏详情
+func GetGameDetail(c *gin.Context) {
+	id := c.Param("id")
+	var game models.Game
+	if err := config.DB.First(&game, id).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "游戏不存在"})
+		return
+	}
+	fillCategoryName(&[]models.Game{game})
+	// 用户维度附加信息
+	resp := gin.H{"game": game}
+	if uid := c.GetUint("user_id"); uid > 0 {
+		var favCount, libCount int64
+		config.DB.Model(&models.Favorite{}).Where("user_id = ? AND game_id = ?", uid, game.ID).Count(&favCount)
+		config.DB.Model(&models.LibraryItem{}).Where("user_id = ? AND game_id = ?", uid, game.ID).Count(&libCount)
+		resp["is_favorite"] = favCount > 0
+		resp["in_library"] = libCount > 0
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": resp})
+}
+
+// GetCategories 类别列表
+func GetCategories(c *gin.Context) {
+	var cats []models.Category
+	config.DB.Order("sort ASC").Find(&cats)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": cats})
+}
+
+// GetTools 工具列表
+func GetTools(c *gin.Context) {
+	var tools []models.Tool
+	config.DB.Order("id ASC").Find(&tools)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": tools})
+}
+
+// GetAnnouncements 公告
+func GetAnnouncements(c *gin.Context) {
+	var anns []models.Announcement
+	config.DB.Order("id DESC").Limit(10).Find(&anns)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": anns})
+}
+
+// ToggleFavorite 收藏/取消收藏
+func ToggleFavorite(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var req struct {
+		GameID uint `json:"game_id"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil || req.GameID == 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
+		return
+	}
+	var fav models.Favorite
+	err := config.DB.Where("user_id = ? AND game_id = ?", userID, req.GameID).First(&fav).Error
+	if err == nil {
+		config.DB.Delete(&fav)
+		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"favorited": false}, "msg": "已取消收藏"})
+		return
+	}
+	config.DB.Create(&models.Favorite{UserID: userID, GameID: req.GameID})
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"favorited": true}, "msg": "加入收藏成功!"})
+}
+
+// GetFavorites 我的收藏
+func GetFavorites(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var favs []models.Favorite
+	config.DB.Where("user_id = ?", userID).Order("id DESC").Find(&favs)
+	gameIDs := make([]uint, 0, len(favs))
+	for _, f := range favs {
+		gameIDs = append(gameIDs, f.GameID)
+	}
+	games := []models.Game{}
+	if len(gameIDs) > 0 {
+		config.DB.Where("id IN ?", gameIDs).Find(&games)
+		fillCategoryName(&games)
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": games})
+}
+
+// AddToLibrary 加入资源库
+func AddToLibrary(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var req struct {
+		GameID uint `json:"game_id"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil || req.GameID == 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
+		return
+	}
+	var count int64
+	config.DB.Model(&models.LibraryItem{}).Where("user_id = ? AND game_id = ?", userID, req.GameID).Count(&count)
+	if count > 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已在资源库中"})
+		return
+	}
+	config.DB.Create(&models.LibraryItem{UserID: userID, GameID: req.GameID})
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "兑换成功!"})
+}
+
+// GetLibrary 我的资源库
+func GetLibrary(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var items []models.LibraryItem
+	config.DB.Where("user_id = ?", userID).Order("id DESC").Find(&items)
+	gameIDs := make([]uint, 0, len(items))
+	for _, f := range items {
+		gameIDs = append(gameIDs, f.GameID)
+	}
+	games := []models.Game{}
+	if len(gameIDs) > 0 {
+		config.DB.Where("id IN ?", gameIDs).Find(&games)
+		fillCategoryName(&games)
+	}
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": games})
+}
+
+// RemoveFromLibrary 移出资源库(卸载)
+func RemoveFromLibrary(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	gameID := c.Param("gameId")
+	config.DB.Where("user_id = ? AND game_id = ?", userID, gameID).Delete(&models.LibraryItem{})
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已移出资源库"})
+}
+
+// GetDownloadInfo 获取游戏下载地址(需要有效会员)
+func GetDownloadInfo(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	gameID := c.Param("id")
+	var game models.Game
+	if err := config.DB.First(&game, gameID).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "游戏不存在"})
+		return
+	}
+	// 校验会员是否有效
+	var keys []models.MemberKey
+	config.DB.Where("user_id = ? AND expired_at > ?", userID, time.Now()).Find(&keys)
+	if len(keys) == 0 {
+		c.JSON(http.StatusOK, gin.H{"code": 2, "msg": "您的会员已到期,无法下载游戏。请激活新的会员密钥!"})
+		return
+	}
+	// 加入资源库 & 下载计数
+	var count int64
+	config.DB.Model(&models.LibraryItem{}).Where("user_id = ? AND game_id = ?", userID, game.ID).Count(&count)
+	if count == 0 {
+		config.DB.Create(&models.LibraryItem{UserID: userID, GameID: game.ID})
+	}
+	config.DB.Model(&game).UpdateColumn("download_count", game.DownloadCount+1)
+	c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
+		"title": game.Title,
+		"files": game.Files,
+	}})
+}
diff --git a/server/handlers/keys.go b/server/handlers/keys.go
new file mode 100644
index 0000000..fceea00
--- /dev/null
+++ b/server/handlers/keys.go
@@ -0,0 +1,76 @@
+package handlers
+
+import (
+	"net/http"
+	"time"
+
+	"gamebox-server/config"
+	"gamebox-server/models"
+
+	"github.com/gin-gonic/gin"
+)
+
+func cardDuration(cardType string) time.Duration {
+	switch cardType {
+	case "day":
+		return 24 * time.Hour
+	case "month":
+		return 30 * 24 * time.Hour
+	case "year":
+		return 365 * 24 * time.Hour
+	}
+	return 0
+}
+
+// ActivateKey 激活会员密钥(绑定机器)
+func ActivateKey(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var req struct {
+		Code        string `json:"code"`
+		MachineCode string `json:"machine_code"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil || req.Code == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请输入激活码"})
+		return
+	}
+	if req.MachineCode == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "获取机器码失败"})
+		return
+	}
+	var key models.MemberKey
+	if err := config.DB.Where("code = ?", req.Code).First(&key).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "激活码不存在,请检查后重新输入"})
+		return
+	}
+
+	now := time.Now()
+	if key.Status == 0 {
+		// 未使用,直接激活
+		expired := now.Add(cardDuration(key.CardType))
+		config.DB.Model(&key).Updates(map[string]interface{}{
+			"status":       1,
+			"user_id":      userID,
+			"machine_code": req.MachineCode,
+			"activated_at": now,
+			"expired_at":   expired,
+		})
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "激活成功!", "data": gin.H{
+			"expire_at": expired.Format("2006-01-02 15:04:05"),
+		}})
+		return
+	}
+
+	// 已使用的密钥
+	if key.MachineCode != req.MachineCode {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已在其他电脑上使用,无法在此设备激活!"})
+		return
+	}
+	if key.ExpiredAt != nil && key.ExpiredAt.Before(now) {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已过期,请使用新的激活码!"})
+		return
+	}
+	// 同机器重复激活,返回当前有效期
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "该激活码已在此设备激活", "data": gin.H{
+		"expire_at": key.ExpiredAt.Format("2006-01-02 15:04:05"),
+	}})
+}
diff --git a/server/main.go b/server/main.go
new file mode 100644
index 0000000..77abc99
--- /dev/null
+++ b/server/main.go
@@ -0,0 +1,76 @@
+package main
+
+import (
+	"gamebox-server/config"
+	"gamebox-server/handlers"
+	"gamebox-server/middleware"
+
+	"github.com/gin-gonic/gin"
+)
+
+func main() {
+	config.InitDB()
+
+	r := gin.Default()
+	r.MaxMultipartMemory = 64 << 20 // 64MB
+
+	// 静态资源(封面/视频/游戏包)
+	r.Static("/static", "./uploads")
+
+	// ---------- 客户端 API ----------
+	api := r.Group("/api")
+	{
+		api.GET("/captcha", handlers.GetCaptcha)
+		api.POST("/register", handlers.Register)
+		api.POST("/login", handlers.Login)
+		api.POST("/reset_password", handlers.ResetPassword)
+		api.GET("/categories", handlers.GetCategories)
+		api.GET("/games", handlers.GetGames)
+		api.GET("/banners", handlers.GetBanners)
+		api.GET("/tools", handlers.GetTools)
+		api.GET("/announcements", handlers.GetAnnouncements)
+		api.GET("/games/:id", handlers.GetGameDetail) // 支持可选登录
+
+		auth := api.Group("", middleware.UserAuth())
+		{
+			auth.GET("/user/info", handlers.GetUserInfo)
+			auth.POST("/favorites", handlers.ToggleFavorite)
+			auth.GET("/favorites", handlers.GetFavorites)
+			auth.POST("/library", handlers.AddToLibrary)
+			auth.GET("/library", handlers.GetLibrary)
+			auth.DELETE("/library/:gameId", handlers.RemoveFromLibrary)
+			auth.GET("/download/:id", handlers.GetDownloadInfo)
+			auth.POST("/keys/activate", handlers.ActivateKey)
+		}
+	}
+
+	// ---------- 管理后台 ----------
+	r.GET("/admin", func(c *gin.Context) {
+		c.File("./admin/index.html")
+	})
+	admin := r.Group("/admin/api")
+	{
+		admin.POST("/login", handlers.AdminLogin)
+
+		a := admin.Group("", middleware.AdminAuth())
+		{
+			a.GET("/stats", handlers.AdminStats)
+			a.GET("/keys", handlers.ListKeys)
+			a.POST("/keys/generate", handlers.GenerateKeys)
+			a.POST("/keys/:id/reset", handlers.ResetKey)
+			a.DELETE("/keys/:id", handlers.DeleteKey)
+
+			a.GET("/games", handlers.AdminListGames)
+			a.POST("/games", handlers.AdminSaveGame)
+			a.DELETE("/games/:id", handlers.AdminDeleteGame)
+
+			a.GET("/categories", handlers.AdminListCategories)
+			a.POST("/categories", handlers.AdminSaveCategory)
+			a.DELETE("/categories/:id", handlers.AdminDeleteCategory)
+
+			a.POST("/upload", handlers.UploadFile)
+		}
+	}
+
+	r.Run(":8080")
+}
diff --git a/server/middleware/auth.go b/server/middleware/auth.go
new file mode 100644
index 0000000..4a6f0b1
--- /dev/null
+++ b/server/middleware/auth.go
@@ -0,0 +1,48 @@
+package middleware
+
+import (
+	"net/http"
+	"strings"
+
+	"gamebox-server/utils"
+
+	"github.com/gin-gonic/gin"
+)
+
+// UserAuth 用户JWT认证
+func UserAuth() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		token := c.GetHeader("Authorization")
+		token = strings.TrimPrefix(token, "Bearer ")
+		if token == "" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "请先登录"})
+			return
+		}
+		claims, err := utils.ParseToken(token)
+		if err != nil || claims.Role != "user" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "登录已失效,请重新登录"})
+			return
+		}
+		c.Set("user_id", claims.UserID)
+		c.Next()
+	}
+}
+
+// AdminAuth 管理员JWT认证
+func AdminAuth() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		token := c.GetHeader("Authorization")
+		token = strings.TrimPrefix(token, "Bearer ")
+		if token == "" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "请先登录"})
+			return
+		}
+		claims, err := utils.ParseToken(token)
+		if err != nil || claims.Role != "admin" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "登录已失效"})
+			return
+		}
+		c.Set("admin_id", claims.UserID)
+		c.Next()
+	}
+}
diff --git a/server/models/models.go b/server/models/models.go
new file mode 100644
index 0000000..4e328fd
--- /dev/null
+++ b/server/models/models.go
@@ -0,0 +1,104 @@
+package models
+
+import "time"
+
+type Admin struct {
+	ID        uint      `gorm:"primaryKey" json:"id"`
+	Username  string    `gorm:"uniqueIndex;size:50" json:"username"`
+	Password  string    `json:"-"`
+	CreatedAt time.Time `json:"created_at"`
+}
+
+type User struct {
+	ID        uint      `gorm:"primaryKey" json:"id"`
+	Phone     string    `gorm:"uniqueIndex;size:20" json:"phone"`
+	Password  string    `json:"-"`
+	CreatedAt time.Time `json:"created_at"`
+}
+
+type Category struct {
+	ID        uint      `gorm:"primaryKey" json:"id"`
+	Name      string    `gorm:"uniqueIndex;size:50" json:"name"`
+	Sort      int       `json:"sort"`
+	CreatedAt time.Time `json:"created_at"`
+}
+
+type Game struct {
+	ID           uint      `gorm:"primaryKey" json:"id"`
+	Title        string    `gorm:"size:255" json:"title"`
+	CategoryID   uint      `json:"category_id"`
+	CategoryName string    `gorm:"-" json:"category_name,omitempty"`
+	Platform     string    `gorm:"size:20;default:pc" json:"platform"` // pc / switch
+	Tags         string    `gorm:"size:200" json:"tags"`               // 逗号分隔: 即时战略,经典怀旧
+	Size         string    `gorm:"size:20" json:"size"`                // 游戏大小 232.6 GB
+	InstallSize  string    `gorm:"size:20" json:"install_size"`        // 安装磁盘占用 411.6 GB
+	OSReq        string    `gorm:"size:100" json:"os_req"`
+	CPUReq       string    `gorm:"size:100" json:"cpu_req"`
+	GPUReq       string    `gorm:"size:100" json:"gpu_req"`
+	RAMReq       string    `gorm:"size:100" json:"ram_req"`
+	VersionNote  string    `gorm:"size:500" json:"version_note"` // V1.685.421顶级版|容量175GB|官方简体中文...
+	Cover        string    `gorm:"size:255" json:"cover"`
+	Video        string    `gorm:"size:255" json:"video"`
+	Screenshots  string    `gorm:"type:text" json:"screenshots"` // JSON数组
+	Description  string    `gorm:"type:longtext" json:"description"`
+	Files        string    `gorm:"type:text" json:"files"` // JSON数组 [{name,size,url}]
+	IsBanner     bool      `json:"is_banner"`              // 是否在首页轮播
+	DownloadCount int      `json:"download_count"`
+	UpdatedAt    time.Time `json:"updated_at"`
+	CreatedAt    time.Time `json:"created_at"`
+}
+
+type Tool struct {
+	ID          uint      `gorm:"primaryKey" json:"id"`
+	Name        string    `gorm:"size:100" json:"name"`
+	Size        string    `gorm:"size:20" json:"size"`
+	Cover       string    `gorm:"size:255" json:"cover"`
+	Description string    `gorm:"size:500" json:"description"`
+	FileURL     string    `gorm:"size:255" json:"file_url"`
+	CreatedAt   time.Time `json:"created_at"`
+}
+
+type MemberKey struct {
+	ID          uint       `gorm:"primaryKey" json:"id"`
+	Code        string     `gorm:"uniqueIndex;size:50" json:"code"`
+	CardType    string     `gorm:"size:20" json:"card_type"` // day/month/year
+	Status      int        `json:"status"`                   // 0未使用 1已使用
+	UserID      uint       `json:"user_id"`
+	MachineCode string     `gorm:"size:100" json:"machine_code"`
+	ActivatedAt *time.Time `json:"activated_at"`
+	ExpiredAt   *time.Time `json:"expired_at"`
+	ResetCount  int        `json:"reset_count"`
+	CreatedAt   time.Time  `json:"created_at"`
+}
+
+func (k MemberKey) CardName() string {
+	switch k.CardType {
+	case "day":
+		return "日卡"
+	case "month":
+		return "月卡"
+	case "year":
+		return "年卡"
+	}
+	return k.CardType
+}
+
+type Favorite struct {
+	ID        uint      `gorm:"primaryKey" json:"id"`
+	UserID    uint      `gorm:"uniqueIndex:idx_fav" json:"user_id"`
+	GameID    uint      `gorm:"uniqueIndex:idx_fav" json:"game_id"`
+	CreatedAt time.Time `json:"created_at"`
+}
+
+type LibraryItem struct {
+	ID        uint      `gorm:"primaryKey" json:"id"`
+	UserID    uint      `gorm:"uniqueIndex:idx_lib" json:"user_id"`
+	GameID    uint      `gorm:"uniqueIndex:idx_lib" json:"game_id"`
+	CreatedAt time.Time `json:"created_at"`
+}
+
+type Announcement struct {
+	ID        uint      `gorm:"primaryKey" json:"id"`
+	Content   string    `gorm:"type:text" json:"content"`
+	CreatedAt time.Time `json:"created_at"`
+}
diff --git a/server/utils/utils.go b/server/utils/utils.go
new file mode 100644
index 0000000..a63c49b
--- /dev/null
+++ b/server/utils/utils.go
@@ -0,0 +1,57 @@
+package utils
+
+import (
+	"crypto/rand"
+	"math/big"
+	"time"
+
+	"github.com/golang-jwt/jwt/v5"
+)
+
+var JWTSecret = []byte("gamebox-secret-key-2026")
+
+type Claims struct {
+	UserID   uint   `json:"user_id"`
+	Username string `json:"username"`
+	Role     string `json:"role"` // user / admin
+	jwt.RegisteredClaims
+}
+
+func GenerateToken(userID uint, username, role string) (string, error) {
+	claims := Claims{
+		UserID:   userID,
+		Username: username,
+		Role:     role,
+		RegisteredClaims: jwt.RegisteredClaims{
+			ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * 24 * time.Hour)),
+			IssuedAt:  jwt.NewNumericDate(time.Now()),
+		},
+	}
+	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+	return token.SignedString(JWTSecret)
+}
+
+func ParseToken(tokenString string) (*Claims, error) {
+	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) {
+		return JWTSecret, nil
+	})
+	if err != nil {
+		return nil, err
+	}
+	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
+		return claims, nil
+	}
+	return nil, jwt.ErrTokenInvalidClaims
+}
+
+const keyCharset = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
+
+// GenerateKeyCode 生成形如 XXXX-XXXX-XXXX-XXXX 的激活码
+func GenerateKeyCode() string {
+	code := make([]byte, 16)
+	for i := range code {
+		n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(keyCharset))))
+		code[i] = keyCharset[n.Int64()]
+	}
+	return string(code[0:4]) + "-" + string(code[4:8]) + "-" + string(code[8:12]) + "-" + string(code[12:16])
+}

--
Gitblit v1.10.0