class PublicEvent {
  final String id;
  final String title;
  final String? description;
  final String? eventType;
  final DateTime? startDate;
  final DateTime? endDate;
  final String? location;
  final int gameCount;
  final DateTime? registrationDeadline;
  final int? maxParticipants;
  final num? participantFee;
  final String? status;

  PublicEvent({
    required this.id,
    required this.title,
    this.description,
    this.eventType,
    this.startDate,
    this.endDate,
    this.location,
    required this.gameCount,
    this.registrationDeadline,
    this.maxParticipants,
    this.participantFee,
    this.status,
  });

  factory PublicEvent.fromJson(Map<String, dynamic> json) {
    String parseId(dynamic v) => v?.toString() ?? '';
    DateTime? parseDate(dynamic v) {
      if (v == null) return null;
      final s = v.toString();
      return DateTime.tryParse(s);
    }

    int parseInt(dynamic v, {int def = 0}) {
      if (v == null) return def;
      if (v is int) return v;
      return int.tryParse(v.toString()) ?? def;
    }

    num? parseNum(dynamic v) {
      if (v == null) return null;
      if (v is num) return v;
      return num.tryParse(v.toString());
    }

    return PublicEvent(
      id: parseId(json['id']),
      title: (json['title'] ?? '').toString(),
      description: json['description']?.toString(),
      eventType: json['eventType']?.toString(),
      startDate: parseDate(json['startDate']),
      endDate: parseDate(json['endDate']),
      location: json['location']?.toString(),
      gameCount: parseInt(json['gameCount'], def: 3),
      registrationDeadline: parseDate(json['registrationDeadline']),
      maxParticipants: json['maxParticipants'] == null ? null : parseInt(json['maxParticipants']),
      participantFee: parseNum(json['participantFee']),
      status: json['status']?.toString(),
    );
  }

  bool get isReady => (status == 'ready');
  bool get isActive => (status == 'active');
  bool get isFinished => (status == 'completed');
}

enum EventStatus { ready, active, completed, canceled, unknown }
enum EventType { regular, tournament, practice, league, unknown }

extension PublicEventEnums on PublicEvent {
  EventStatus get statusEnum {
    switch ((status ?? '').toLowerCase()) {
      case 'ready':
        return EventStatus.ready;
      case 'active':
        return EventStatus.active;
      case 'completed':
        return EventStatus.completed;
      case 'canceled':
        return EventStatus.canceled;
      default:
        return EventStatus.unknown;
    }
  }

  EventType get typeEnum {
    switch ((eventType ?? '').toLowerCase()) {
      case 'regular':
        return EventType.regular;
      case 'tournament':
        return EventType.tournament;
      case 'practice':
        return EventType.practice;
      case 'league':
        return EventType.league;
      default:
        return EventType.unknown;
    }
  }
}
