// lib/core/theme_manager.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ThemeManager {
  ThemeManager._();

  static const String _prefKey = 'is_dark_mode';
  static final ValueNotifier<ThemeMode> themeMode = ValueNotifier(ThemeMode.light);

  /// Call during app startup to load saved preference.
  static Future<void> init() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final isDark = prefs.getBool(_prefKey) ?? false;
      themeMode.value = isDark ? ThemeMode.dark : ThemeMode.light;
    } catch (e) {
      // If SharedPreferences fails, default to light theme
      print('Error initializing theme: $e');
      themeMode.value = ThemeMode.light;
    }
  }

  /// Set theme and persist
  static Future<void> setThemeMode(ThemeMode mode) async {
    themeMode.value = mode;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefKey, mode == ThemeMode.dark);
  }

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

  /// Toggle helper
  static Future<void> toggle() async {
    final newMode = themeMode.value == ThemeMode.dark ? ThemeMode.light : ThemeMode.dark;
    await setThemeMode(newMode);
  }
}
