import Foundation
import Observation

@Observable
@MainActor
public final class SettingsStore {
    var radioBrowserBaseURL: String {
        didSet { defaults.set(radioBrowserBaseURL, forKey: Keys.radioBrowserBaseURL) }
    }

    var resumeOnLaunch: Bool {
        didSet { defaults.set(resumeOnLaunch, forKey: Keys.resumeOnLaunch) }
    }

    var showMenuBarExtraDetails: Bool {
        didSet { defaults.set(showMenuBarExtraDetails, forKey: Keys.showMenuBarExtraDetails) }
    }

    private let defaults: UserDefaults

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        radioBrowserBaseURL = defaults.string(forKey: Keys.radioBrowserBaseURL) ?? "https://de1.api.radio-browser.info/json"
        resumeOnLaunch = defaults.object(forKey: Keys.resumeOnLaunch) as? Bool ?? false
        showMenuBarExtraDetails = defaults.object(forKey: Keys.showMenuBarExtraDetails) as? Bool ?? true
    }

    var baseURL: URL {
        URL(string: radioBrowserBaseURL) ?? URL(string: "https://de1.api.radio-browser.info/json")!
    }

    private enum Keys {
        static let radioBrowserBaseURL = "radioBrowserBaseURL"
        static let resumeOnLaunch = "resumeOnLaunch"
        static let showMenuBarExtraDetails = "showMenuBarExtraDetails"
    }
}
