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

import 'autopilot_theme.dart';
import 'theme_registry.dart';

/// Manages the active [AutopilotTheme] and persists the user's selection.
///
/// ## Persistence
/// - Stored locally in [SharedPreferences] under [_kThemeKey].
/// - **NOT sent to the ESP32** — firmware is colour-agnostic.
/// - **NOT synchronised between displays** — each display (bridge / engine room)
///   maintains its own independent preference.
///
/// ## Usage
/// ```dart
/// // In main.dart — wrap the widget tree:
/// ChangeNotifierProvider<AutopilotThemeProvider>(
///   create: (_) => await AutopilotThemeProvider.load(),
///   child: const AutopilotApp(),
/// )
///
/// // Read the current theme anywhere in the tree:
/// final theme = context.watch<AutopilotThemeProvider>().current;
///
/// // Switch theme (e.g. from the Appearance screen):
/// await context.read<AutopilotThemeProvider>().setTheme('wine');
/// ```
class AutopilotThemeProvider extends ChangeNotifier {
  static const String _kThemeKey = 'autopilot.theme.id';

  AutopilotTheme _current;

  AutopilotThemeProvider(this._current);

  /// The currently active [AutopilotTheme].
  AutopilotTheme get current => _current;

  /// Loads the persisted theme preference from [SharedPreferences].
  ///
  /// Falls back to [ThemeRegistry.defaultId] if no preference is stored
  /// (e.g. first launch) or the stored id is no longer registered.
  static Future<AutopilotThemeProvider> load() async {
    final prefs = await SharedPreferences.getInstance();
    final id = prefs.getString(_kThemeKey) ?? ThemeRegistry.defaultId;
    return AutopilotThemeProvider(ThemeRegistry.byId(id));
  }

  /// Switches to the theme identified by [id] and persists the selection.
  ///
  /// Unknown ids silently fall back to [ThemeRegistry.defaultId].
  /// Notifies all listeners after the switch so the UI rebuilds.
  Future<void> setTheme(String id) async {
    _current = ThemeRegistry.byId(id);
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_kThemeKey, _current.id);
    notifyListeners();
  }
}
