import Foundation
import Observation
import SwiftData
import SwiftUI

enum AppAppearance: String, CaseIterable, Sendable {
    case system
    case light
    case dark

    var preferredColorScheme: ColorScheme? {
        switch self {
        case .system: nil
        case .light: .light
        case .dark: .dark
        }
    }
}

@Observable
@MainActor
final class AppState {
    private enum DefaultsKey {
        static let appearance = "appAppearance"
    }

    var selectedTab: AppTab = .cards
    var cardStore: CardStore
    var contactsStore: ContactsStore
    let shareLinkService: ShareLinkProviding
    var appearance: AppAppearance {
        didSet {
            UserDefaults.standard.set(appearance.rawValue, forKey: DefaultsKey.appearance)
        }
    }

    var preferredColorScheme: ColorScheme? {
        appearance.preferredColorScheme
    }

    init(modelContext: ModelContext) {
        self.cardStore = CardStore(modelContext: modelContext)
        self.contactsStore = ContactsStore(modelContext: modelContext)
        self.shareLinkService = ShareLinkService()
        if let rawValue = UserDefaults.standard.string(forKey: DefaultsKey.appearance),
           let savedAppearance = AppAppearance(rawValue: rawValue) {
            self.appearance = savedAppearance
        } else {
            self.appearance = .system
        }

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