import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:smplayer/features/player/widgets/player_hold_speed_prompt.dart';
import 'package:smplayer/features/player/widgets/player_video_widget.dart';

import '../../../helpers/fake_player_engine.dart';

void main() {
  testWidgets('keyboard hold speed prompt hides immediately on release', (
    tester,
  ) async {
    final player = FakePlayerEngine(playing: true);
    final fit = ValueNotifier<BoxFit>(BoxFit.contain);
    final rates = <double>[];

    await tester.pumpWidget(
      MaterialApp(
        home: SizedBox(
          width: 800,
          height: 450,
          child: PlayerVideoWidget(
            player: player,
            fit: fit,
            topBar: const [],
            bottomBar: const SizedBox.shrink(),
            overlays: const [],
            onControlsAreaTap: null,
            isFullscreen: false,
            onToggleFullscreen: () async {},
            isPip: false,
            keyboardEnabled: true,
            currentRate: 1,
            onSetRate: rates.add,
            suppressControlsChrome: true,
          ),
        ),
      ),
    );
    await tester.pump();

    await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight);
    await tester.pump(const Duration(milliseconds: 200));

    expect(_promptOpacity(tester), 1);
    expect(rates.last, 3);

    await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowRight);
    await tester.pump();

    expect(_promptOpacity(tester), 0);
    expect(rates.last, 1);

    fit.dispose();
    await player.dispose();
  });
}

double _promptOpacity(WidgetTester tester) {
  return tester
      .widget<AnimatedOpacity>(
        find.descendant(
          of: find.byType(HoldSpeedPrompt),
          matching: find.byType(AnimatedOpacity),
        ),
      )
      .opacity;
}
