import Foundation
import Observation
import SwiftData
import SwiftUI

@Observable
@MainActor
final class AppState {
    var selectedTab: AppTab = .cards
    var shouldPresentCreateCardFlow = false
    var cardStore: CardStore
    var contactsStore: ContactsStore
    let preferences: AppPreferencesStore
    let appSettings: AppSettingsStore
    let shareLinkService: ShareLinkProviding

    var preferredColorScheme: ColorScheme? {
        preferences.preferredColorScheme
    }

    var appearance: AppAppearance {
        get { preferences.appearance }
        set { preferences.appearance = newValue }
    }

    init(modelContext: ModelContext) {
        self.cardStore = CardStore(modelContext: modelContext)
        self.contactsStore = ContactsStore(modelContext: modelContext)
        self.preferences = AppPreferencesStore()
        self.appSettings = AppSettingsStore(modelContext: modelContext)
        self.shareLinkService = ShareLinkService()

        // Clean up expired shared cards on launch (best-effort, non-blocking)
        Task {
            await SharedCardCloudKitService().cleanupExpiredCards()
        }
    }
}
