
class PublicTeamMemberSummary {
  final String? participantId;
  final String? memberId;
  final String name;
  final List<int?> rawScores;
  final List<int> handicaps;

  PublicTeamMemberSummary({
    required this.participantId,
    required this.memberId,
    required this.name,
    required this.rawScores,
    required this.handicaps,
  });

  factory PublicTeamMemberSummary.fromJson(Map<String, dynamic> json, {int gameCount = 3}) {
    final participantId = json['participantId']?.toString();
    final memberId = json['memberId']?.toString();
    final name = (json['name'] ?? '이름없음').toString();
    // 점수 포맷은 PublicParticipant와 동일 규칙
    final List<dynamic> src = (json['scores'] is List) ? (json['scores'] as List) : const [];
    final List<int?> raw = List<int?>.filled(gameCount, null);
    final List<int> hcs = List<int>.filled(gameCount, 0);
    for (int i = 0; i < src.length && i < gameCount; i++) {
      final el = src[i];
      if (el == null) {
        raw[i] = null;
        hcs[i] = 0;
      } else if (el is num) {
        raw[i] = el.toInt();
        hcs[i] = 0;
      } else if (el is Map) {
        final score = el['score'];
        final hc = el['handicap'];
        raw[i] = (score is num) ? score.toInt() : int.tryParse(score?.toString() ?? '');
        hcs[i] = (hc is num) ? hc.toInt() : (int.tryParse(hc?.toString() ?? '') ?? 0);
      } else {
        raw[i] = int.tryParse(el.toString());
        hcs[i] = 0;
      }
    }
    return PublicTeamMemberSummary(
      participantId: participantId,
      memberId: memberId,
      name: name,
      rawScores: raw,
      handicaps: hcs,
    );
  }
}

class PublicTeam {
  final String teamId;
  final int teamNumber;
  final int handicap; // 팀 핸디캡
  final List<PublicTeamMemberSummary> members;

  PublicTeam({
    required this.teamId,
    required this.teamNumber,
    required this.handicap,
    required this.members,
  });

  factory PublicTeam.fromJson(Map<String, dynamic> json, {int gameCount = 3}) {
    int parseInt(dynamic v, {int def = 0}) {
      if (v == null) return def;
      if (v is int) return v;
      return int.tryParse(v.toString()) ?? def;
    }
    final List<dynamic> mem = (json['members'] is List) ? (json['members'] as List) : const [];
    return PublicTeam(
      teamId: (json['teamId'] ?? json['id'] ?? '').toString(),
      teamNumber: parseInt(json['teamNumber'], def: 0),
      handicap: parseInt(json['handicap'], def: 0),
      members: mem.map((e) => PublicTeamMemberSummary.fromJson((e as Map).cast<String, dynamic>(), gameCount: gameCount)).toList(),
    );
  }
}
