package com.simplecleaner.app.business.ads.admob

import android.content.Context
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions
import com.simplecleaner.app.business.ads.admob.AdmobEvent.AdmobOnPaidEventListener
import com.simplecleaner.app.utils.LogEx
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob

/**
 * 原生广告加载器
 */
class NativeAdLoader {
    
    private val TAG = "NativeAdLoader"
    
    // 协程作用域
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    
    /**
     * 加载原生广告
     */
    fun loadAd(
        context: Context,
        admobEvent: AdmobEvent,
        onSuccess: ((NativeAd) -> Unit)? = null,
        onError: ((LoadAdError) -> Unit)? = null
    ) {
        try {
            LogEx.logDebug(TAG, "Starting to load native ad")
            admobEvent.adPulStart()
            
            var currentNativeAd: NativeAd? = null
            
            val adLoader = AdLoader.Builder(context, NativeAdConfig.AD_UNIT_ID)
                .forNativeAd { nativeAd ->
                    try {
                        LogEx.logDebug(TAG, "Native ad loaded successfully")
                        
                        // 设置付费事件监听器
                        nativeAd.setOnPaidEventListener(
                            AdmobOnPaidEventListener(nativeAd, scope)
                        )
                        
                        currentNativeAd = nativeAd
                        admobEvent.pullAd(nativeAd.responseInfo)
                        
                        onSuccess?.invoke(nativeAd)
                        
                    } catch (e: Exception) {
                        LogEx.logDebug(TAG, "Error handling loaded ad: ${e.message}")
                    }
                }
                .withAdListener(object : AdListener() {
                    override fun onAdFailedToLoad(error: LoadAdError) {
                        LogEx.logDebug(TAG, "Native ad failed to load: ${error.message}")
                        admobEvent.pullAd(error.responseInfo, error)
                        onError?.invoke(error)
                    }
                    
                    override fun onAdClicked() {
                        LogEx.logDebug(TAG, "Native ad clicked")
                        admobEvent.clickAd(currentNativeAd?.responseInfo)
                    }
                    
                    override fun onAdClosed() {
                        LogEx.logDebug(TAG, "Native ad closed")
                    }
                })
                .withNativeAdOptions(
                    NativeAdOptions.Builder()
                        .setAdChoicesPlacement(NativeAdOptions.ADCHOICES_TOP_RIGHT)
                        .setRequestCustomMuteThisAd(true)
                        .setVideoOptions(
                            com.google.android.gms.ads.VideoOptions.Builder()
                                .setStartMuted(true)
                                .build()
                        )
                        .build()
                )
                .build()
            
            // 开始加载广告
            adLoader.loadAds(AdRequest.Builder().build(), 1)
            
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error creating ad loader: ${e.message}")
        }
    }
    
    /**
     * 预加载广告
     */
    fun preloadAd(context: Context) {
        loadAd(
            context = context,
            admobEvent = AdmobEvent(NativeAdConfig.Event.AD_UNIT_NAME, NativeAdConfig.Event.PRELOAD_FROM),
            onSuccess = { nativeAd ->
                LogEx.logDebug(TAG, "Preload ad loaded successfully")
            },
            onError = { error ->
                LogEx.logDebug(TAG, "Preload ad failed: ${error.message}")
            }
        )
    }
} 