//
//  UIColor+Extension.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/6.
//

import Foundation
import UIKit

extension UIColor {
    /// 从十六进制字符串创建UIColor，转换失败时返回透明色
    /// - Parameter hexString: 十六进制颜色字符串，格式可以是 "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA"
    convenience init(hex: String) {
        // 移除字符串中的 # 符号和空白字符
        let cleanedString = hex.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "#", with: "")
        
        var rgbValue: UInt64 = 0
        // 扫描字符串并转换为UInt64
        let success = Scanner(string: cleanedString).scanHexInt64(&rgbValue)
        
        let red: CGFloat
        let green: CGFloat
        let blue: CGFloat
        let alpha: CGFloat
        
        if success {
            switch cleanedString.count {
            case 3: // RGB (12-bit)
                red = CGFloat((rgbValue & 0xF00) >> 8) / 15.0
                green = CGFloat((rgbValue & 0x0F0) >> 4) / 15.0
                blue = CGFloat(rgbValue & 0x00F) / 15.0
                alpha = 1.0
                
            case 4: // RGBA (16-bit)
                red = CGFloat((rgbValue & 0xF000) >> 12) / 15.0
                green = CGFloat((rgbValue & 0x0F00) >> 8) / 15.0
                blue = CGFloat((rgbValue & 0x00F0) >> 4) / 15.0
                alpha = CGFloat(rgbValue & 0x000F) / 15.0
                
            case 6: // RGB (24-bit)
                red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
                green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
                blue = CGFloat(rgbValue & 0x0000FF) / 255.0
                alpha = 1.0
                
            case 8: // RGBA (32-bit)
                red = CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0
                green = CGFloat((rgbValue & 0x00FF0000) >> 16) / 255.0
                blue = CGFloat((rgbValue & 0x0000FF00) >> 8) / 255.0
                alpha = CGFloat(rgbValue & 0x000000FF) / 255.0
                
            default:
                // 不符合任何支持的格式，使用透明色
                red = 0
                green = 0
                blue = 0
                alpha = 0
            }
        } else {
            // 扫描失败，使用透明色
            red = 0
            green = 0
            blue = 0
            alpha = 0
        }
        
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
}

extension UIColor {
    // MARK: - 1. RGB 线性过渡（基础版）
    /// 计算从当前颜色到目标颜色的过渡色（RGB 插值）
    /// - Parameters:
    ///   - toColor: 目标颜色
    ///   - progress: 过渡进度（0~1，0=当前色，1=目标色）
    /// - Returns: 过渡后的中间色
    func interpolateRGB(to toColor: UIColor, progress: CGFloat) -> UIColor {
        // 限制进度在 0~1 范围内
        let clampedProgress = max(0, min(1, progress))
        
        // 获取当前颜色的 RGB+Alpha 分量
        var fromRed: CGFloat = 0, fromGreen: CGFloat = 0, fromBlue: CGFloat = 0, fromAlpha: CGFloat = 0
        self.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)
        
        // 获取目标颜色的 RGB+Alpha 分量
        var toRed: CGFloat = 0, toGreen: CGFloat = 0, toBlue: CGFloat = 0, toAlpha: CGFloat = 0
        toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha)
        
        // 线性插值计算中间分量
        let red = fromRed + (toRed - fromRed) * clampedProgress
        let green = fromGreen + (toGreen - fromGreen) * clampedProgress
        let blue = fromBlue + (toBlue - fromBlue) * clampedProgress
        let alpha = fromAlpha + (toAlpha - fromAlpha) * clampedProgress
        
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    // MARK: - HSB 色相过渡（自然渐变版）
    /// 计算从当前颜色到目标颜色的过渡色（HSB 插值，色相更自然）
    /// - Parameters:
    ///   - toColor: 目标颜色
    ///   - progress: 过渡进度（0~1）
    /// - Returns: 过渡后的中间色
    func interpolateHSB(to toColor: UIColor, progress: CGFloat) -> UIColor {
        let clampedProgress = max(0, min(1, progress))
        
        // 获取当前颜色的 HSB+Alpha 分量
        var fromHue: CGFloat = 0, fromSaturation: CGFloat = 0, fromBrightness: CGFloat = 0, fromAlpha: CGFloat = 0
        self.getHue(&fromHue, saturation: &fromSaturation, brightness: &fromBrightness, alpha: &fromAlpha)
        
        // 获取目标颜色的 HSB+Alpha 分量
        var toHue: CGFloat = 0, toSaturation: CGFloat = 0, toBrightness: CGFloat = 0, toAlpha: CGFloat = 0
        toColor.getHue(&toHue, saturation: &toSaturation, brightness: &toBrightness, alpha: &toAlpha)
        
        // 色相插值：处理 0/1 边界（如红色 Hue=0 到紫色 Hue=1，走短路径）
        var hueDelta = toHue - fromHue
        if hueDelta > 0.5 {
            hueDelta -= 1.0
        } else if hueDelta < -0.5 {
            hueDelta += 1.0
        }
        let hue = fromHue + hueDelta * clampedProgress
        
        // 饱和度、亮度、透明度插值
        let saturation = fromSaturation + (toSaturation - fromSaturation) * clampedProgress
        let brightness = fromBrightness + (toBrightness - fromBrightness) * clampedProgress
        let alpha = fromAlpha + (toAlpha - fromAlpha) * clampedProgress
        
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
    }
}
