import Foundation
import Observation

@Observable
@MainActor
final class WatchCardStore {
    private static let appGroupID = "group.com.mbrucedogs.BusinessCard"
    private static let cardsKey = "SyncedCards"
    private static let defaultCardIDKey = "WatchDefaultCardID"

    private(set) var cards: [WatchCard] = []
    var defaultCardID: UUID? {
        didSet {
            persistDefaultID()
        }
    }

    private var sharedDefaults: UserDefaults? {
        UserDefaults(suiteName: Self.appGroupID)
    }

    init() {
        loadCards()
        loadDefaultID()
    }

    var defaultCard: WatchCard? {
        guard let defaultCardID else { return cards.first(where: { $0.isDefault }) ?? cards.first }
        return cards.first(where: { $0.id == defaultCardID }) ?? cards.first(where: { $0.isDefault }) ?? cards.first
    }

    func loadCards() {
        guard let defaults = sharedDefaults,
              let data = defaults.data(forKey: Self.cardsKey),
              let decoded = try? JSONDecoder().decode([WatchCard].self, from: data) else {
            // Fall back to sample data if no synced data available
            cards = WatchCard.samples
            return
        }
        cards = decoded
    }

    func setDefault(_ card: WatchCard) {
        defaultCardID = card.id
    }

    private func persistDefaultID() {
        UserDefaults.standard.set(defaultCardID?.uuidString ?? "", forKey: Self.defaultCardIDKey)
    }

    private func loadDefaultID() {
        let storedValue = UserDefaults.standard.string(forKey: Self.defaultCardIDKey) ?? ""
        if let id = UUID(uuidString: storedValue), cards.contains(where: { $0.id == id }) {
            defaultCardID = id
        } else {
            defaultCardID = cards.first(where: { $0.isDefault })?.id ?? cards.first?.id
        }
    }
}
