import ForgejoKit
import SwiftUI

struct IssueLabelView: View {
    let label: IssueLabel

    var body: some View {
        Text(label.name)
            .font(.caption2)
            .fontWeight(.medium)
            .padding(.horizontal, 8)
            .padding(.vertical, 3)
            .foregroundStyle(textColor)
            .glassEffect(.regular.tint(backgroundColor))
    }

    private var backgroundColor: Color {
        Color(hex: label.color) ?? .gray
    }

    private var textColor: Color {
        guard let rgb = Color.rgbValue(hex: label.color) else {
            return .white
        }
        let red = Double((rgb >> 16) & 0xFF) / 255.0
        let green = Double((rgb >> 8) & 0xFF) / 255.0
        let blue = Double(rgb & 0xFF) / 255.0
        let luminance = 0.299 * red + 0.587 * green + 0.114 * blue
        return luminance > 0.5 ? .black : .white
    }
}

extension Color {
    init?(hex: String) {
        guard let rgb = Color.rgbValue(hex: hex) else {
            return nil
        }
        self.init(
            red: Double((rgb >> 16) & 0xFF) / 255.0,
            green: Double((rgb >> 8) & 0xFF) / 255.0,
            blue: Double(rgb & 0xFF) / 255.0,
        )
    }

    /// Parses a 6-digit or 3-digit shorthand hex color into its RGB value,
    /// expanding the shorthand the same way Forgejo normalizes label colors
    /// (#f00 -> #ff0000). Labels created before Forgejo normalized colors on
    /// write can still carry the shorthand form.
    static func rgbValue(hex: String) -> UInt64? {
        var hex = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
        if hex.count == 3 {
            hex = hex.map { "\($0)\($0)" }.joined()
        }
        guard hex.count == 6 else {
            return nil
        }
        return UInt64(hex, radix: 16)
    }
}

#if DEBUG
    #Preview {
        HStack {
            ForEach(IssueLabel.previewList) { label in
                IssueLabelView(label: label)
            }
        }
        .padding()
    }
#endif
