//
//  YHPageControl.swift
//  galaxy
//
//  Created by Dufet on 2024/12/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHPageControl: UIView {
    
    // MARK: - Properties
    private var dots: [UIView] = []
    var dotSize: CGSize = CGSize(width: 40, height: 8) // 普通点的大小
    var selectedDotSize: CGSize = CGSize(width: 60, height: 8) // 选中点的大小
    var spacing: CGFloat = 8 // 点之间的间距
    
    // 当前页码
    var currentPage: Int = 0 {
        didSet {
            guard oldValue != currentPage else { return }
            updateDots(animated: true)
        }
    }
    
    // 总页数
    var numberOfPages: Int = 0 {
        didSet {
            guard oldValue != numberOfPages else { return }
            setupDots()
        }
    }
    
    // 自定义颜色
    var dotColor: UIColor = UIColor.lightGray {
        didSet {
            dots.forEach { $0.backgroundColor = dotColor }
            dots[safe: currentPage]?.backgroundColor = selectedDotColor
        }
    }
    
    var selectedDotColor: UIColor = UIColor.systemBlue {
        didSet {
            dots[safe: currentPage]?.backgroundColor = selectedDotColor
        }
    }
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    // MARK: - Setup
    private func setupView() {
        backgroundColor = .clear
    }
    
    private func setupDots() {
        // 移除现有的点
        dots.forEach { $0.removeFromSuperview() }
        dots.removeAll()
        
        // 创建新的点
        for _ in 0..<numberOfPages {
            let dot = UIView()
            dot.backgroundColor = dotColor
            dot.layer.shadowOffset = .zero
            addSubview(dot)
            dots.append(dot)
        }
        
        // 更新布局
        setNeedsLayout()
        updateDots(animated: false)
    }
    
    // MARK: - Layout
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let totalWidth = CGFloat(numberOfPages - 1) * (dotSize.width + spacing) + selectedDotSize.width
        var xOffset = (bounds.width - totalWidth) / 2
        
        for (index, dot) in dots.enumerated() {
            let isSelected = index == currentPage
            let width = isSelected ? selectedDotSize.width : dotSize.width
            dot.frame = CGRect(x: xOffset,
                             y: (bounds.height - dotSize.height) / 2,
                             width: width,
                             height: dotSize.height)
            dot.layer.cornerRadius = self.dotSize.height / 2
            dot.clipsToBounds = true
            xOffset += width + spacing
        }
    }
    
    // MARK: - Updates
    private func updateDots(animated: Bool) {
        guard !dots.isEmpty else { return }
        
        let update = {
            self.dots.enumerated().forEach { index, dot in
                let isSelected = index == self.currentPage
                dot.backgroundColor = isSelected ? self.selectedDotColor : self.dotColor
                
                let width = isSelected ? self.selectedDotSize.width : self.dotSize.width
                var frame = dot.frame
                frame.size.width = width
                dot.layer.cornerRadius = self.dotSize.height / 2
                dot.clipsToBounds = true
                dot.frame = frame
            }
            self.layoutSubviews()
        }
        
        if animated {
            UIView.animate(withDuration: 0.3,
                         delay: 0,
                         usingSpringWithDamping: 0.7,
                         initialSpringVelocity: 0.5,
                         options: [.curveEaseInOut],
                         animations: update)
        } else {
            update()
        }
    }
}

// MARK: - Safe Array Access
private extension Array {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

