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 StubJoinService extends PublicEventService {
  int fetchCount = 0;
  bool addGuestCalled = false;

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

  @override
  Future<void> addGuest(String publicHash, {required String name, String? phone, String? gender, num? average}) async {
    addGuestCalled = true;
    await Future<void>.delayed(const Duration(milliseconds: 10));
  }
}

void main() {
  testWidgets('join button opens dialog, saves, and reloads (fetch called twice)', (tester) async {
    final stub = StubJoinService();

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

    await tester.pumpAndSettle();
    expect(stub.fetchCount, 1);
    expect(find.byKey(const Key('join_button')), findsOneWidget);

    await tester.tap(find.byKey(const Key('join_button')));
    await tester.pumpAndSettle();

    expect(find.text('참가 신청(게스트)'), findsOneWidget);

    await tester.enterText(find.byKey(const Key('join_name_input')), 'New Guest');
    await tester.tap(find.byKey(const Key('join_save_button')));
    await tester.pumpAndSettle();

    expect(stub.addGuestCalled, isTrue);
    // reload triggered
    expect(stub.fetchCount, 2);
  });
}
