//
//  VerticalLoopScrollLabel.swift
//  OrderScheduling
//
//  Created by 中道 on 2025/7/28.
//

import UIKit

/// 可点击的纵向轮播标签控件，支持点击获取当前 index
class VerticalLoopScrollLabel: UIView {
    private let scrollView = UIScrollView()
    private let label1 = UILabel()
    private let label2 = UILabel()
    private var timer: Timer?
    
    /// 点击回调，返回当前索引
    var onTap: ((Int) -> Void)?
    
    var items: [String] = [] {
        didSet {
            guard !items.isEmpty else { return }
            currentIdx = 0
            label1.text = items.first
            label2.text = items.count > 1 ? items[1] : items.first
            setNeedsLayout()
            startLoop()
        }
    }
    
    var interval: TimeInterval = 2.5
    private var currentIdx = 0
    private var isLabel1OnTop = true
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        clipsToBounds = true
        scrollView.isScrollEnabled = false
        addSubview(scrollView)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        addGestureRecognizer(tap)
        
        for label in [label1, label2] {
            label.font = .systemFont(ofSize: 16, weight: .semibold)
            label.textColor = .white
            label.textAlignment = .left
            label.numberOfLines = 1
            label.lineBreakMode = .byTruncatingTail
            scrollView.addSubview(label)
        }
    }
    required init?(coder: NSCoder) { fatalError() }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        scrollView.frame = bounds
        label1.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
        label2.frame = CGRect(x: 0, y: bounds.height, width: bounds.width, height: bounds.height)
        scrollView.contentSize = CGSize(width: bounds.width, height: bounds.height * 2)
    }
    
    private func startLoop() {
        timer?.invalidate()
        guard items.count > 1 else { return }
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: { [weak self] _ in
            self?.scrollNext()
        })
    }
    
    private func scrollNext() {
        let fromLabel = isLabel1OnTop ? label1 : label2
        let toLabel = isLabel1OnTop ? label2 : label1
        let nextIdx = (currentIdx + 1) % items.count
        toLabel.text = items[nextIdx]
        // 动画向上滚动
        UIView.animate(withDuration: 0.35, animations: {
            self.scrollView.contentOffset = CGPoint(x: 0, y: self.bounds.height)
        }, completion: { _ in
            // 滚动完后交换内容和位置
            self.scrollView.contentOffset = .zero
            fromLabel.text = toLabel.text
            self.currentIdx = nextIdx
            self.isLabel1OnTop.toggle()
        })
    }
    
    @objc private func handleTap() {
        onTap?(currentIdx)
    }
    
    deinit { timer?.invalidate() }
}
