import Foundation class HistoryManager: ObservableObject { static let shared = HistoryManager() @Published var history: [Wallpaper] = [] private let key = "wallpaperHistory" private let maxHistoryItems = 50 init() { loadHistory() } func addToHistory(_ wallpaper: Wallpaper) { // Remove if existing to promote to top if let index = history.firstIndex(where: { $0.id == wallpaper.id }) { history.remove(at: index) } history.insert(wallpaper, at: 0) if history.count > maxHistoryItems { history = Array(history.prefix(maxHistoryItems)) } saveHistory() } func clearHistory() { history = [] saveHistory() } private func saveHistory() { if let data = try? JSONEncoder().encode(history) { UserDefaults.standard.set(data, forKey: key) } } private func loadHistory() { if let data = UserDefaults.standard.data(forKey: key), let decoded = try? JSONDecoder().decode([Wallpaper].self, from: data) { history = decoded } } }