/// WebShell 核心库：为 H5 壳应用提供 WebView 引擎、原生桥接与平台服务。
library;

import 'dart:async';
import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';

// ── 配置 ──
part 'src/config/shell_environment.dart';
part 'src/config/url_resolver.dart';

// ── 引擎 ──
part 'src/engine/compatibility.dart';
part 'src/engine/recovery.dart';

// ── 桥接 ──
part 'src/bridge/bridge_protocol.dart';
part 'src/bridge/bridge_actions.dart';
part 'src/bridge/legacy_camera_compat.dart';

// ── 服务 ──
part 'src/services/media_service.dart';
part 'src/services/permission_service.dart';
part 'src/services/navigation_service.dart';

// ── 界面 ──
part 'src/ui/shell_app.dart';
part 'src/ui/shell_page.dart';
part 'src/ui/launch_overlay.dart';
part 'src/ui/error_overlay.dart';
part 'src/ui/progress_bar.dart';
part 'src/ui/unsupported_platform_page.dart';
part 'src/testing/test_hooks.dart';

// ── 全局环境 ──
late ShellEnvironment _env;

Color get _shellAccentColor => _env.accentColor;
Color get _shellBackgroundColor => _env.backgroundColor;
Color get _shellTextColor => _env.textColor;
Color get _shellMutedTextColor => _env.mutedTextColor;

// ── 入口 ──

/// 启动壳应用的唯一入口。
/// 各品牌应用的 `main.dart` 调用此函数，并传入自己的 [ShellEnvironment]。
Future<void> runShellApp(ShellEnvironment environment) async {
  _env = environment;
  _initializeUrls();
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(const [
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  await _enterImmersiveMode();
  runApp(const ShellApp());
}

Future<void> _enterImmersiveMode() async {
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
      statusBarBrightness: Brightness.dark,
      systemNavigationBarColor: Colors.black,
      systemNavigationBarDividerColor: Colors.black,
      systemNavigationBarIconBrightness: Brightness.light,
    ),
  );
}

bool _supportsEmbeddedWebView({
  bool isWeb = kIsWeb,
  TargetPlatform? platform,
}) {
  if (isWeb) {
    return false;
  }

  final target = platform ?? defaultTargetPlatform;
  return target == TargetPlatform.android;
}
