import SwiftUI
import Bedrock

/// Displays a circular avatar with either a photo or a system icon fallback.
/// Reusable across business cards, editor previews, and contact rows.
struct AvatarBadgeView: View {
    let systemName: String
    let accentColor: Color
    let photoData: Data?
    let size: CGFloat
    let borderColor: Color
    
    init(
        systemName: String = "person.crop.circle",
        accentColor: Color = Color.Accent.red,
        photoData: Data? = nil,
        size: CGFloat = Design.CardSize.avatarSize,
        borderColor: Color = Color.Text.inverted
    ) {
        self.systemName = systemName
        self.accentColor = accentColor
        self.photoData = photoData
        self.size = size
        self.borderColor = borderColor
    }
    
    var body: some View {
        if let photoData, let uiImage = UIImage(data: photoData) {
            Image(uiImage: uiImage)
                .resizable()
                .scaledToFill()
                .frame(width: size, height: size)
                .clipShape(.circle)
                .overlay(
                    Circle()
                        .stroke(borderColor.opacity(Design.Opacity.medium), lineWidth: Design.LineWidth.thin)
                )
        } else {
            Circle()
                .fill(borderColor)
                .frame(width: size, height: size)
                .overlay(
                    Image(systemName: systemName)
                        .foregroundStyle(accentColor)
                )
                .overlay(
                    Circle()
                        .stroke(borderColor.opacity(Design.Opacity.medium), lineWidth: Design.LineWidth.thin)
                )
        }
    }
}

#Preview {
    VStack(spacing: Design.Spacing.large) {
        AvatarBadgeView(
            systemName: "person.crop.circle",
            accentColor: Color.CardPalette.coral
        )
        
        AvatarBadgeView(
            systemName: "briefcase.fill",
            accentColor: Color.CardPalette.ocean,
            size: 80,
            borderColor: Color.Text.primary
        )
    }
    .padding()
    .background(Color.CardPalette.midnight)
}
