/**
 * Team Logo Utility — serves locally cached logos from /logos/{league}/{abbr}.png
 * Logos sourced from ESPN CDN and cached in public/logos/
 *
 * For NCAAB: SGO abbreviations mapped to ESPN numeric IDs, saved as {sgo_abbr}.png
 * For EPL: SGO abbreviations mapped to ESPN soccer IDs, saved as {sgo_abbr}.png
 * For NBA/NHL/NFL/MLB: abbreviations match ESPN directly (lowercase)
 */

// SGO abbreviation overrides — normalize to the filename we saved
const ABBR_FIX: Record<string, string> = {
  // NBA
  'PHX': 'phx', 'GS': 'gs', 'GSW': 'gs', 'SA': 'sa', 'SAS': 'sa',
  'NY': 'ny', 'NYK': 'ny', 'NO': 'no', 'NOP': 'no',
  'BKN': 'bkn', 'WSH': 'wsh', 'WAS': 'wsh',
  // NFL
  'JAX': 'jax', 'LV': 'lv', 'LAR': 'lar', 'LAC': 'lac',
  'SF': 'sf', 'TB': 'tb', 'GB': 'gb', 'KC': 'kc', 'NE': 'ne',
  // MLB
  'NYY': 'nyy', 'NYM': 'nym', 'CWS': 'chw', 'SD': 'sd',
  'STL': 'stl',
  // NHL
  'NJ': 'nj', 'LA': 'la', 'SJ': 'sj',
  // EPL common variants
  'MCI': 'mci', 'MAC': 'mci', 'MC': 'mci',
  'MUN': 'mun', 'MU': 'mun', 'MANU': 'mun',
  'ARS': 'ars', 'AVL': 'avl', 'AST': 'avl',
  'BHA': 'bha', 'BRI': 'bha',
  'BOU': 'bou', 'BRE': 'bre', 'CHE': 'che',
  'CRY': 'cry', 'CP': 'cry',
  'EVE': 'eve', 'FUL': 'ful', 'LEI': 'lei',
  'LIV': 'liv', 'NEW': 'new', 'NU': 'new',
  'NFO': 'nfo', 'NOT': 'nfo', 'NF': 'nfo',
  'SOU': 'sou', 'TOT': 'tot', 'TH': 'tot',
  'WHU': 'whu', 'WES': 'whu',
  'WOL': 'wol', 'WW': 'wol',
  'IPC': 'ipc', 'LUT': 'lut',
};

// Leagues that use the standard {abbr}.png pattern locally
const SUPPORTED_LEAGUES = new Set(['nba', 'nhl', 'nfl', 'mlb', 'ncaab', 'ncaaf', 'epl', 'mma', 'wnba']);

export function getTeamLogoUrl(league: string, shortName: string): string | null {
  const lg = league.toLowerCase();
  if (!SUPPORTED_LEAGUES.has(lg)) return null;

  // For ncaaf, use ncaab logos (same schools)
  const logoLeague = lg === 'ncaaf' ? 'ncaab' : lg === 'wnba' ? 'nba' : lg;

  // Normalize abbreviation
  const upper = shortName.toUpperCase();
  const abbr = (ABBR_FIX[upper] || shortName).toLowerCase();

  return `/logos/${logoLeague}/${abbr}.webp`;
}

// Generate a stable color from team name for fallback circles
export function getTeamColor(teamName: string): string {
  let hash = 0;
  for (let i = 0; i < teamName.length; i++) {
    hash = teamName.charCodeAt(i) + ((hash << 5) - hash);
  }
  const h = Math.abs(hash) % 360;
  return `hsl(${h}, 55%, 45%)`;
}
