//
// TeamLogo.swift
// IceGlass-iOS
//
// Copyright 2026 Rouslan Zenetl. All Rights Reserved.
//

import SwiftUI
import UIKit

/// Loads a bundled team logo PNG from `TeamLogos/{abbrev}.png`. Falls back to
/// an SF Symbol if the file is missing (e.g. abbrev is "TBD" for unfilled
/// playoff matchups).
struct TeamLogo: View {
    let abbrev: String
    var size: CGFloat = 22

    var body: some View {
        Group {
            if let image = Self.loadImage(for: abbrev) {
                Image(uiImage: image)
                    .resizable()
                    .interpolation(.high)
                    .scaledToFit()
            } else {
                Image(systemName: "shield")
                    .resizable()
                    .scaledToFit()
                    .foregroundStyle(.tertiary)
            }
        }
        .frame(width: size, height: size)
    }

    /// Bundle lookup is trivial but image decoding isn't free — cache by
    /// abbrev so scrolling through 16+ rows doesn't repeatedly hit disk.
    private static var cache: [String: UIImage] = [:]

    private static func loadImage(for abbrev: String) -> UIImage? {
        if let cached = cache[abbrev] { return cached }
        guard let url = Bundle.main.url(
            forResource: abbrev, withExtension: "png", subdirectory: "TeamLogos"
        ), let image = UIImage(contentsOfFile: url.path) else {
            return nil
        }
        cache[abbrev] = image
        return image
    }
}
