//
//  PowerbankSidebarCardView.swift
//  USB Meter
//

import SwiftUI

struct PowerbankSidebarCardView: View {
    let powerbank: PowerbankSummary

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

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

    private var header: some View {
        HStack {
            Label(powerbank.name, systemImage: powerbank.identitySymbolName)
                .font(.headline)

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

    @ViewBuilder
    private var details: some View {
        Text(reportingSummary)
            .font(.caption2)
            .foregroundColor(.secondary)

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

    private var reportingSummary: String {
        switch powerbank.batteryLevelReporting {
        case .percent:
            return "Battery: 0–100%"
        case .bars:
            return "Battery: \(powerbank.batteryBarsCount) bars"
        case .fullOnly:
            return "Battery: full-only LED"
        case .none:
            return "Battery: not reported"
        }
    }
}
