part of '../../core_app.dart';

/// 获取设备信息，包括 Android 版本、设备型号、WebView 版本等。
Future<Map<String, dynamic>> _getDeviceInfoFromBridge() async {
  final androidInfo = await DeviceInfoPlugin().androidInfo;
  return <String, dynamic>{
    'platform': 'android',
    'brand': androidInfo.brand,
    'model': androidInfo.model,
    'manufacturer': androidInfo.manufacturer,
    'androidVersion': androidInfo.version.release,
    'sdkInt': androidInfo.version.sdkInt,
    'isPhysicalDevice': androidInfo.isPhysicalDevice,
    'display': androidInfo.display,
    'product': androidInfo.product,
    'appName': _env.appName,
    'appKey': _env.appKey,
    'shellVersion': _appShellBridgeVersion,
  };
}

/// 获取当前网络连接状态及类型。
Future<Map<String, dynamic>> _getNetworkStatusFromBridge() async {
  final results = await Connectivity().checkConnectivity();
  // connectivity_plus 返回 List<ConnectivityResult>
  final primary = results.isNotEmpty ? results.first : ConnectivityResult.none;

  String type;
  switch (primary) {
    case ConnectivityResult.wifi:
      type = 'wifi';
    case ConnectivityResult.mobile:
      type = 'cellular';
    case ConnectivityResult.ethernet:
      type = 'ethernet';
    case ConnectivityResult.bluetooth:
      type = 'bluetooth';
    case ConnectivityResult.vpn:
      type = 'vpn';
    case ConnectivityResult.none:
      type = 'none';
    case ConnectivityResult.other:
      type = 'unknown';
  }

  return <String, dynamic>{
    'connected': primary != ConnectivityResult.none,
    'type': type,
  };
}

/// 显示原生 Toast 提示。
///
/// 使用 Overlay 实现，不依赖额外插件。
void _showToastFromBridge(BuildContext context, Map<String, dynamic> payload) {
  final message = (payload['message'] ?? '').toString();
  if (message.isEmpty) return;

  final duration = switch ((payload['duration'] ?? 'short').toString()) {
    'long' => const Duration(milliseconds: 3500),
    _ => const Duration(milliseconds: 2000),
  };

  final overlay = Overlay.of(context);
  late final OverlayEntry entry;

  entry = OverlayEntry(
    builder: (context) => _ToastWidget(
      message: message,
      duration: duration,
      onDismiss: () => entry.remove(),
    ),
  );

  overlay.insert(entry);
}

/// 设置系统状态栏样式。
void _setStatusBarFromBridge(Map<String, dynamic> payload) {
  final style = (payload['style'] ?? '').toString();
  final color = payload['color']?.toString();

  Brightness? brightness;
  if (style == 'light') {
    brightness = Brightness.light;
  } else if (style == 'dark') {
    brightness = Brightness.dark;
  }

  Color? bgColor;
  if (color != null && color.isNotEmpty) {
    final parsed = int.tryParse(
      color.replaceFirst('#', '0xFF'),
    );
    if (parsed != null) bgColor = Color(parsed);
  }

  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(
      statusBarIconBrightness: brightness,
      statusBarColor: bgColor ?? Colors.transparent,
    ),
  );
}

// ── Toast 动效组件 ──

class _ToastWidget extends StatefulWidget {
  const _ToastWidget({
    required this.message,
    required this.duration,
    required this.onDismiss,
  });

  final String message;
  final Duration duration;
  final VoidCallback onDismiss;

  @override
  State<_ToastWidget> createState() => _ToastWidgetState();
}

class _ToastWidgetState extends State<_ToastWidget>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 250),
    );
    _fadeAnimation = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    );

    unawaited(_controller.forward());

    unawaited(
      Future<void>.delayed(widget.duration).then((_) {
        if (mounted) {
          unawaited(
            _controller.reverse().then((_) {
              if (mounted) widget.onDismiss();
            }),
          );
        }
      }),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: 100,
      left: 0,
      right: 0,
      child: Center(
        child: FadeTransition(
          opacity: _fadeAnimation,
          child: Material(
            color: Colors.transparent,
            child: Container(
              constraints: const BoxConstraints(maxWidth: 300),
              padding: const EdgeInsets.symmetric(
                horizontal: 20,
                vertical: 12,
              ),
              decoration: BoxDecoration(
                color: const Color(0xDD333333),
                borderRadius: BorderRadius.circular(24),
              ),
              child: Text(
                widget.message,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
