//
//  SpeakSegmentTool.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/22.
//

import UIKit

class SpeakSegmentTool: UIView {

    var item:[String] = [] {
        didSet {
            reloadUI()
        }
    }
    
    var selectIdx = 0
    
    init( item:[String]) {
        super.init(frame: CGRect())
        self.item = item
        makeUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
    }
    
    private lazy var stack: UIStackView = {
        let stack = UIStackView()
        stack.spacing = 4
        stack.axis = .horizontal
        stack.alignment = .fill
        stack.distribution = .fillEqually
        addSubview(stack)
        return stack
    }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutIfNeeded()
        stack.arrangedSubviews.forEach({$0.corners = $0.height/2.0})
    }
    
}

extension SpeakSegmentTool {
    
    @objc private func SegmentTap(_ sender:UIButton) -> Void {
        if selectIdx != sender.tag {
            selectIdx = sender.tag
            stack.arrangedSubviews.forEach { btn in
                guard let btn:UIButton = btn as? UIButton else { return }
                btn.setTitleColor( btn.tag == selectIdx ? .black : .init(hex: 0x000000,alpha: 0.4), for: .normal)
                btn.backgroundColor = btn.tag == selectIdx ? .white : .clear
            }
            guard let call = callblack else { return }
            call(selectIdx)
        }
    }
    
    private func makeUI() -> Void {
        stack.snp.makeConstraints { make in
            make.left.top.bottom.right.equalToSuperview()
        }
    }
    
    private func reloadUI() -> Void {
        stack.arrangedSubviews.forEach({$0.removeFromSuperview()})
        for (i,title) in item.enumerated() {
            let btn = UIButton(type: .custom)
            btn.setTitle(title, for: .normal)
            btn.tag = i
            btn.setTitleColor( i == selectIdx ? .black : .init(hex: 0x000000,alpha: 0.4), for: .normal)
            btn.titleLabel?.font = UIFont.montserrat(.semiBold,size: 16)
            btn.backgroundColor = i == selectIdx ? .white : .clear
            btn.addTarget(self, action: #selector(SegmentTap(_:)), for: .touchUpInside)
            stack.addArrangedSubview(btn)
        }
    }
    
}
