import Foundation
import Observation
import SwiftUI

@Observable
@MainActor
final class AppPreferencesStore {
    private enum Keys {
        static let appearance = "appAppearance"
        static let debugPremiumEnabled = "debugPremiumEnabled"
        static let hasCompletedOnboarding = "hasCompletedOnboarding"
    }

    private let userDefaults: UserDefaults

    var appearance: AppAppearance {
        didSet {
            userDefaults.set(appearance.rawValue, forKey: Keys.appearance)
        }
    }

    var hasCompletedOnboarding: Bool {
        get { userDefaults.bool(forKey: Keys.hasCompletedOnboarding) }
        set { userDefaults.set(newValue, forKey: Keys.hasCompletedOnboarding) }
    }

    #if DEBUG
    var isDebugPremiumEnabled: Bool {
        get { userDefaults.bool(forKey: Keys.debugPremiumEnabled) }
        set { userDefaults.set(newValue, forKey: Keys.debugPremiumEnabled) }
    }
    #endif

    var preferredColorScheme: ColorScheme? {
        appearance.preferredColorScheme
    }

    init(userDefaults: UserDefaults = .standard) {
        self.userDefaults = userDefaults

        if let rawValue = userDefaults.string(forKey: Keys.appearance),
           let savedAppearance = AppAppearance(rawValue: rawValue) {
            self.appearance = savedAppearance
        } else {
            self.appearance = .system
        }
    }
}
