//
//  NewGuideViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/28.
//

import UIKit

class NewGuideViewController: UIViewController {

   
    @IBOutlet weak var privacyL: UILabel!
    @IBOutlet weak var dotImage: UIImageView!
    @IBOutlet weak var collectionView: UICollectionView!
    var timer: Timer?
    
    @IBOutlet weak var startBtn: UIButton!
    
    @IBOutlet weak var termsL: UILabel!
    let dots = ["icon_guide_one","icon_guide_two","icon_guide_three"]
    
    var index = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.transitioningDelegate = self
        configUI()
        startTimer()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 禁用滑动返回手势
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 恢复滑动返回手势，避免影响其他视图控制器
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    func configUI(){
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        collectionView.setCollectionViewLayout(layout, animated: false)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isScrollEnabled = false
        collectionView.backgroundColor = .white
        collectionView.isPagingEnabled = true // 启用分页
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UINib.init(nibName: "NewGuideOneCell", bundle: nil), forCellWithReuseIdentifier: "NewGuideOneCell")
        collectionView.register(UINib.init(nibName: "NewGuideTwoCell", bundle: nil), forCellWithReuseIdentifier: "NewGuideTwoCell")
        collectionView.register(UINib.init(nibName: "NewGuideThreeCell", bundle: nil), forCellWithReuseIdentifier: "NewGuideThreeCell")
        
        
        privacyL.addUnderline()
        termsL.addUnderline()
        
        let onetap = UITapGestureRecognizer(target: self, action: #selector(pricyClick))
        privacyL.isUserInteractionEnabled = true
        privacyL.addGestureRecognizer(onetap)
        
        let twotap = UITapGestureRecognizer(target: self, action: #selector(termClick))
        termsL.isUserInteractionEnabled = true
        termsL.addGestureRecognizer(twotap)
    }
    
    @IBAction func nextClick(_ sender: Any) {
        if index < 2{
            index += 1
            collectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: true)
        }else{
            enterHome()
        }
        
        dotImage.image = UIImage.init(named: dots[index])
    }
    
  @objc func pricyClick(){
        let vc:PrivacyPolicyWebViewController = PrivacyPolicyWebViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc  func termClick(){
        let vc:TermOfUseWebViewController = TermOfUseWebViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func enterHome(){
//        let vc:HomeViewController = HomeViewController()
//        
//        let nav = BaseNavViewController(rootViewController: vc)
//        
//        cWindow?.rootViewController = nav
//        
//        let transition = CATransition()
//        transition.duration = 0.5
//        transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
//
//        // 添加动画到 window 的 layer
//        cWindow?.layer.add(transition, forKey: kCATransition)
//
//        // 显示 window
//        cWindow?.makeKeyAndVisible()
        
        
        self.navigationController?.popToRootViewController(animated: false)
        UserDef.shard.isShowLanding = true
        UserDef.shard.saveUserDefToSandBox()
        NotificationCenter.default.post(name: .guidePageClose, object: nil)
    }
    
    deinit{
        timer?.invalidate()
    }
    
    func startTimer() {
         // 创建定时器，每隔 3 秒调用一次
         timer = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(advanceToNextItem), userInfo: nil, repeats: true)
     }
    
     @objc func advanceToNextItem() {
         if index < 2{
             index += 1
             collectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: true)
         }else{
             timer?.invalidate()
         }
         dotImage.image = UIImage.init(named: dots[index])
     }
}

extension NewGuideViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dots.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.row == 0{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewGuideOneCell", for: indexPath) as! NewGuideOneCell
            return cell
        }
        if indexPath.row == 1{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewGuideTwoCell", for: indexPath) as! NewGuideTwoCell
            return cell
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewGuideThreeCell", for: indexPath) as! NewGuideThreeCell
        return cell
    }
    
    // MARK: - UICollectionViewDelegateFlowLayout
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.bounds.size // 让单元格大小与 UICollectionView 的大小一致
    }

}

extension NewGuideViewController: UIViewControllerTransitioningDelegate {
    func animationController(forDismissed dismissedController: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // pop 时触发消失动画（等同于 popToRootViewController）
        return FadeOutPopTransition()
    }
}
