import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:health_app/app.dart';
import 'package:health_app/core/navigation_provider.dart';
import 'package:health_app/providers/auth_provider.dart';

class _TestAuthNotifier extends AuthNotifier {
  @override
  AuthState build() => const AuthState(isLoggedIn: false, isLoading: false);
}

void main() {
  testWidgets('native navigator pop keeps the app route stack in sync', (
    tester,
  ) async {
    debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
    addTearDown(() => debugDefaultTargetPlatformOverride = null);

    final container = ProviderContainer(
      overrides: [authProvider.overrideWith(_TestAuthNotifier.new)],
    );
    addTearDown(container.dispose);

    await tester.pumpWidget(
      UncontrolledProviderScope(container: container, child: const HealthApp()),
    );
    await tester.pump();

    container
        .read(routeStackProvider.notifier)
        .push('staticText', params: const {'type': 'privacy'});
    await tester.pumpAndSettle();

    final navigators = tester
        .stateList<NavigatorState>(find.byType(Navigator))
        .toList();
    expect(navigators.length, greaterThanOrEqualTo(2));
    expect(navigators.last.canPop(), isTrue);
    final route = ModalRoute.of(tester.element(find.text('隐私协议').first));
    expect(route, isA<PageRoute<void>>());
    expect((route! as PageRoute<void>).popGestureEnabled, isTrue);

    await tester.dragFrom(const Offset(5, 100), const Offset(500, 0));
    await tester.pump(const Duration(milliseconds: 351));
    await tester.pumpAndSettle();

    debugDefaultTargetPlatformOverride = null;
    expect(container.read(routeStackProvider).length, 1);
  });
}
