//
//  IMGiftGridCell.swift

//
//  Created by Leon on 2025/8/17.
//

import UIKit

class IMGiftGridCell: UICollectionViewCell {
    var block: UIView!
    var icon: UIImageView!
    var itemLabel: CLLabel!
    var coinLabel: CLIconLabel!

    var data: GiftDictModel?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews() {
        block = {
            let v = UIView()
            contentView.addSubview(v)
            v.cornerRadius = 16
            v.layer.borderColor = UIColor.c.cpn.cgColor
            v.layer.borderWidth = 0
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 88, height: 88))
                make.centerX.equalToSuperview()
                make.height.equalTo(v.snp.width)
                make.top.equalToSuperview()
            }
            return v
        }()

        icon = {
            let v = UIImageView()
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalToSuperview()
                make.size.equalTo(CGSize(width: 64, height: 64))
            }
            return v
        }()

        itemLabel = {
            let v = CLLabel()
            v.textAlignment = .center
            v.font = .t.tls
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.top.equalTo(block.snp.bottom).offset(4)
            }
            return v
        }()

        coinLabel = {
            let v = CLIconLabel()
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(itemLabel.snp.bottom).offset(4)
            }
            return v
        }()
    }

    private func setupData() {
        coinLabel.iconImageView.image = UIImage(named: "icon_16_diamond")
        coinLabel.contentLabel.text = "10"
        itemLabel.text = "Friends"
    }

    private func setupEvent() {
    }

    func config(_ data: GiftDictModel) {
        self.data = data
        
        itemLabel.text = data.name
        icon.loadImage(data.icon, bgColor: UIColor.clear)

        let price = data.price ?? 0
        let coin = Double(price) * 0.01
        coinLabel.contentLabel.text = String.thousandString(float: coin, maxDigits: 2)
    }

    func setupSelected(selectedId: Int?) {
        guard let id = selectedId, let dataId = data?.id else {
            block.layer.borderWidth = 0
            return
        }
        block.layer.borderWidth = id == dataId ? 2 : 0
    }
}
