package com.example.myapplication

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.navigation.NavController
import androidx.navigation.NavDestination

class MainActivity : AppCompatActivity() {

    private lateinit var bottomNav: BottomNavigationView
    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 1. 找到 NavHostFragment
        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        // 2. 找到 BottomNavigationView
        bottomNav = findViewById(R.id.bottom_nav)

        // 3. 绑定导航控制器（负责切换 Fragment、保持选中状态）
        bottomNav.setupWithNavController(navController)

        // 4. 取消图标颜色 tint —— 使用原图标颜色
        bottomNav.itemIconTintList = null

        // 5. 添加导航监听（用于某些 Fragment 隐藏底部导航栏）
        navController.addOnDestinationChangedListener { _, destination, _ ->
            when (destination.id) {
                R.id.rechargeFragment, R.id.goldCoinRechargeFragment,R.id.PersonalSettings,R.id.MySkin,R.id.searchFragment,R.id.MyKeyboard,R.id.searchResultFragment,R.id.keyboardDetailFragment,R.id.feedbackFragment,R.id.notificationFragment-> {
                    bottomNav.visibility = View.GONE
                }
                else -> {
                    bottomNav.visibility = View.VISIBLE
                }
            }
        }

        // 6. 检查是否有导航参数，处理从键盘跳转过来的请求
        handleNavigationFromIntent()
    }

    private fun handleNavigationFromIntent() {
        val navigateTo = intent.getStringExtra("navigate_to")
        if (navigateTo == "recharge_fragment") {
            // 延迟执行导航，确保导航控制器已经准备好
            bottomNav.post {
                try {
                    navController.navigate(R.id.action_global_rechargeFragment)
                } catch (e: Exception) {
                    // 如果导航失败，记录错误日志
                    android.util.Log.e("MainActivity", "Failed to navigate to recharge fragment", e)
                }
            }
        }
    }
}
