//
//  StatisticsPeriodButton.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 数据统计周期 pill 按钮，对齐 Android `PeriodButton`。
final class StatisticsPeriodButton: UIButton {

    /// 按钮圆角策略，支持随高度变化的胶囊形与固定圆角。
    enum CornerStyle: Equatable {
        case capsule
        case fixed(CGFloat)
    }

    var periodTitle: String = "" {
        didSet { setTitle(periodTitle, for: .normal) }
    }

    /// 当前圆角策略，默认使用高度一半的胶囊形。
    var cornerStyle: CornerStyle = .capsule {
        didSet { setNeedsLayout() }
    }

    override var isSelected: Bool {
        didSet { updateAppearance() }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        switch cornerStyle {
        case .capsule:
            layer.cornerRadius = bounds.height / 2
        case .fixed(let radius):
            layer.cornerRadius = max(0, radius)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

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

    private func setupUI() {
        titleLabel?.font = .app(.bodyMedium)
        layer.cornerCurve = .continuous
        clipsToBounds = true
        setConfigurationContentInsets(
            NSDirectionalEdgeInsets(top: 6, leading: 20, bottom: 6, trailing: 20)
        )
        updateAppearance()
    }

    private func updateAppearance() {
        backgroundColor = isSelected ? AppColor.primary : AppColor.inputBackground
        setTitleColor(isSelected ? .white : AppColor.textSecondary, for: .normal)
        titleLabel?.font = .systemFont(ofSize: 14, weight: isSelected ? .semibold : .medium)
    }
}
