//
//  DiscoverRootPageController.swift

//
//  Created by Leon on 2025/7/22.
//

import UIKit
import Combine
class DiscoverRootPageController: CLTabRootController<DiscoverRootPageView> {
    
    @Published var filterModel = RolesFilterModel()
    private var cancellables = Set<AnyCancellable>()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let baseImageView = UIImageView(image: R.image.base_bg())
        baseImageView.contentMode = .scaleAspectFill
        self.view.insertSubview(baseImageView, at: 0)
        baseImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        setupViews()
        setupDatas()
        setupEvents()
        
        
    }

    private func setupViews() {
        navigationView.bgView.alpha = 0
        navigationView.setupBgViewToStatusBarHeight()
        navigationView.isUserInteractionEnabled = false
    }

    private func setupDatas() {
        loadDiscoverInfo()
    }

    private func loadDiscoverInfo() {
        DiscoverProvider.request(.discoverInfo, modelType: DiscoverHomeInfo.self) { [weak self] result in
            switch result {
            case let .success(model):
//                dlog(model)
                self?.container.headerView.leaderboardEntryView.config(model)
            case .failure:
                break
            }
        }
    }

    private func setupEvents() {
        container.pinHeaderView.filterButton.addTarget(self, action: #selector(tapFilterButton(button:)), for: .touchUpInside)
        container.headerView.banner.topButton.addTarget(self, action: #selector(tapBannerAd), for: .touchUpInside)
        
        $filterModel.sink {[weak self] model in
            self?.container.pinHeaderView.setupFilterCount(model.filterCount())
        }.store(in: &cancellables)
    }

    // MARK: Action

    @objc private func tapFilterButton(button: UIButton) {
        let vc = RolesFilterController()
        vc.filterType = .discover
        vc.rolesFilterModel = filterModel
        presentNaviRootVc(vc: vc)
        vc.completion = {[weak self] model in
            self?.filterModel = model
            // dlog("完成fitler选择:\(model)")
            self?.container.setupFilter(filter: model)
        }
    }

    @objc private func tapBannerAd() {
        guard UserCore.shared.checkUserLoginIfNotPushUserToLogin() else{
            return
        }
        let vc = DailyFreeCoinCheckController()
        navigationController?.pushViewController(vc, animated: true)
    }
}
