//
//  Color+Extensions.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import SwiftUI

extension Color {
    
    /// Initialize Color from hex string
    /// - Parameter hex: Hex string (e.g., "#FFFFFF", "FFFFFF", "#FFF")
    init?(hex: String) {
        let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int: UInt64 = 0
        guard Scanner(string: hex).scanHexInt64(&int) else { return nil }
        let r, g, b, a: UInt64
        switch hex.count {
        case 3: (r, g, b, a) = (int >> 8, int >> 4 & 0xF, int & 0xF, 0xF)
        case 6: (r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF, 0xFF)
        case 8: (r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default: return nil
        }
        self.init(.sRGB,
                  red: Double(r) / 255,
                  green: Double(g) / 255,
                  blue: Double(b) / 255,
                  opacity: Double(a) / 255)
    }
    
    /// Convert Color to hex string
    /// - Returns: Hex string representation (e.g., "#FFFFFF")
    func toHex() -> String? {
        let uic = UIColor(self)
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        guard uic.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }
        let rgb: Int = Int(r*255)<<16 | Int(g*255)<<8 | Int(b*255)<<0
        return String(format: "#%06x", rgb)
    }
    
    /// Generate a random bright color
    /// - Returns: Hex string of a random bright color
    static func randomBrightColorHex() -> String {
        let hue = Double.random(in: 0...1)
        let color = Color(hue: hue, saturation: 0.9, brightness: 0.95)
        return color.toHex() ?? AppConstants.Defaults.digitColorHex
    }
}
