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 {
        let hex = label.color.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
        guard hex.count == 6,
              let rgb = UInt64(hex, radix: 16)
        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) {
        let hex = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
        guard hex.count == 6,
              let rgb = UInt64(hex, radix: 16)
        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,
        )
    }
}

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