package ui import ( "github.com/humdrum-tiv/sportsball/internal/config" "github.com/humdrum-tiv/sportsball/internal/model" ) // favKey is the stable identity of a favorited team: league + ESPN team id, // falling back to the abbreviation when no id is present. func favKey(league model.LeagueID, t model.Team) string { id := t.ID if id == "" { id = t.Abbr } return string(league) + ":" + id } // loadFavorites builds the in-memory favorites set from persisted config. func loadFavorites(cfg config.Config) map[string]bool { favs := make(map[string]bool, len(cfg.Favorites)) for _, f := range cfg.Favorites { id := f.ID if id == "" { id = f.Abbr } favs[f.League+":"+id] = true } return favs } // isFav reports whether a team is favorited. func (a App) isFav(league model.LeagueID, t model.Team) bool { return a.favs[favKey(league, t)] } // hasFav reports whether either side of a game is a favorite. func (a App) hasFav(g model.Game) bool { return a.isFav(g.League, g.Home) || a.isFav(g.League, g.Away) } // toggleFav flips a team's favorite state and persists the change. Persistence // is best-effort: a write failure leaves the in-memory toggle intact. func (a *App) toggleFav(league model.LeagueID, t model.Team) { key := favKey(league, t) if a.favs[key] { delete(a.favs, key) } else { a.favs[key] = true } a.cfg.Favorites = a.favoritesList() _ = config.Save(a.cfg) } // favoritesList rebuilds the persisted favorites slice from current data, // preserving display fields by scanning loaded games for each key. func (a App) favoritesList() []config.FavTeam { out := make([]config.FavTeam, 0, len(a.favs)) seen := map[string]bool{} for _, games := range a.games { for _, g := range games { for _, t := range []model.Team{g.Home, g.Away} { key := favKey(g.League, t) if a.favs[key] && !seen[key] { seen[key] = true out = append(out, config.FavTeam{ League: string(g.League), ID: t.ID, Abbr: t.Abbr, Name: t.Name, }) } } } } // Keep any favorites we couldn't resolve to a loaded game (id-only). for _, f := range a.cfg.Favorites { id := f.ID if id == "" { id = f.Abbr } key := f.League + ":" + id if a.favs[key] && !seen[key] { seen[key] = true out = append(out, f) } } return out }