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,
  ) {
    // USB 慢充锁定 7.5W
    if (chargeType == "SDP") return "≈7.5W";

    // 🟢 优先使用 wiredLevel 精确匹配
    if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
      double p = ChargeMaps.wiredPower[wiredLevel]!;
      if (p > 0) return '≈${p.toInt()}W';
    }

    // 🟢 匹配阈值收窄到 ±3W，减少跳变
    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';
  }

  static String getChargeTypeLabel(bool isWireless, String chargeType) {
    if (isWireless) {
      return chargeType == "无线" ? "无线" : chargeType;
    }
    // 🟢 空类型显示"识别中..."，比"等待log信息"更友好
    if (chargeType.isEmpty) {
      return "识别中...";
    }
    if (chargeType == 'PPS') return 'PPS';
    if (chargeType == 'SDP') return 'USB';
    return chargeType;
  }
}
