import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ThemeController extends ValueNotifier<ThemeMode> {
  ThemeController._(this.storageKey) : super(ThemeMode.light);

  static const appStorageKey = 'userfront_theme';
  static const authStorageKey = 'userfront_auth_theme';
  static final ThemeController app = ThemeController._(appStorageKey);
  static final ThemeController auth = ThemeController._(authStorageKey);
  static final ThemeController instance = app;

  final String storageKey;

  bool get isDark => value == ThemeMode.dark;

  Future<void> restore() async {
    final prefs = await SharedPreferences.getInstance();
    final stored = prefs.getString(storageKey);
    value = stored == 'dark' ? ThemeMode.dark : ThemeMode.light;
  }

  Future<void> setThemeMode(ThemeMode mode) async {
    if (value != mode) {
      value = mode;
    }
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(
      storageKey,
      mode == ThemeMode.dark ? 'dark' : 'light',
    );
  }

  Future<void> toggle() {
    return setThemeMode(isDark ? ThemeMode.light : ThemeMode.dark);
  }
}
