//
//  SidebarMeterCardView.swift
//  USB Meter
//

import SwiftUI

struct SidebarMeterCardView: View {
    @EnvironmentObject private var meter: Meter

    var body: some View {
        HStack(spacing: 14) {
            Image(systemName: "sensor.tag.radiowaves.forward.fill")
                .font(.system(size: 18, weight: .semibold))
                .foregroundColor(meter.color)
                .frame(width: 42, height: 42)
                .background(
                    Circle()
                        .fill(meter.color.opacity(0.18))
                )
                .overlay(alignment: .bottomTrailing) {
                    Circle()
                        .fill(connectivityTint)
                        .frame(width: 12, height: 12)
                        .overlay(
                            Circle()
                                .stroke(Color(uiColor: .systemBackground), lineWidth: 2)
                        )
                }

            VStack(alignment: .leading, spacing: 4) {
                Text(meter.name)
                    .font(.headline)
                Text(meter.deviceModelSummary)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }

            Spacer()

            VStack(alignment: .trailing, spacing: 4) {
                HStack(spacing: 6) {
                    Circle()
                        .fill(connectivityTint)
                        .frame(width: 8, height: 8)
                    Text(statusText)
                        .font(.caption.weight(.semibold))
                        .foregroundColor(.secondary)
                }
                .padding(.horizontal, 10)
                .padding(.vertical, 6)
                .background(
                    Capsule(style: .continuous)
                        .fill(connectivityTint.opacity(0.12))
                )
                .overlay(
                    Capsule(style: .continuous)
                        .stroke(connectivityTint.opacity(0.22), lineWidth: 1)
                )
            }
        }
        .padding(14)
        .meterCard(
            tint: meter.color,
            fillOpacity: 0.16,
            strokeOpacity: 0.22,
            cornerRadius: 18
        )
    }

    private var connectivityTint: Color {
        Meter.operationalColor(for: meter.operationalState)
    }

    private var statusText: String {
        switch meter.operationalState {
        case .notPresent:
            return "Missing"
        case .peripheralNotConnected:
            return "Available"
        case .peripheralConnectionPending:
            return "Connecting"
        case .peripheralConnected:
            return "Linked"
        case .peripheralReady:
            return "Ready"
        case .comunicating:
            return "Syncing"
        case .dataIsAvailable:
            return "Live"
        }
    }
}
