import SwiftUI
import VNCCore

struct ConnectionCard: View {
    let connection: SavedConnection

    var body: some View {
        HStack(spacing: 14) {
            ZStack {
                Circle()
                    .fill(connection.colorTag.color.opacity(0.18))
                    .frame(width: 38, height: 38)
                Circle()
                    .fill(connection.colorTag.color)
                    .frame(width: 14, height: 14)
            }
            VStack(alignment: .leading, spacing: 2) {
                Text(connection.displayName)
                    .font(.headline)
                    .foregroundStyle(.primary)
                    .lineLimit(1)
                Text("\(connection.host):\(portLabel(connection.port))")
                    .font(.caption.monospacedDigit())
                    .foregroundStyle(.secondary)
                    .lineLimit(1)
                    .truncationMode(.middle)
                if connection.viewOnly {
                    Label("View only", systemImage: "eye")
                        .labelStyle(.titleAndIcon)
                        .font(.caption2)
                        .foregroundStyle(.tertiary)
                }
            }
            Spacer(minLength: 8)
            VStack(alignment: .trailing, spacing: 4) {
                if let last = connection.lastConnectedAt {
                    Text(last, format: .relative(presentation: .numeric, unitsStyle: .abbreviated))
                        .font(.caption2)
                        .foregroundStyle(.tertiary)
                        .lineLimit(1)
                }
                Image(systemName: "chevron.right")
                    .font(.caption2.weight(.bold))
                    .foregroundStyle(.tertiary)
            }
        }
        .padding(.vertical, 6)
        .contentShape(Rectangle())
    }
}

extension ColorTag {
    var color: Color {
        switch self {
        case .red: .red
        case .orange: .orange
        case .yellow: .yellow
        case .green: .green
        case .blue: .blue
        case .purple: .purple
        case .pink: .pink
        case .gray: .gray
        }
    }
}
