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

import 'package:minstrel/auth/auth_provider.dart';
import 'package:minstrel/models/user.dart';
import 'package:minstrel/shared/widgets/main_app_bar_actions.dart';
import 'package:minstrel/theme/theme_data.dart';

class _StubAuth extends AuthController {
  _StubAuth(this._user);
  final User? _user;
  @override
  Future<User?> build() async => _user;
}

Widget _harness({required User? user, required String currentRoute}) {
  return ProviderScope(
    overrides: [
      authControllerProvider.overrideWith(() => _StubAuth(user)),
    ],
    child: MaterialApp(
      theme: buildThemeData(),
      home: Scaffold(
        appBar: AppBar(
          actions: [MainAppBarActions(currentRoute: currentRoute)],
        ),
      ),
    ),
  );
}

void main() {
  const adminUser = User(id: 'u1', username: 'admin', isAdmin: true);
  const regularUser = User(id: 'u2', username: 'alice', isAdmin: false);

  testWidgets('renders Library + Search primary icons + kebab on /home',
      (t) async {
    await t.pumpWidget(_harness(user: regularUser, currentRoute: '/home'));
    await t.pumpAndSettle();
    expect(find.byKey(const Key('app_bar_library')), findsOneWidget);
    expect(find.byKey(const Key('app_bar_search')), findsOneWidget);
    expect(find.byKey(const Key('app_bar_home')), findsNothing);
    expect(find.byKey(const Key('app_bar_overflow')), findsOneWidget);
  });

  testWidgets('suppresses Library icon when currentRoute is /library',
      (t) async {
    await t.pumpWidget(_harness(user: regularUser, currentRoute: '/library'));
    await t.pumpAndSettle();
    expect(find.byKey(const Key('app_bar_library')), findsNothing);
    expect(find.byKey(const Key('app_bar_home')), findsOneWidget);
  });

  testWidgets('overflow includes Admin only for admin users', (t) async {
    await t.pumpWidget(_harness(user: adminUser, currentRoute: '/home'));
    await t.pumpAndSettle();
    await t.tap(find.byKey(const Key('app_bar_overflow')));
    await t.pumpAndSettle();
    expect(find.text('Admin'), findsOneWidget);
  });

  testWidgets('overflow omits Admin for non-admin users', (t) async {
    await t.pumpWidget(_harness(user: regularUser, currentRoute: '/home'));
    await t.pumpAndSettle();
    await t.tap(find.byKey(const Key('app_bar_overflow')));
    await t.pumpAndSettle();
    expect(find.text('Admin'), findsNothing);
  });
}
