import Foundation
import Observation

@Observable
@MainActor
final class WatchCardStore {
    private(set) var cards: [WatchCard] = []
    
    /// The ID of the default card (synced from iPhone)
    private(set) var defaultCardID: UUID?

    init() {
        WatchDesign.debugLog("WatchCardStore: Initialized, waiting for cards from iPhone")
        
        // Set up callback for when cards are received from iPhone
        WatchConnectivityService.shared.onCardsReceived = { [weak self] cards in
            self?.updateCards(cards)
        }
    }

    /// The default card to display (always synced from iPhone)
    var defaultCard: WatchCard? {
        if let defaultCardID {
            return cards.first { $0.id == defaultCardID }
        }
        return cards.first { $0.isDefault } ?? cards.first
    }
    
    /// Called by WatchConnectivityService when cards are received from iPhone
    func updateCards(_ newCards: [WatchCard]) {
        WatchDesign.debugLog("WatchCardStore: Received \(newCards.count) cards from iPhone")
        cards = newCards
        
        // Always use the iPhone's default card - the watch no longer has its own picker
        defaultCardID = cards.first { $0.isDefault }?.id ?? cards.first?.id
    }
}
