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

import 'package:chanora_flutter/services/ui_preferences_service.dart';

void main() {
  late UiPreferencesService service;

  setUp(() {
    SharedPreferences.setMockInitialValues({});
    service = const UiPreferencesService();
  });

  test('loads empty settings when preferences are unset', () async {
    final settings = await service.loadSettings();

    expect(settings.host, isEmpty);
    expect(settings.nickname, isEmpty);
    expect(settings.themeMode, UiThemeMode.system);
  });

  test('saves and loads host and nickname independently', () async {
    await service.saveSettings(host: 'example.com');
    var settings = await service.loadSettings();

    expect(settings.host, 'example.com');
    expect(settings.nickname, isEmpty);

    await service.saveSettings(nickname: 'Chanora');
    settings = await service.loadSettings();

    expect(settings.host, 'example.com');
    expect(settings.nickname, 'Chanora');
  });

  test('tracks permission explanation flag', () async {
    expect(await service.hasExplainedPermissions(), isFalse);

    await service.markPermissionsExplained();

    expect(await service.hasExplainedPermissions(), isTrue);
  });

  test('saves and loads theme mode independently', () async {
    await service.saveSettings(host: 'example.com', nickname: 'Chanora');
    await service.saveThemeMode(UiThemeMode.dark);

    var settings = await service.loadSettings();

    expect(settings.host, 'example.com');
    expect(settings.nickname, 'Chanora');
    expect(settings.themeMode, UiThemeMode.dark);

    await service.saveThemeMode(UiThemeMode.light);
    settings = await service.loadSettings();

    expect(settings.host, 'example.com');
    expect(settings.nickname, 'Chanora');
    expect(settings.themeMode, UiThemeMode.light);
  });

  test('falls back to system theme mode for invalid stored values', () async {
    SharedPreferences.setMockInitialValues({'ui.theme_mode': 'sepia'});
    service = const UiPreferencesService();

    final settings = await service.loadSettings();

    expect(settings.themeMode, UiThemeMode.system);
  });
}
