import SwiftUI

public struct Badge: View {
    let label: String
    let backgroundColor: Color?
    
    private var primaryColors: [Color] {
        [
            Colors.black03,
            Colors.pink03,
            Colors.violet03,
            Colors.indigo03,
            Colors.blue03,
            Colors.mint03,
            Colors.green03,
            Colors.lime03,
            Colors.yellow03,
            Colors.gold03,
            Colors.orange03,
            Colors.red03
        ]
    }
    
    public init(label: String = "Label", backgroundColor: Color? = nil) {
        self.label = label
        self.backgroundColor = backgroundColor
    }
    
    private func isNumber(_ text: String) -> Bool {
        return text.range(of: "^\\d+$", options: .regularExpression) != nil
    }
    
    private func formatTitle(_ text: String) -> String {
        if isNumber(text), let number = Int(text), number > 99 {
            return "99+"
        }
        return text
    }
    
    private var badgeColor: Color {
        // If a custom background color is provided, use it
        if let bgColor = backgroundColor {
            return bgColor
        }
        
        // Otherwise, use default colors based on label type
        if isNumber(label) {
            return Colors.red03 // error.primary
        } else {
            return Colors.orange03 // warning.primary
        }
    }
    
    public var body: some View {
        Text(formatTitle(label))
            .font(.system(size: scaleSize(10), weight: .bold))
            .foregroundColor(Colors.black01)
            .padding(.horizontal, Spacing.XS)
            .frame(minWidth: scaleSize(16), minHeight: scaleSize(16))
            .background(badgeColor)
            .cornerRadius(Radius.M)
            .overlay(
                RoundedRectangle(cornerRadius: Radius.M)
                    .stroke(Colors.black01, lineWidth: 1)
            )
    }
}

// MARK: - Preview
#if DEBUG
struct Badge_Previews: PreviewProvider {
    static var previews: some View {
        VStack(spacing: 20) {
            Badge(label: "5")
            Badge(label: "99")
            Badge(label: "100")
            Badge(label: "New")
            Badge(label: "Hot", backgroundColor: Colors.pink03)
        }
        .padding()
        .previewLayout(.sizeThatFits)
    }
}
#endif

