import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

extension WidgetTesterDialogActions on WidgetTester {
  /// 다이얼로그 내 `ShadButton`을 텍스트 라벨로 찾아 탭한다.
  Future<void> tapShadButton(String label, {bool settle = true}) async {
    final buttonFinder = find.widgetWithText(ShadButton, label);
    expect(
      buttonFinder,
      findsWidgets,
      reason: '텍스트 "$label" 를 가진 ShadButton을 찾지 못했습니다.',
    );
    final elements = buttonFinder.evaluate().toList(growable: false);
    final targetIndex = elements.lastIndexWhere((element) {
      final widget = element.widget;
      return widget is ShadButton && widget.onPressed != null;
    });
    expect(
      targetIndex,
      isNot(-1),
      reason: '눌러야 할 활성화된 "$label" 버튼을 찾을 수 없습니다.',
    );
    final targetButton = buttonFinder.at(targetIndex);
    final targetText = find.descendant(
      of: targetButton,
      matching: find.byType(Text),
    );
    await ensureVisible(targetText.first);
    await tap(targetText.first, warnIfMissed: false);
    if (settle) {
      await pumpAndSettle();
    }
  }
}
