//
//  CoinsRechargeGridCell.swift

//
//  Created by Leon on 2025/9/15.
//

import UIKit

class CoinsRechargeGridCell: UICollectionViewCell{
    var block: UIView!
    
    var stackV: UIStackView!
    var iconAndLabel: CLIconLabel!
    var priceLabel : CLLabel!
    
    var data : IAPProducts?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        block = {
            let v = UIView()
            v.cornerRadius = 16
            v.backgroundColor = .c.csbn
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
        
        stackV = {
            let v = UIStackView()
            v.spacing = 8
            v.axis = .vertical
            v.alignment = .center
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        iconAndLabel = {
            let v = CLIconLabel()
            v.spacing = 8
            v.iconSize = CGSize(width: 24, height: 24)
            v.iconImageView.image = UIImage.icon32Diamond
            v.contentLabel.textColor = .text
            v.contentLabel.font = .t.tndm
            stackV.addArrangedSubview(v)
            return v
        }()
        
        priceLabel = {
            let v = CLLabel()
            v.textColor = .c.ctsn
            v.font = .t.tnms
            stackV.addArrangedSubview(v)
            return v
        }()
        
        testData()
    }
    
    private func testData(){
        let coin = Coin(cents: 530)
        iconAndLabel.contentLabel.text = coin.formatted
        
        priceLabel.text = "$4.99"
    }

    // MARK: - Public
    
    func config(_ data: IAPProducts?){
        self.data = data
        guard let tier = data, let chargeAmount = tier.chargeAmount, let payAmount = tier.payAmount else{
            return
        }
        
        let coin = Coin(cents: chargeAmount)
        iconAndLabel.contentLabel.text = coin.formatted
        
        if let currencySymbol = tier.currencySymbol{
            let coin = Coin(usd: payAmount)
            priceLabel.text = "\(currencySymbol)\(coin.formatted)"
//            priceLabel.text = "\(currencySymbol)\(payAmount)"
        }else{
            let usd = Coin(usd: payAmount*0.01)
            priceLabel.text = "$\(usd.formatted)"
        }
        
    }

    func setupSelected(selected: Bool){
        block.layer.borderWidth = selected ? 2 : 0
        block.layer.borderColor = selected ? UIColor.c.cpn.cgColor : UIColor.clear.cgColor
    }


}
