//
//  LNHomeGameMatePanel.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/17.
//

import Foundation
import UIKit
import SnapKit


class LNHomeGameMatePanel: UIView {
    private var curItem: LNGameTypeItemVO?
    private let listView = LNGameMateListView()
    
    func prepareFor(_ item: LNGameTypeItemVO) {
        setupViews(item)
        curItem = item
    }
    
    func onShow() {
        listView.reportExposure()
    }
}

extension LNHomeGameMatePanel: LNHomeGameTabViewDelegate {
    func homeGameTabView(view: LNHomeGameTabView, didSelect category: LNGameCategoryItemVO?) {
        guard let curItem else { return }
        listView.reloadList(newTopCategory: curItem.code, newCategory: category?.code, filter: LNGameMateFilter())
    }
    
    func homeGameTabViewClickMore(view: LNHomeGameTabView) {
        pushToGameCategoryList { [weak self] category, game in
            guard let self else { return }
            pushToGameMateList(topCategory: category, category: game, filter: LNGameMateFilter())
        }
    }
}

extension LNHomeGameMatePanel: LNHomeActivityTabViewDelegate {
    func homeActivityTabView(view: LNHomeActivityTabView, didSelect category: LNGameCategoryItemVO?) {
        guard let curItem else { return }
        listView.reloadList(newTopCategory: curItem.code, newCategory: category?.code, filter: LNGameMateFilter())
    }
    
    func homeActivityTabViewClickMore(view: LNHomeActivityTabView) {
        pushToGameCategoryList { [weak self] category, game in
            guard let self else { return }
            pushToGameMateList(topCategory: category, category: game, filter: LNGameMateFilter())
        }
    }
}

extension LNHomeGameMatePanel {
    private func setupViews(_ item: LNGameTypeItemVO) {
        let tabView: UIView
        if item.categoryType == .offline
            || item.categoryType == .user {
            let gameTab = LNHomeActivityTabView()
            gameTab.delegate = self
            addSubview(gameTab)
            gameTab.snp.makeConstraints { make in
                make.horizontalEdges.equalToSuperview().inset(16)
                make.top.equalToSuperview()
            }
            gameTab.update(item.children)
            tabView = gameTab
        } else {
            let gameTab = LNHomeGameTabView()
            gameTab.delegate = self
            addSubview(gameTab)
            gameTab.snp.makeConstraints { make in
                make.horizontalEdges.equalToSuperview().inset(16)
                make.top.equalToSuperview()
                make.height.equalTo(78)
            }
            gameTab.update(item.children)
            tabView = gameTab
        }
        
        addSubview(listView)
        listView.reloadList(newTopCategory: item.code, newCategory: nil, filter: LNGameMateFilter())
        listView.snp.makeConstraints { make in
            make.top.equalTo(tabView.snp.bottom).offset(8)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
}
