import Foundation
import Combine

final class ProgressStore: ObservableObject {
    static let shared = ProgressStore()
    private let defaults = UserDefaults.standard
    private init() {}

    /// Bumped whenever stored progress changes. SwiftUI views that observe
    /// this store re-render automatically; the actual reads still go through
    /// the existing methods.
    @Published private(set) var version: Int = 0

    // MARK: - Keys

    private func starsKey(for levelId: String) -> String { "stars_\(levelId)" }
    private func completedKey(for levelId: String) -> String { "completed_\(levelId)" }

    // MARK: - API

    func starsFor(levelId: String) -> Int {
        defaults.integer(forKey: starsKey(for: levelId))   // returns 0 if missing
    }

    func setStars(_ stars: Int, for levelId: String) {
        let clamped = max(0, min(3, stars))
        // Only upgrade, never downgrade
        if clamped > starsFor(levelId: levelId) {
            defaults.set(clamped, forKey: starsKey(for: levelId))
            defaults.set(true, forKey: completedKey(for: levelId))
            version &+= 1
        }
    }

    func isCompleted(levelId: String) -> Bool {
        defaults.bool(forKey: completedKey(for: levelId))
    }

    func totalStars() -> Int {
        // Sum all stored star keys
        defaults.dictionaryRepresentation()
            .filter { $0.key.hasPrefix("stars_") }
            .values
            .compactMap { $0 as? Int }
            .reduce(0, +)
    }
}
