//
//  EmailKeywordCollectionCell.swift
//  PhoneManager
//
//  Created by edy on 2025/5/12.
//

import UIKit

class EmailKeywordCollectionCell: UICollectionViewCell {
    
    static let id = "EmailKeywordCollectionCell"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setuup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setuup() -> Void {
        content.snp.makeConstraints { make in
            make.left.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(5)
            make.right.equalTo(titleL.snp.right).offset(12)
        }
        titleL.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(12)
            make.top.equalToSuperview().offset(17)
            make.bottom.equalToSuperview().inset(10)
        }
        icon.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(3)
            make.top.equalToSuperview()
        }
        DispatchQueue.main.async {
            self.content.layer.borderColor = UIColor.colorWithHex(hexStr: "#B3B3B3").cgColor
            self.content.layer.borderWidth = 0.5
            self.content.layer.cornerRadius = 8
            self.content.clipsToBounds = true
        }
    }
    
    private lazy var content: UIView = {
        let c = UIView()
        c.backgroundColor = .clear
        contentView.addSubview(c)
        return c
    }()
    
    private lazy var icon: UIImageView = {
        let v = UIImageView(image: UIImage(named: "icon_email_close"))
        v.contentMode = .scaleAspectFill
        contentView.addSubview(v)
        return v
    }()
    
    lazy var titleL: UILabel = {
        let l = UILabel()
        contentView.addSubview(l)
        l.font = UIFont.boldSystemFont(ofSize: 14)
        l.textAlignment = .center
        l.textColor = UIColor.colorWithHex(hexStr: "#333333")
        return l
    }()
    
    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        let attributes = super.preferredLayoutAttributesFitting(layoutAttributes)
        let strs:NSString = self.titleL.text as? NSString ?? ""
        let frame = strs.boundingRect(with: CGSizeMake(ScreenW-15*2-29.0, .infinity), attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)], context: nil)
        let width = max(40, min(CGRectGetWidth(frame), ScreenW-15*2-29.0)) + 24.0
        attributes.frame.size = contentView.systemLayoutSizeFitting(
            CGSize(width: width, height: UIView.layoutFittingCompressedSize.height),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: .fittingSizeLevel
        )
        return attributes
    }
    
}
