class CompetitionPlayer {
  const CompetitionPlayer({required this.id, required this.name});

  final String id;
  final String name;
}

class CompetitionTeam {
  const CompetitionTeam({
    required this.id,
    required this.name,
    required this.players,
  });

  final String id;
  final String name;
  final List<CompetitionPlayer> players;

  String get playerNames => players.map((player) => player.name).join('、');
}

class CompetitionMatchup {
  const CompetitionMatchup({
    required this.id,
    required this.teamA,
    required this.teamB,
    this.winnerTeamId,
  });

  final String id;
  final CompetitionTeam teamA;
  final CompetitionTeam teamB;
  final String? winnerTeamId;

  CompetitionMatchup copyWith({String? winnerTeamId}) {
    return CompetitionMatchup(
      id: id,
      teamA: teamA,
      teamB: teamB,
      winnerTeamId: winnerTeamId ?? this.winnerTeamId,
    );
  }
}

/// 参赛项目/组别列表项（来自 /api/events/device/item/group）
class CompetitionTeamListItem {
  const CompetitionTeamListItem({
    required this.eventId,
    required this.itemId,
    required this.name,
    required this.groupName,
    this.matchStartTime = '',
    this.matchEndTime = '',
    this.matchups = const [],
  });

  final String eventId;
  final String itemId;
  final String name;
  final String groupName;
  final String matchStartTime;
  final String matchEndTime;

  /// 对阵明细暂未由列表接口返回，默认空
  final List<CompetitionMatchup> matchups;

  String get title => groupName.isEmpty ? name : '$name （$groupName）';

  String get scheduleTime {
    if (matchStartTime.isEmpty && matchEndTime.isEmpty) return '';
    if (matchStartTime.isNotEmpty && matchEndTime.isNotEmpty) {
      return '$matchStartTime-$matchEndTime';
    }
    if (matchStartTime.isNotEmpty) return matchStartTime;
    return matchEndTime;
  }

  factory CompetitionTeamListItem.fromJson(Map<String, dynamic> json) {
    return CompetitionTeamListItem(
      eventId: (json['eventId'] ?? '').toString(),
      itemId: (json['itemId'] ?? '').toString(),
      name: (json['name'] ?? '').toString(),
      groupName: (json['groupName'] ?? '').toString(),
      matchStartTime: (json['matchStartTime'] ?? '').toString(),
      matchEndTime: (json['matchEndTime'] ?? '').toString(),
    );
  }

  CompetitionTeamListItem copyWith({List<CompetitionMatchup>? matchups}) {
    return CompetitionTeamListItem(
      eventId: eventId,
      itemId: itemId,
      name: name,
      groupName: groupName,
      matchStartTime: matchStartTime,
      matchEndTime: matchEndTime,
      matchups: matchups ?? this.matchups,
    );
  }
}

class CompetitionTeamPageResult {
  const CompetitionTeamPageResult({
    required this.items,
    required this.total,
    required this.page,
    required this.pageSize,
  });

  final List<CompetitionTeamListItem> items;
  final int total;
  final int page;
  final int pageSize;

  bool get hasMore => page * pageSize < total;

  factory CompetitionTeamPageResult.fromJson(
    dynamic json, {
    required int page,
    required int pageSize,
  }) {
    if (json is List) {
      // 整表无分页：本页即全部，hasMore = false
      final items = json
          .whereType<Map>()
          .map(
            (item) => CompetitionTeamListItem.fromJson(
              Map<String, dynamic>.from(item),
            ),
          )
          .toList(growable: false);
      final effectivePageSize = items.isEmpty ? pageSize : items.length;
      return CompetitionTeamPageResult(
        items: items,
        total: items.length,
        page: page,
        pageSize: effectivePageSize,
      );
    }

    if (json is Map) {
      final map = Map<String, dynamic>.from(json);
      final rawItems =
          map['items'] ?? map['rows'] ?? map['list'] ?? map['records'];
      final items = rawItems is List
          ? rawItems
                .whereType<Map>()
                .map(
                  (item) => CompetitionTeamListItem.fromJson(
                    Map<String, dynamic>.from(item),
                  ),
                )
                .toList(growable: false)
          : const <CompetitionTeamListItem>[];
      final total = (map['total'] as num?)?.toInt() ?? items.length;
      return CompetitionTeamPageResult(
        items: items,
        total: total,
        page: page,
        pageSize: pageSize,
      );
    }

    return CompetitionTeamPageResult(
      items: const [],
      total: 0,
      page: page,
      pageSize: pageSize,
    );
  }
}
