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 StubInlineService extends PublicEventService {
  int fetchCount = 0;
  int updateCount = 0;
  final List<Map<String, dynamic>> calls = [];

  @override
  Future<Map<String, dynamic>> fetchEvent(String publicHash) async {
    fetchCount++;
    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, teamNumber}) async {
    updateCount++;
    calls.add({'pid': participantId, 'g': gameNumber, 's': score});
    // simulate small delay
    await Future<void>.delayed(const Duration(milliseconds: 1));
  }
}

void main() {
  testWidgets('3자리 입력 즉시 저장, 디바운스 저장, 범위 밖 값은 저장 안함', (tester) async {
    final stub = StubInlineService();

    await tester.pumpWidget(MaterialApp(
      home: PublicEventScreen(publicHash: 'H', service: stub),
    ));
    await tester.pumpAndSettle();

    // cell p1 game2 존재 확인
    final cellG2 = find.byKey(const Key('cell_p1_2'));
    expect(cellG2, findsOneWidget);

    // 3자리 입력 즉시 저장
    await tester.enterText(cellG2, '150');
    // allow microtasks
    await tester.pump(const Duration(milliseconds: 10));
    expect(stub.updateCount, 1);
    expect(stub.calls.last['s'], 150);

    // 1자리 입력 후 디바운스 200ms 후 저장
    await tester.enterText(cellG2, '2');
    await tester.pump(const Duration(milliseconds: 250));
    expect(stub.updateCount, 2);
    expect(stub.calls.last['s'], 2);

    // 범위 밖 값은 저장 안함 (350)
    await tester.enterText(cellG2, '350');
    await tester.pump(const Duration(milliseconds: 250));
    expect(stub.updateCount, 2);
  });
}
