import 'dart:convert';

/// JS Bridge 常量定义
class JSBridgeConstants {
  // JS 对象名称
  static const String nativeAttrs = 'nativeAttrs';

  // JS 方法名称
  static const String setStatusBarColor = 'setStatusBarColor';
  static const String exitWebView = 'exitWebView';
  static const String connectVPN = 'connectVPN';
  static const String disconnectVPN = 'disconnectVPN';
  static const String openApp = 'openApp';
  static const String getVPNStatus = 'getVPNStatus';

  // Flutter 调用 JS 的方法名称
  static const String onVPNStatusChanged = 'onVPNStatusChanged';
  static const String onVPNConnected = 'onVPNConnected';
  static const String onVPNDisconnected = 'onVPNDisconnected';
  static const String onVPNConnecting = 'onVPNConnecting';
}

/// JS Bridge 消息类型
enum JSBridgeMessageType {
  setStatusBarColor,
  exitWebView,
  connectVPN,
  disconnectVPN,
  openApp,
  getVPNStatus,
}

/// JS Bridge 消息
class JSBridgeMessage {
  final JSBridgeMessageType type;
  final Map<String, dynamic> data;

  JSBridgeMessage({required this.type, required this.data});

  factory JSBridgeMessage.fromJson(Map<String, dynamic> json) {
    final typeStr = json['type'] as String;
    final type = JSBridgeMessageType.values.firstWhere(
      (e) => e.name == typeStr,
      orElse: () => JSBridgeMessageType.getVPNStatus,
    );

    return JSBridgeMessage(
      type: type,
      data: json['data'] as Map<String, dynamic>? ?? {},
    );
  }

  Map<String, dynamic> toJson() {
    return {'type': type.name, 'data': data};
  }
}

/// JS Bridge 响应
class JSBridgeResponse {
  final bool success;
  final dynamic data;
  final String? error;

  JSBridgeResponse({required this.success, this.data, this.error});

  Map<String, dynamic> toJson() {
    return {'success': success, 'data': data, 'error': error};
  }

  String toJsonString() {
    return jsonEncode(toJson());
  }
}

/// VPN 连接参数
class VPNConnectParams {
  final int? id;
  final String? code;

  VPNConnectParams({this.id, this.code});

  factory VPNConnectParams.fromJson(Map<String, dynamic> json) {
    return VPNConnectParams(
      id: json['id'] as int?,
      code: json['code'] as String?,
    );
  }

  bool get isValid => id != null || code != null;
}

/// 打开 App 参数
class OpenAppParams {
  final String packageName;
  final String? scheme;
  final Map<String, dynamic>? extras;

  OpenAppParams({required this.packageName, this.scheme, this.extras});

  factory OpenAppParams.fromJson(Map<String, dynamic> json) {
    return OpenAppParams(
      packageName: json['packageName'] as String,
      scheme: json['scheme'] as String?,
      extras: json['extras'] as Map<String, dynamic>?,
    );
  }
}
