//
//  RolesRootPageView.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/14.
//

import JXPagingView
import JXSegmentedView
import UIKit
import Combine

class RolesRootPageView: CLContainer {
    
    let itemWidth: CGFloat = (UIScreen.width - 30.0) / 2.0
    var jumpPublisher: AnyPublisher<JumpTarget, Never> { topView.jumpPublisher }
    
//    private lazy var pagingView = JXPagingListRefreshView(delegate: self)
//    lazy var headerView:


    let data: [String] = [
        "Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy, Lin Feng had his cultivation shattered and was cast",
        "Once a prodigy, Lin Feng had his cultivation",
        "Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy",
        "Once a prodigy",
        "Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy, Lin Feng had his cultivation shattered and was cast Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy, Lin Feng had his cultivation shattered and was cast",
        "Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy",
        "Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy",
        "Once a prodigy",
        "Once a prodigy, Lin Feng had his cultivation shattered and was cast out Once a prodigy, Lin Feng had his cultivation shattered and was cast",
        "Once a prodigy"
    ]
    
    let remind: [String] = [
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]",
        "[The Lsat Oracle of Kael]"
    ]
    
    lazy var topView: CLTopHeaderView = {
        let view = CLTopHeaderView()
        return view
    }()
    
    lazy var tagsView: CLRoleTagsView = {
        let tagsView = CLRoleTagsView()
        return tagsView
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = CLWaterfallLayout()
        layout.columnCount = 2
        layout.delegate = self
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(CLRoleCollectionCell.self, forCellWithReuseIdentifier: "CLRoleCollectionCell")
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
        setupDatas()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        addSubview(self.topView)
//        addSubview(tagsChooseView)
        addSubview(tagsView)
        addSubview(collectionView)
        
        topView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(UIDevice().navHeight)
        }
        
        tagsView.snp.makeConstraints { make in
            make.right.left.equalToSuperview()
            make.top.equalTo(topView.snp.bottom).offset(0)
        }
        
        collectionView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(tagsView.snp.bottom).offset(0)
        }
    }
    
    private func setupDatas() {
        
    }
}

extension RolesRootPageView: UICollectionViewDelegate, UICollectionViewDataSource, WaterfallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: CLRoleCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CLRoleCollectionCell", for: indexPath) as! CLRoleCollectionCell
        
        cell.setupData(desc: data[indexPath.item])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let sessionId = "439217670979585@r@t"
        AppRouter.goChatVC(conversationId: sessionId, title: "Character · 18", complete: nil)
    }
    
    func collectionView(_ collectionView: UICollectionView,
                            layout: CLWaterfallLayout,
                            heightForItemAt indexPath: IndexPath) -> CGFloat {
        let model = data[indexPath.item]

        let coverH = itemWidth * (4.0 / 3.0)
        // 文字高度
        let maxLines = 3
        let font = UIFont.systemFont(ofSize: 12)
        let lineHeight = font.lineHeight        // 15 pt 字体 ≈ 17.4 pt
        let maxHeight = lineHeight * CGFloat(maxLines)

        // 真实文本高度（不会超过 maxHeight）
        let textSize = model.boundingRect(
            with: CGSize(width: itemWidth - 20, height: maxHeight), // 高度封顶
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: [.font: font],
            context: nil).size

        // 取最小值，保证不足 3 行时按实际算，超过 3 行时截断在 3 行高
        let textH = min(textSize.height, maxHeight)
        
        let remindH = remind[indexPath.item].boundingRect(
            with: CGSize(width: itemWidth - 20.0, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [.font: UIFont.boldSystemFont(ofSize: 10)],
            context: nil).height
        
        return coverH + 10.0 + textH + 5.0 + remindH
    }
}

//extension RolesRootPageView: JXPagingViewDelegate {
//    func tableHeaderViewHeight(in _: JXPagingView) -> Int {
//        return 100
//    }
//
//    func tableHeaderView(in _: JXPagingView) -> UIView {
//        return headerView
//    }
//
//    func heightForPinSectionHeader(in _: JXPagingView) -> Int {
//        return headerPinHeadHeight
//    }
//
//    func viewForPinSectionHeader(in _: JXPagingView) -> UIView {
//        return pinHeaderView
//    }
//
//    func numberOfLists(in _: JXPagingView) -> Int {
//        return controllers.count
//    }
//
//    func pagingView(_: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
//        let vc = controllers[index]
//        return vc
//    }
//
//    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
//        if segmentedView == pinHeaderView.segmentedView {
//            refreshSubTagsSegmentView()
//        }
////        else if segmentedView == pinHeaderView.subSegementedView {
////            let selectTag = tagsNodes[index]
////            if let currentVc = controllers[pinHeaderView.segmentedView.selectedIndex] as? DiscoverRolesGridController {
////                currentVc.tryLoad(code: selectTag.code!)
////            }
////        }
//    }
//
//    func mainTableViewDidScroll(_ scrollView: UIScrollView) {
//        NaviAlphaHandle.changeNaviViewsAlpha(scrollView: scrollView, alphaViews: [bgBdView, navigationView?.bgView], oppositeViews: [])
//    }
//}

//extension DiscoverRootPageView: JXPagingMainTableViewGestureDelegate {
//    func mainTableViewGestureRecognizer(
//        _ gestureRecognizer: UIGestureRecognizer,
//        shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
//        // 如果是 UICollectionView 的手势，先判断滚动方向
//        if let panGesture = otherGestureRecognizer as? UIPanGestureRecognizer,
//           let otherView = otherGestureRecognizer.view,
//           otherView is UICollectionView {
//            let velocity = panGesture.velocity(in: otherView)
//            // 横向滚动时禁止
//            if abs(velocity.x) > abs(velocity.y) {
//                return false
//            }
//        }
//        // 禁止segmentedView左右滑动的时候，上下和左右都可以滚动
////        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
////            return false
////        }
//        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
//            && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
//    }
//}
