import SwiftUI
import Combine

/// App-wide settings persisted via @AppStorage and exposed as an
/// ObservableObject for views that need a single source of truth.
@MainActor
final class AppSettings: ObservableObject {
    /// Default URL for new windows. Override via the Settings pane or
    /// `CXWEBAPP_URL` env var at launch.
    @Published var backendURL: String {
        didSet { UserDefaults.standard.set(backendURL, forKey: "backendURL") }
    }

    /// Auto-reload every N seconds. 0 = disabled.
    @Published var autoReloadSeconds: Int {
        didSet { UserDefaults.standard.set(autoReloadSeconds, forKey: "autoReloadSeconds") }
    }

    /// Show the developer/inspector tools menu in the WebView.
    @Published var developerExtras: Bool {
        didSet { UserDefaults.standard.set(developerExtras, forKey: "developerExtras") }
    }

    init() {
        let env = ProcessInfo.processInfo.environment["CXWEBAPP_URL"]
        self.backendURL = env
            ?? UserDefaults.standard.string(forKey: "backendURL")
            ?? "http://127.0.0.1:8085"
        self.autoReloadSeconds = UserDefaults.standard.integer(forKey: "autoReloadSeconds")
        self.developerExtras = UserDefaults.standard.bool(forKey: "developerExtras")
    }
}
