//
//  LNNavigationController.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/6.
//

import Foundation
import UIKit

class LNNavigationController: UINavigationController {
    private let whileListVC: [UIViewController.Type] = [
        LNMainViewController.self,
        LNWebViewController.self,
        LNLoginPhoneInputViewController.self,
        LNLoginCaptchaInputViewController.self
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        interactivePopGestureRecognizer?.delegate = self
        navigationBar.backgroundColor = .white
        
        configureNavigationBarAppearance()
        
        LNEventDeliver.addObserver(self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if !hasLogin {
            self.showLoginPanel()
        }
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if hasLogin || whileListVC.contains(where: { $0 == type(of: viewController) }) {
            super.pushViewController(viewController, animated: animated)
            LNVoicePlayer.shared.stop()
            return
        }
        showLoginPanel()
    }
    
    override func popViewController(animated: Bool) -> UIViewController? {
        LNVoicePlayer.shared.stop()
        
        return super.popViewController(animated: animated)
    }
}

extension LNNavigationController: LNAccountManagerNotify {
    func onUserLogout() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
            guard let self else { return }
            showLoginPanel()
        }
    }
}

extension LNNavigationController {
    // 配置导航栏及返回按钮的全局样式
    private func configureNavigationBarAppearance() {
        let navBarAppearance = UINavigationBarAppearance()
        
//        navBarAppearance.backgroundColor = .backgroundSecondary // 导航栏背景色
        navBarAppearance.shadowColor = .clear // 去除底部阴影线
        
        UINavigationBar.appearance().standardAppearance = navBarAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
    }
    
    private func showLoginPanel() {
        LNLoginPanel.show(container: viewControllers.first?.view)
    }
}

extension LNNavigationController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        guard viewControllers.count > 1 else { return false }
        guard let viewController = viewControllers.last as? LNViewController else { return true }
        return viewController.enableDragBack
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                           shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        true
    }
}
