//
//  UIView+Theme.swift
//  Gami
//
//  Created by OneeChan on 2026/4/1.
//

import Foundation
import UIKit
import Combine


enum LNViewGradientDirection {
    case horizontalLTR
    case horizontalRTL
    case verticalUTD
    case verticalDTU
    case custom(start: CGPoint, endPoint: CGPoint)
}

extension UIView {
    static func gradientView(_ colors: [UIColor], _ direction: LNViewGradientDirection) -> UIView {
        let view = UIView()
        view.isUserInteractionEnabled = false
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors.map({ $0.cgColor })
        switch direction {
        case .horizontalLTR:
            gradientLayer.startPoint = .zero
            gradientLayer.endPoint = .init(x: 1, y: 0)
        case .horizontalRTL:
            gradientLayer.startPoint = .init(x: 1, y: 0)
            gradientLayer.endPoint = .zero
        case .verticalUTD:
            gradientLayer.startPoint = .zero
            gradientLayer.endPoint = .init(x: 0, y: 1)
        case .verticalDTU:
            gradientLayer.startPoint = .init(x: 0, y: 1)
            gradientLayer.endPoint = .zero
        case .custom(let start, let endPoint):
            gradientLayer.startPoint = start
            gradientLayer.endPoint = endPoint
        }
        view.layer.addSublayer(gradientLayer)
        view.publisher(for: \.bounds).removeDuplicates().sink
        { [weak gradientLayer] newValue in
            guard let gradientLayer else { return }
            gradientLayer.frame = newValue
        }.store(in: &view.cancellables)
        
        return view
    }
}
