Files
MLBApp/mlbTVOS/ViewModels/GameCenterViewModel.swift
Trey t b5daddefd3 Add UI redesign: design system, dashboard density, game intelligence, feed tab, league leaders
Phase 1 - Design System: DesignSystem.swift (typography, colors, spacing
constants) and DataPanel.swift (reusable panel container with 3 densities
and optional team accent bar).

Phase 2 - Dashboard Density: LiveSituationBar (compact strip of all live
games with scores/innings/outs), MiniLinescoreView (R-H-E footer for game
cards), DiamondView (visual baseball diamond with runners and count).
Dashboard shows live situation bar when games are active. Game cards now
display mini linescore for live/final games.

Phase 3 - Game Center Intelligence: WinProbabilityChartView (full-game
line chart using Swift Charts with area fills), PitchArsenalView (pitch
type distribution with velocity bars). GameCenterViewModel now stores
full WP history array instead of just latest values.

Phase 4 - Feed Tab: MLBWebDataService (fetches league leaders from Stats
API, news headlines, transactions), FeedViewModel, FeedView with
reverse-chronological feed items. FeedItemView with colored edge bars
by category. Added 5th "Feed" tab to both tvOS and iOS.

Phase 5 - Intel Tab: LeaderboardView (top-5 stat cards with headshots),
integrated into LeagueCenterView. Renamed tabs: Games->Today,
League->Intel. LeagueCenterViewModel now fetches league leaders.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 13:12:09 -05:00

97 lines
3.2 KiB
Swift

import Foundation
import Observation
import OSLog
private let gameCenterLogger = Logger(subsystem: "com.treyt.mlbTVOS", category: "GameCenter")
private func logGameCenter(_ message: String) {
gameCenterLogger.debug("\(message, privacy: .public)")
print("[GameCenter] \(message)")
}
@Observable
@MainActor
final class GameCenterViewModel {
var feed: LiveGameFeed?
var highlights: [Highlight] = []
var winProbabilityHome: Double?
var winProbabilityAway: Double?
var winProbabilityHistory: [WinProbabilityEntry] = []
var isLoading = false
var errorMessage: String?
var lastUpdated: Date?
private let statsAPI = MLBStatsAPI()
@ObservationIgnored
private var lastHighlightsFetch: Date?
func watch(game: Game) async {
guard let gamePk = game.gamePk else {
logGameCenter("watch: no gamePk for game id=\(game.id)")
errorMessage = "No live game feed is available for this matchup."
return
}
logGameCenter("watch: starting for gamePk=\(gamePk)")
while !Task.isCancelled {
await refresh(gamePk: gamePk)
await refreshHighlightsIfNeeded(gamePk: gamePk, gameDate: game.gameDate)
await refreshWinProbability(gamePk: gamePk)
let liveState = feed?.gameData.status?.abstractGameState == "Live"
if !liveState {
break
}
try? await Task.sleep(for: .seconds(12))
}
}
func refresh(gamePk: String) async {
isLoading = true
errorMessage = nil
do {
logGameCenter("refresh: fetching feed for gamePk=\(gamePk)")
feed = try await statsAPI.fetchGameFeed(gamePk: gamePk)
logGameCenter("refresh: success playEvents=\(feed?.currentPlay?.playEvents?.count ?? 0) allPlays=\(feed?.liveData.plays.allPlays.count ?? 0)")
lastUpdated = Date()
} catch {
logGameCenter("refresh: FAILED gamePk=\(gamePk) error=\(error)")
errorMessage = "Failed to load game center."
}
isLoading = false
}
private func refreshHighlightsIfNeeded(gamePk: String, gameDate: String) async {
// Only fetch highlights every 60 seconds
if let last = lastHighlightsFetch, Date().timeIntervalSince(last) < 60 {
return
}
let serverAPI = MLBServerAPI()
do {
highlights = try await serverAPI.fetchHighlights(gamePk: gamePk, gameDate: gameDate)
lastHighlightsFetch = Date()
} catch {
// Highlights are supplementary don't surface errors
}
}
private func refreshWinProbability(gamePk: String) async {
do {
let entries = try await statsAPI.fetchWinProbability(gamePk: gamePk)
winProbabilityHistory = entries
if let latest = entries.last,
let home = latest.homeTeamWinProbability,
let away = latest.awayTeamWinProbability {
winProbabilityHome = home
winProbabilityAway = away
}
} catch {
// Win probability is supplementary don't surface errors
}
}
}