import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:ar_autopilot_display/theme/theme_provider.dart';
import 'package:ar_autopilot_display/theme/theme_registry.dart';

void main() {
  setUp(() {
    // Reset SharedPreferences mock before each test
    SharedPreferences.setMockInitialValues({});
  });

  group('AutopilotThemeProvider — persistence', () {
    test('loads default theme (cyan) when no preference is stored', () async {
      final provider = await AutopilotThemeProvider.load();
      expect(provider.current.id, ThemeRegistry.defaultId);
    });

    test('loads a previously persisted theme on startup', () async {
      SharedPreferences.setMockInitialValues({'autopilot.theme.id': 'wine'});
      final provider = await AutopilotThemeProvider.load();
      expect(provider.current.id, 'wine');
    });

    test('persists selection so a fresh load returns the same theme', () async {
      final provider = await AutopilotThemeProvider.load();
      await provider.setTheme('light');

      // Simulate app restart — reload from SharedPreferences
      final provider2 = await AutopilotThemeProvider.load();
      expect(provider2.current.id, 'light');
    });

    test('cycling through all 4 themes persists each correctly', () async {
      final provider = await AutopilotThemeProvider.load();
      for (final id in ['light', 'wine', 'ochre', 'cyan']) {
        await provider.setTheme(id);
        final reloaded = await AutopilotThemeProvider.load();
        expect(reloaded.current.id, id,
            reason: 'After setting "$id", reload should return "$id"');
      }
    });
  });

  group('AutopilotThemeProvider — state changes', () {
    test('setTheme updates current theme immediately', () async {
      final provider = await AutopilotThemeProvider.load();
      expect(provider.current.id, ThemeRegistry.defaultId);
      await provider.setTheme('ochre');
      expect(provider.current.id, 'ochre');
    });

    test('setTheme with unknown id falls back to default (cyan)', () async {
      final provider = await AutopilotThemeProvider.load();
      await provider.setTheme('nonexistent_theme');
      expect(provider.current.id, ThemeRegistry.defaultId);
    });

    test('setTheme notifies listeners', () async {
      final provider = await AutopilotThemeProvider.load();
      var notifyCount = 0;
      provider.addListener(() => notifyCount++);
      await provider.setTheme('wine');
      expect(notifyCount, 1);
      await provider.setTheme('ochre');
      expect(notifyCount, 2);
    });

    test('initial load does not notify listeners', () async {
      final provider = await AutopilotThemeProvider.load();
      var notified = false;
      provider.addListener(() => notified = true);
      // No setTheme called — listeners must not have fired
      expect(notified, isFalse);
    });
  });
}
