//
//  OrderTypeChipView.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 订单类型标签 chip。
final class OrderTypeChipView: UIView {

    private enum Metrics {
        static let contentInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
    }

    private let pillView = UIView()
    private let label = UILabel()

    override var intrinsicContentSize: CGSize {
        let labelSize = label.intrinsicContentSize
        return CGSize(
            width: labelSize.width + Metrics.contentInsets.left + Metrics.contentInsets.right,
            height: labelSize.height + Metrics.contentInsets.top + Metrics.contentInsets.bottom
        )
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        setContentHuggingPriority(.required, for: .horizontal)
        setContentHuggingPriority(.required, for: .vertical)

        pillView.backgroundColor = OrderTokens.chipBackground
        pillView.layer.cornerRadius = OrderTokens.pillRadius
        pillView.clipsToBounds = true

        label.font = .app(.caption)
        label.textColor = AppColor.primary
        label.lineBreakMode = .byTruncatingTail
        label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        addSubview(pillView)
        pillView.addSubview(label)
        pillView.snp.makeConstraints { make in
            make.top.bottom.leading.equalToSuperview()
            make.trailing.lessThanOrEqualToSuperview()
        }
        label.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(Metrics.contentInsets)
        }
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func apply(text: String) {
        label.text = text
        isHidden = text.isEmpty
        invalidateIntrinsicContentSize()
    }
}
