//
//  LandingVC.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/19.
//

import UIKit

class LandingVC:UIViewController {
    
    @IBOutlet weak var titleBackView: UIView!
    @IBOutlet weak var bottomTextView: UITextView!
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var bottomView: UIView!
    
    private var currentIndex:Int = 0
    
    private var collectionView: UICollectionView?
    
    private var titleAnimationView:LandingTitleAnimationView?
    
    private var models:[LandingCollectionModel] = []
    
    private var isPPClick:Bool = false
    
    private var isTOUClick:Bool = false
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setDefault()
        
        configureGradientView()
        
        setupUI()
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        isPPClick = false
        
        isTOUClick = false
    }
    
    private func setDefault() {
        
        models = loadLandingSONFromBundle() ?? []
    }
    
    private func setupUI() {
        
        titleAnimationView = LandingTitleAnimationView(frame: titleBackView.bounds, count: models.count, spacing: 12)
        titleBackView.addSubview(titleAnimationView ?? UIView())
        
        titleAnimationView?.startWithIndex(index: currentIndex)
        
        titleAnimationView?.callBack = {[weak self] index in
            
            guard let self else {return}
            
            let nextIndex = (index as? Int ?? 0) + 1
            
            if (isPPClick || isTOUClick) {
                
                
            }else {
                
             //   changeCurrentIndex(index: nextIndex)
            }
            
        }
        
        bottomTextView.isEditable = false
        bottomTextView.isScrollEnabled = false
        bottomTextView.backgroundColor = .clear
        
        bottomTextView.delegate = self
        
        let fullText = "Privacy Policy and Terms of Use"
        let termsText = "Terms of Use"
        let privacyText = "Privacy Policy"
        
        let attributedString2 = NSMutableAttributedString(string: fullText, attributes: [
            .font: UIFont.systemFont(ofSize: 14),
            .foregroundColor: UIColor.colorWithHex(hexStr: "#666666")
        ])
        
        let termsRange = (fullText as NSString).range(of: termsText)
        let privacyRange = (fullText as NSString).range(of: privacyText)
        
        attributedString2.addAttributes([
            .underlineStyle: NSUnderlineStyle.single.rawValue,
            .link:"terms://termsOfUse"
        ], range: termsRange)
        
        attributedString2.addAttributes([
            .underlineStyle: NSUnderlineStyle.single.rawValue,
            .link: "privacy://privacyPolicy"
        ], range: privacyRange)
        
        bottomTextView.gestureRecognizers?.forEach { gestureRecognizer in
            if gestureRecognizer is UILongPressGestureRecognizer {
                // 移除长按手势
                bottomTextView.removeGestureRecognizer(gestureRecognizer)
            }
        }
        
        bottomTextView.gestureRecognizers?.forEach { gestureRecognizer in
            if gestureRecognizer is UILongPressGestureRecognizer {
                // 禁用长按和双击手势
                gestureRecognizer.isEnabled = false
            }
            
            if let tapGesture = gestureRecognizer as? UITapGestureRecognizer {
                // 判断是否是双击手势
                if tapGesture.numberOfTapsRequired == 2 {
                    tapGesture.isEnabled = false // 禁用双击手势
                }
            }
        }
        bottomTextView.attributedText = attributedString2
        bottomTextView.textAlignment = .center
        bottomTextView.linkTextAttributes = [:]  // 取消默认 link 颜
        
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        
        
        let cW:CGFloat = view.width
        let cY:CGFloat = titleBackView.y + titleBackView.height
        let cH:CGFloat = bottomView.y - cY
        
        let flowlayout:UICollectionViewFlowLayout =  UICollectionViewFlowLayout()
        flowlayout.scrollDirection = .horizontal
        flowlayout.itemSize = CGSizeMake(cW, cH)
        flowlayout.minimumLineSpacing = 0
        
        collectionView = UICollectionView.init(frame: CGRectMake(0, cY , cW , cH), collectionViewLayout: flowlayout)
        collectionView?.backgroundColor = .clear
        
        collectionView?.decelerationRate = UIScrollView.DecelerationRate.fast;
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.isPagingEnabled = true
        collectionView?.isUserInteractionEnabled = false
        
        let nib = UINib(nibName: "LandingCollectionCell", bundle: nil)
        collectionView?.register(nib, forCellWithReuseIdentifier: LandingCollectionCell.identifiers)
        // 设置 UICollectionView 的数据源和代理
        collectionView?.dataSource = self
        collectionView?.delegate = self
        
        view.addSubview(collectionView!)
        
    }
    
    func findCell(at indexPath: IndexPath) -> LandingCollectionCell? {
        return collectionView?.cellForItem(at: indexPath) as? LandingCollectionCell ?? nil
    }
    
    private func configureGradientView() {
        // 创建 CAGradientLayer
        let gradientLayer = CAGradientLayer()
        
        // 设置渐变的颜色
        gradientLayer.colors = [
            UIColor.colorWithHex(hexStr: "#FFFFFF").cgColor, // 白色
            UIColor.colorWithHex(hexStr: "#E4EDFD").cgColor  // 浅蓝色
        ]
        
        // 设置渐变方向（从上到下）
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0) // 顶部
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)   // 底部
        
        // 设置渐变图层的大小
        gradientLayer.frame = view.bounds
        
        // 将渐变图层添加到视图中
        view.layer.insertSublayer(gradientLayer, at: 0)
    }
    
    @IBAction func nextClick(_ sender: UIButton) {
        
        changeCurrentIndex(index: currentIndex + 1)
        
        sender.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
    }
    
    private func changeCurrentIndex(index:Int) {
        
        if (index < models.count) {
            
            currentIndex = index
            
            let indexPath = IndexPath(item: index, section: 0)
            
            DispatchQueue.main.async {[weak self] in
                
                guard let self else {return}
                
                titleAnimationView?.startWithIndex(index: index)
                
                collectionView?.scrollToItem(at: indexPath , at: UICollectionView.ScrollPosition.left, animated: true)
                findCell(at: indexPath)?.playAnimation()
                
                if (index == models.count - 1) {
                    
                    nextButton.setTitle("Get started", for: .normal)
                }else {
                    
                    nextButton.setTitle("Next", for: .normal)
                }
                
            }
            
            
        }else {
            
            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()
            
            UserDef.shard.isShowLanding = true
            UserDef.shard.saveUserDefToSandBox()
        }
    }
    
    private func ppClick() {
        
        if (!isPPClick) {
            
            isPPClick = true
            
            DispatchQueue.main.async {[weak self] in
                
                guard let self else {return}
                
                let vc:PrivacyPolicyWebViewController = PrivacyPolicyWebViewController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        
    }
    
    private func touClick() {
        
        if (!isTOUClick) {
            
            isTOUClick = true
            
            DispatchQueue.main.async {[weak self] in
                
                guard let self else {return}
                
                let vc:TermOfUseWebViewController = TermOfUseWebViewController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
    }
}

extension LandingVC:UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.scheme == "terms" {
            touClick()
            // 处理 Terms of Use 点击事件
            return false // 阻止默认行为（打开链接）
        } else if URL.scheme == "privacy" {
            ppClick()
            // 处理 Privacy Policy 点击事件
            return false // 阻止默认行为（打开链接）
        }
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // 禁用所有菜单选项
        return false
    }
}

extension LandingVC:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return models.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LandingCollectionCell.identifiers, for: indexPath) as! LandingCollectionCell
        
        
        if (indexPath.row < models.count) {
            
            cell.model = models[indexPath.row]
        }
        
        return cell
    }
    
    
    
}
