import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lanebow/models/event_model.dart';
import 'package:lanebow/models/score_model.dart';
import 'package:lanebow/models/team_model.dart';
import 'package:lanebow/screens/club/event_details_screen.dart';

void main() {
  setUp(() { EventDetailsScreen.testMode = true; });
  tearDown(() { EventDetailsScreen.testMode = false; });

  testWidgets('팀 에버리지 계산: 멤버별 평균의 평균을 반환한다', (tester) async {
    // given
    final event = Event(
      id: 'ev1', clubId: 'c1', title: 'E', type: 'team', status: 'draft', startDate: DateTime.now(), isActive: true,
    );

    await tester.pumpWidget(MaterialApp(home: EventDetailsScreen(event: event)));
    await tester.pumpAndSettle();

    final state = tester.state(find.byType(EventDetailsScreen));
    final dynamic dyn = state;

    // 점수: m1 => (150,170)=160 / m2 => (200,180,190)=190 → 팀 평균 = (160+190)/2=175
    dyn.debugSetScores(<Score>[
      Score(id: 's1', memberId: 'm1', eventId: 'ev1', clubId: 'c1', frames: const [], totalScore: 150, date: DateTime(2024,1,1)),
      Score(id: 's2', memberId: 'm1', eventId: 'ev1', clubId: 'c1', frames: const [], totalScore: 170, date: DateTime(2024,1,2)),
      Score(id: 's3', memberId: 'm2', eventId: 'ev1', clubId: 'c1', frames: const [], totalScore: 200, date: DateTime(2024,1,1)),
      Score(id: 's4', memberId: 'm2', eventId: 'ev1', clubId: 'c1', frames: const [], totalScore: 180, date: DateTime(2024,1,2)),
      Score(id: 's5', memberId: 'm2', eventId: 'ev1', clubId: 'c1', frames: const [], totalScore: 190, date: DateTime(2024,1,3)),
    ]);
    await tester.pump();

    final team = Team(id: 't1', eventId: 'ev1', name: 'A', memberIds: const ['m1','m2']);

    // when
    final avg = dyn.debugCalculateTeamAverage(team) as double;

    // then
    expect(avg, closeTo(175.0, 0.0001));
  });

  testWidgets('팀 에버리지 계산: 점수가 없는 팀은 0.0을 반환한다', (tester) async {
    final event = Event(
      id: 'ev1', clubId: 'c1', title: 'E', type: 'team', status: 'draft', startDate: DateTime.now(), isActive: true,
    );
    await tester.pumpWidget(MaterialApp(home: EventDetailsScreen(event: event)));
    await tester.pumpAndSettle();

    final state = tester.state(find.byType(EventDetailsScreen));
    final dynamic dyn = state;
    dyn.debugSetScores(const <Score>[]);
    await tester.pump();

    final team = Team(id: 't0', eventId: 'ev1', name: 'Empty', memberIds: const []);
    expect(dyn.debugCalculateTeamAverage(team) as double, 0.0);

    final team2 = Team(id: 't2', eventId: 'ev1', name: 'NoScore', memberIds: const ['mX']);
    expect(dyn.debugCalculateTeamAverage(team2) as double, 0.0);
  });
}
