//
//  PageIndicatorView.swift

//
//  Created by Leon on 2025/9/12.
//

import UIKit

class PageIndicatorView: UIView {
    
    private let topIndicator: UIView
    private let bottomIndicator: UIView
    
    override init(frame: CGRect) {
        topIndicator = UIView()
        bottomIndicator = UIView()
        
        super.init(frame: frame)
        
        // 设置指示器容器的大小
        self.frame = CGRect(x: 0, y: 0, width: 4, height: 60)
        self.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 4, height: 60))
        }
        
        cornerRadius = 2
        backgroundColor = CLGlobalToken.color(token: .glo_color_white)!.withAlphaComponent(0.3)
        
        // 配置顶部部分
        topIndicator.backgroundColor = CLSystemToken.color(token: .cswn)//.white
        topIndicator.cornerRadius = 2
//        topIndicator.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        addSubview(topIndicator)
        
        // 配置底部部分
        bottomIndicator.backgroundColor = CLSystemToken.color(token: .cswn)
        bottomIndicator.cornerRadius = 2
        bottomIndicator.isHidden = true
        addSubview(bottomIndicator)
        
        // 初始设置布局为均分
        topIndicator.frame = CGRect(x: 0, y: 0, width: 4, height: 30)
        bottomIndicator.frame = CGRect(x: 0, y: 30, width: 4, height: 30)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 更新指示器的比例，传入一个进度值 (0.0 到 1.0)
    func updateIndicator(progress: CGFloat) {
        // 限制进度值范围
        let clampedProgress = max(0, min(progress, 1))
        
        // 计算顶部和底部的高度
        let topHeight = clampedProgress * 60
        let bottomHeight = 60 - topHeight
        
        // 更新顶部和底部部分的高度
        topIndicator.frame = CGRect(x: 0, y: 0, width: 4, height: topHeight)
        bottomIndicator.frame = CGRect(x: 0, y: topHeight, width: 4, height: bottomHeight)
        
        // 根据进度更新颜色
        if clampedProgress <= 0.5 {
            topIndicator.isHidden = false
            bottomIndicator.isHidden = true
            // 页面在上半部分：上面白色，下面灰色
//            topIndicator.backgroundColor = .white
//            bottomIndicator.backgroundColor = .gray
        } else {
            topIndicator.isHidden = true
            bottomIndicator.isHidden = false
            // 页面在下半部分：上面灰色，下面白色
//            topIndicator.backgroundColor = .gray
//            bottomIndicator.backgroundColor = .white
        }
    }
    
    func updateIndicator(top:Bool){
        updateIndicator(progress: top ? 0.501 : 0.499)
    }
}

