import Foundation
import Observation
import Bedrock

@MainActor
@Observable
final class SettingsStore: CloudSyncable, ThemeProviding {
    @ObservationIgnored private let cloudSync = CloudSyncManager<AppSettingsData>()
    
    /// Observable copy of last sync date, updated when sync completes.
    private(set) var lastSyncDate: Date?
    
    /// Observable copy of sync status, updated when sync state changes.
    private(set) var syncStatus: String = ""
    
    /// Observable copy of initial sync state.
    private(set) var hasCompletedInitialSync: Bool = false

    var hapticsEnabled: Bool {
        get { cloudSync.data.hapticsEnabled }
        set { update { $0.hapticsEnabled = newValue } }
    }

    var soundEnabled: Bool {
        get { cloudSync.data.soundEnabled }
        set { update { $0.soundEnabled = newValue } }
    }

    var theme: AppTheme {
        get { cloudSync.data.theme }
        set { update { $0.theme = newValue } }
    }

    var iCloudAvailable: Bool { cloudSync.iCloudAvailable }

    var iCloudEnabled: Bool {
        get { cloudSync.iCloudEnabled }
        set { cloudSync.iCloudEnabled = newValue }
    }

    init() {
        // Initialize observable properties from cloudSync
        refreshSyncState()
    }

    func forceSync() {
        cloudSync.sync()
        refreshSyncState()
    }

    func refresh() {
        cloudSync.sync()
        refreshSyncState()
    }

    private func update(_ transform: (inout AppSettingsData) -> Void) {
        cloudSync.update { data in
            transform(&data)
        }
        refreshSyncState()
    }
    
    /// Copies sync state from CloudSyncManager to observable properties.
    private func refreshSyncState() {
        lastSyncDate = cloudSync.lastSyncDate
        syncStatus = cloudSync.syncStatus
        hasCompletedInitialSync = cloudSync.hasCompletedInitialSync
    }
}

extension SettingsStore {
    static var preview: SettingsStore {
        SettingsStore()
    }
}
