//
//  ColorLabel.swift

//
//  Created by Leon on 2025/7/27.
//

import UIKit

class ColorLabel: UILabel {
    
    enum GradientStyle {
        case sunset      // 两色渐变
        case ocean       // 三色渐变
        case theme        // 两色渐变
        case vip            // VIP
        case custom(colors: [UIColor]) // 可自定义颜色数组
        
        var colors: [UIColor] {
            switch self {
            case .sunset:
                return [UIColor.red, UIColor.orange]
            case .ocean:
                return [UIColor.cyan, UIColor.blue, UIColor.purple]
            case .theme:
                let gradient = CLSystemToken.gradient(token: .cpgn)
                return gradient.colors()
            case .vip:
                let gradient = CLSystemToken.gradient(token: .ccvn)
                return gradient.colors()
            case .custom(let colors):
                return colors
            }
        }
    }
    
    private var gradientStyle: GradientStyle?
    private var gradientLayer: CAGradientLayer?
    
    /// 设置渐变样式
    func applyGradient(_ style: GradientStyle) {
        self.gradientStyle = style
        setNeedsLayout()
    }
    
    func clearGradient(){
        self.gradientStyle = nil
        gradientLayer?.removeFromSuperlayer()
        setNeedsLayout()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let style = gradientStyle, bounds.size.width > 0 , bounds.size.height > 0 else { return }
        
        gradientLayer?.removeFromSuperlayer()
        
        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = style.colors.map { $0.cgColor }
        gradient.startPoint = CGPoint(x: 0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1, y: 0.5)
        
        // 用渐变图层做文字填充
        gradient.mask = textLayer()
        
        layer.addSublayer(gradient)
        gradientLayer = gradient
    }
    
    private func textLayer() -> CALayer {
        let text = self.text ?? ""
        let font = self.font ?? UIFont.systemFont(ofSize: 17)
        
        let label = UILabel()
        label.frame = bounds
        label.text = text
        label.font = font
        label.textAlignment = textAlignment
        label.textColor = .black // 不影响遮罩，只为了内容
        
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
        label.layer.render(in: UIGraphicsGetCurrentContext()!)
        let maskImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        let maskLayer = CALayer()
        maskLayer.contents = maskImage?.cgImage
        maskLayer.frame = bounds
        return maskLayer
    }
}
