//
//  LNLoadingView.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/29.
//

import Foundation
import UIKit
import SnapKit

private weak var curLoadingView: LNLoadingView?

func showLoading() {
    guard curLoadingView == nil else { return }
    runOnMain {
        let view = LNLoadingView()
        view.show()
        
        curLoadingView = view
    }
}

func dismissLoading() {
    guard let curLoadingView else { return }
    
    runOnMain {
        curLoadingView.dismiss()
    }
}


class LNLoadingView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
    }
    
    func show() {
        UIView.appKeyWindow?.addSubview(self)
        self.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func dismiss() {
        removeFromSuperview()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNLoadingView {
    private func setupViews() {
        let container = UIView()
        container.backgroundColor = .black.withAlphaComponent(0.8)
        container.layer.cornerRadius = 16
        
        addSubview(container)
        container.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        let ic = UIImageView()
        ic.image = .icLoading
        container.addSubview(ic)
        ic.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(12)
        }
        
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue = Double.pi * 2
        rotationAnimation.duration = 2.0
        rotationAnimation.repeatCount = .infinity
        rotationAnimation.isRemovedOnCompletion = false
        rotationAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
        ic.layer.add(rotationAnimation, forKey: "rotationAnimation")
        
        let tipsLabel = UILabel()
        tipsLabel.text = .init(key: "A00001")
        tipsLabel.font = .body_m
        tipsLabel.textColor = .text_1
        container.addSubview(tipsLabel)
        tipsLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().offset(-12)
            make.top.equalTo(ic.snp.bottom).offset(4)
        }
    }
}
