import 'package:shared_preferences/shared_preferences.dart';

class ReactionService {
  static const _key = 'recent_reactions';
  static const _maxRecent = 6;

  static final _defaultReactions = ['👍', '❤️', '😂', '😮', '😢', '🙏'];

  static List<String> _recent = [];
  static bool _loaded = false;

  static Future<void> load() async {
    if (_loaded) return;
    final prefs = await SharedPreferences.getInstance();
    _recent = prefs.getStringList(_key) ?? [];
    _loaded = true;
  }

  static List<String> get quickReactions {
    if (_recent.isEmpty) return _defaultReactions;
    // Fill up to 6 with defaults not already in recent
    final result = List<String>.from(_recent);
    for (final d in _defaultReactions) {
      if (result.length >= _maxRecent) break;
      if (!result.contains(d)) result.add(d);
    }
    return result.take(_maxRecent).toList();
  }

  static Future<void> recordUsed(String emoji) async {
    await load();
    _recent.remove(emoji);
    _recent.insert(0, emoji);
    if (_recent.length > _maxRecent) _recent = _recent.sublist(0, _maxRecent);
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(_key, _recent);
  }
}
