import '../constants/charge_maps.dart';

class ChargeUtils {
  // ============ 无线充电（保持不变） ============
  static String getDisplayPowerWireless(double power) {
    if (power == 0) return '读取中...';
    const List<int> levels = [5, 7, 15, 27, 40, 50, 66];
    if (power < 3) return '≈${power.round()}W';
    int matchedLevel = levels.firstWhere(
      (level) => power <= level + 2,
      orElse: () => levels.last,
    );
    return '≈${matchedLevel}W';
  }

  // ============ 原有有线逻辑（保留兼容，但主界面不再直接调用） ============
  static String getDisplayPowerWired(
    double power,
    int? wiredLevel,
    String chargeType,
  ) {
    if (chargeType == "SDP") return "≈7.5W";
    if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
      double p = ChargeMaps.wiredPower[wiredLevel]!;
      if (p > 0) return '≈${p.toInt()}W';
    }
    double best = 0;
    for (var entry in ChargeMaps.wiredPower.entries) {
      if (entry.value <= power + 3 && entry.value > best) {
        best = entry.value;
      }
    }
    if (power == 0) return '读取中...';
    return best > 0 ? '≈${best.toInt()}W' : '≈${power.round()}W';
  }

  // ============ 🟢 1.5.0 新增：主界面显示（实际/标定） ============
  /// 示例：≈30w/65w
  static String getMainDisplayPowerWired(
    double power,
    int? wiredLevel,
    String chargeType,
  ) {
    // USB 慢充锁定 7.5W
    if (chargeType == "SDP") return "≈7.5w";

    if (power == 0) return "读取中...";

    final actual = power.round();

    // 有档位且能查到标定值
    if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
      final requested = ChargeMaps.wiredPower[wiredLevel]!.round();
      return "≈${actual}w/${requested}w";
    }

    // 无档位信息，仅显示实际功率
    return "≈${actual}w";
  }

  // ============ 🟢 1.5.0 新增：二级页面标定档位显示 ============
  /// 示例：≈80w/L-10
  static String getDetailRequestedPowerWired(
    double power,
    int? wiredLevel,
    String chargeType,
  ) {
    if (chargeType == "SDP") return "≈7.5w";

    if (power == 0) return "读取中...";

    if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
      final requested = ChargeMaps.wiredPower[wiredLevel]!.round();
      return "≈${requested}w/L-${wiredLevel}";
    }

    return "≈${power.round()}w";
  }

  // ============ 🟢 1.5.0 新增：二级页面实际功率显示 ============
  static String getDetailActualPowerWired(double power, String chargeType) {
    if (chargeType == "SDP") return "≈7.5w";
    if (power == 0) return "读取中...";
    return "≈${power.round()}w";
  }

  // ============ 充电类型标签（保持不变） ============
  static String getChargeTypeLabel(bool isWireless, String chargeType) {
    if (isWireless) {
      return chargeType == "无线" ? "无线" : chargeType;
    }
    if (chargeType.isEmpty) {
      return "识别中...";
    }
    if (chargeType == 'PPS') return 'PPS';
    if (chargeType == 'SDP') return 'USB';
    return chargeType;
  }
}
