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

import SwiftUI

struct ChargedDeviceSidebarCardView: View {
    let chargedDevice: ChargedDeviceSummary

    var body: some View {
        HStack(alignment: .top, spacing: 12) {
            ChargedDeviceQRCodeView(qrIdentifier: chargedDevice.qrIdentifier, side: 54)

            VStack(alignment: .leading, spacing: 6) {
                header
                Text(chargedDevice.identityTitle)
                    .font(.caption.weight(.semibold))
                    .foregroundColor(.secondary)
                details
            }
        }
        .padding(.vertical, 4)
    }

    private var header: some View {
        HStack {
            ChargedDeviceIdentityLabelView(
                chargedDevice: chargedDevice,
                iconPointSize: 17
            )
            .font(.headline)

            if chargedDevice.activeSession != nil {
                Spacer()
                Text("Live")
                    .font(.caption.weight(.bold))
                    .foregroundColor(.green)
            }
        }
    }

    @ViewBuilder
    private var details: some View {
        if chargedDevice.isCharger {
            if let chargerMaximumPowerWatts = chargedDevice.chargerMaximumPowerWatts {
                Text("Max power: \(chargerMaximumPowerWatts.format(decimalDigits: 2)) W")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            } else {
                Text("Wireless charger")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            }
        } else {
            Text(chargedDevice.supportedChargingModes.map(\.title).joined(separator: " + "))
                .font(.caption2)
                .foregroundColor(.secondary)

            if let estimatedCapacityWh = chargedDevice.estimatedBatteryCapacityWh {
                Text("Capacity: \(estimatedCapacityWh.format(decimalDigits: 2)) Wh")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            } else {
                Text("Capacity: learning")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            }
        }
    }
}
