import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lanebow/screens/public_event/public_event_screen.dart';
import 'package:lanebow/services/public_event_service.dart';

class StubDialogService extends PublicEventService {
  String? lastHash;
  String? lastParticipantId;
  int? lastGameNumber;
  int? lastScore;

  @override
  Future<Map<String, dynamic>> fetchEvent(String publicHash) async {
    return {
      'event': {'id': 'E1', 'title': '다이얼로그 테스트', 'gameCount': 3, 'status': 'active'},
      'participants': [
        {
          'participantId': 'p1',
          'name': 'Kim',
          'scores': [null, null, null],
          'handicap': 0,
        },
      ],
      'teams': [],
    };
  }

  @override
  Future<void> updateScore(String publicHash, {required String participantId, required int gameNumber, required int score, int? handicap, dynamic teamNumber}) async {
    lastHash = publicHash;
    lastParticipantId = participantId;
    lastGameNumber = gameNumber;
    lastScore = score;
  }
}

void main() {
  testWidgets('game select and validation works in score dialog', (tester) async {
    final stub = StubDialogService();
    await tester.pumpWidget(MaterialApp(
      home: PublicEventScreen(publicHash: 'hash-validate', service: stub),
    ));

    await tester.pumpAndSettle();
    expect(find.byKey(const Key('participant_tile_p1')), findsOneWidget);

    // Open dialog
    await tester.tap(find.byKey(const Key('participant_tile_p1')));
    await tester.pumpAndSettle();

    // Select game 2
    await tester.tap(find.byKey(const Key('game_select')));
    await tester.pumpAndSettle();
    await tester.tap(find.text('게임 2').last);
    await tester.pumpAndSettle();

    // Enter invalid value
    await tester.enterText(find.byKey(const Key('score_input')), '350');
    await tester.tap(find.byKey(const Key('score_save_button')));
    await tester.pumpAndSettle();
    expect(find.textContaining('0~300'), findsOneWidget);

    // Enter valid value
    await tester.enterText(find.byKey(const Key('score_input')), '180');
    await tester.tap(find.byKey(const Key('score_save_button')));
    await tester.pumpAndSettle();

    // Saved and called with game 2
    expect(stub.lastHash, 'hash-validate');
    expect(stub.lastParticipantId, 'p1');
    expect(stub.lastGameNumber, 2);
    expect(stub.lastScore, 180);
  });
}
