//
//  ChargedDeviceIdentityViews.swift
//  USB Meter
//
//  Created by Codex on 22/04/2026.
//

import SwiftUI
import UIKit

struct ChargedDeviceIdentityLabelView: View {
    let chargedDevice: ChargedDeviceSummary
    var iconPointSize: CGFloat = 15

    var body: some View {
        HStack(alignment: .firstTextBaseline, spacing: 8) {
            ChargedDeviceTemplateIconView(
                icon: chargedDevice.identityIcon,
                fallbackSystemName: chargedDevice.fallbackIdentitySymbolName,
                pointSize: iconPointSize
            )
            Text(chargedDevice.name)
        }
    }
}

struct ChargedDeviceTemplateLabelView: View {
    let template: ChargedDeviceTemplateDefinition
    var iconPointSize: CGFloat = 15

    var body: some View {
        HStack(alignment: .firstTextBaseline, spacing: 8) {
            ChargedDeviceTemplateIconView(
                icon: template.icon,
                fallbackSystemName: template.deviceClass.symbolName,
                pointSize: iconPointSize
            )
            Text(template.name)
        }
    }
}

struct ChargedDeviceTemplateIconView: View {
    let icon: ChargedDeviceTemplateIcon
    let fallbackSystemName: String
    var pointSize: CGFloat = 15

    var body: some View {
        Group {
            if let assetName = resolvedAssetName {
                Image(assetName)
                    .renderingMode(.template)
                    .resizable()
                    .scaledToFit()
            } else {
                Image(systemName: resolvedSystemSymbolName)
                    .font(.system(size: pointSize))
            }
        }
        .frame(width: pointSize + 2, height: pointSize + 2)
    }

    private var resolvedAssetName: String? {
        guard icon.type == .asset, UIImage(named: icon.name) != nil else {
            return nil
        }
        return icon.name
    }

    private var resolvedSystemSymbolName: String {
        let candidate = icon.resolvedSystemSymbolName(fallbackSystemName: fallbackSystemName)
        if UIImage(systemName: candidate) != nil {
            return candidate
        }

        if let fallbackSystemName = icon.fallbackSystemName,
           UIImage(systemName: fallbackSystemName) != nil {
            return fallbackSystemName
        }

        return fallbackSystemName
    }
}
