import 'package:shared_preferences/shared_preferences.dart';
import 'analytics_service.dart';
class FavoritesService {
FavoritesService._();
static final Map<String, Set<String>> _memoryFallback =
<String, Set<String>>{};
static const _poiKey = 'mw_favorites_pois_v1';
static const _tourKey = 'mw_favorites_tours_v1';
static Future<Set<String>> poiIds() async => _read(_poiKey);
static Future<Set<String>> tourIds() async => _read(_tourKey);
static Future<bool> isPoiFavorite(String id) async =>
(await poiIds()).contains(id);
static Future<bool> isTourFavorite(String id) async =>
(await tourIds()).contains(id);
static Future<bool> togglePoi(String id) async {
final value = await _toggle(_poiKey, id);
await AnalyticsService.instance.track(
value ? 'favorite_add' : 'favorite_remove',
properties: {'poi_id': id});
return value;
}
static Future<bool> toggleTour(String id) async {
final value = await _toggle(_tourKey, id);
await AnalyticsService.instance.track(
value ? 'favorite_add' : 'favorite_remove',
properties: {'tour_id': id});
return value;
}
static Future<Set<String>> _read(String key) async {
try {
final prefs = await SharedPreferences.getInstance();
final values = (prefs.getStringList(key) ?? const <String>[]).toSet();
_memoryFallback[key] = Set<String>.from(values);
return values;
} catch (_) {
return Set<String>.from(_memoryFallback[key] ?? const <String>{});
}
}
static Future<bool> _toggle(String key, String id) async {
final values = await _read(key);
final nowFavorite = !values.remove(id);
if (nowFavorite) values.add(id);
_memoryFallback[key] = Set<String>.from(values);
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(key, values.toList()..sort());
} catch (_) {
// Keep favourites usable for the current session.
}
return nowFavorite;
}
}

