package com.example.wallisyn.Activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import com.example.wallisyn.R
import com.example.wallisyn.ad.AdShowFailed
import com.example.wallisyn.ad.AdsInsUtil
import com.example.wallisyn.ad.LoadListener
import com.example.wallisyn.ad.ShowListener
import com.example.wallisyn.databinding.ActivityStartBinding
import com.thinkup.core.api.TUAdInfo
import kotlin.random.Random

class SplashActivity : BaseActivity() {

    companion object {
        private const val AD_TIMEOUT = 15000L // 广告加载超时时间 15 秒
    }

    private lateinit var binding: ActivityStartBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityStartBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.isAppearanceLightStatusBars = true//状态栏文字颜色
        loadSplashAd()
    }


    private val adHandler = Handler(Looper.getMainLooper())
    private val adTimeoutRunnable = Runnable {
        navigateToNext() // 超时直接跳转
    }

    private fun loadSplashAd() {
        adHandler.postDelayed(adTimeoutRunnable, AD_TIMEOUT)

        AdsInsUtil.loadAd(
            act = this,
            adID =AdsInsUtil.Placement.TOP_ON_AD_THREE,
            loadListener = object : LoadListener {
                override fun loaded(ad: TUAdInfo) {
                    adHandler.removeCallbacks(adTimeoutRunnable)
                    showSplashAd()
                }

                override fun loadFailed(error: String) {
                    adHandler.removeCallbacks(adTimeoutRunnable)
                    navigateToNext() // 加载失败直接跳转
                }
            })
    }

    private fun showSplashAd() {
        AdsInsUtil.showAd(
            act = this,
            adID = AdsInsUtil.Placement.TOP_ON_AD_THREE,
            listener = object : ShowListener {
                override fun onAdShown(ad: TUAdInfo?) {
                }

                override fun onAdShowFailed(error: AdShowFailed?) {
                    navigateToNext() // 展示失败也直接跳转
                }

                override fun onAdClosed() {
                    navigateToNext() // 广告关闭后跳转
                }
            })
    }

    private var hasNavigated = false

    //保证只跳转一次
    private fun navigateToNext() {
        if (hasNavigated) return
        hasNavigated = true
        navigateToMainActivity()
    }

    override fun shouldInterceptBackPress(): Boolean = true
    override fun onInterceptBackPressed() {

    }

    override fun onDestroy() {
        super.onDestroy()
        adHandler.removeCallbacks(adTimeoutRunnable)
    }

    private fun navigateToMainActivity() {
        try {
            // 跳转首页（包名+类名与Manifest一致）
            val intent = Intent(this, HomeMainActivity::class.java)
            // 校验目标Activity是否存在（避免类名错误）
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                finish() // 关闭启动页，避免返回重复显示
            } else {
                Toast.makeText(this, "首页未找到", Toast.LENGTH_SHORT).show()
                finish()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "跳转失败", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
            finish()
        }
    }

}