using System.Runtime.InteropServices;
using UnityEngine;

public class AdsterInterstitialAd : MonoBehaviour
{
    public static AdsterInterstitialAd Instance { get; private set; }

    public event System.Action<string> OnLoaded;
    public event System.Action<string> OnLoadFailed;
    public event System.Action<string> OnShowFailed;
    public event System.Action<string> OnWillShow;
    public event System.Action<string> OnClosed;
    public event System.Action<string> OnClicked;
    public event System.Action<string> OnImpression;

#if UNITY_IOS && !UNITY_EDITOR
    [DllImport("__Internal")] private static extern void load_interstitial_ad(string placementKey);
    [DllImport("__Internal")] private static extern void show_interstitial_ad();
#endif

    private void Awake()
    {
        if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); }
        else { Destroy(gameObject); }
    }

    public void LoadInterstitialAd(string placementKey)
    {
        Debug.Log($"LoadInterstitialAd function with placement: {placementKey}");
#if UNITY_IOS && !UNITY_EDITOR
        load_interstitial_ad(placementKey);
#else
        Debug.Log($"load_interstitial_ad({placementKey}) (simulated in editor)");
        Invoke(nameof(SimulateInterstitialLoaded), 2f);
#endif
    }

    public void ShowInterstitialAd()
    {
        Debug.Log("ShowInterstitialAd function...");
#if UNITY_IOS && !UNITY_EDITOR
        show_interstitial_ad();
#else
        Debug.Log("show_interstitial_ad (simulated in editor)");
#endif
    }

    public void HandleInterstitialAdLoaded(string result) { Debug.Log($"Interstitial ad loaded: {result}"); OnLoaded?.Invoke(result); }
    public void HandleInterstitialAdLoadFailed(string error) { Debug.LogError($"Interstitial ad load failed: {error}"); OnLoadFailed?.Invoke(error); }
    public void HandleInterstitialAdShowFailed(string error) { Debug.LogError($"Interstitial ad show failed: {error}"); OnShowFailed?.Invoke(error); }
    public void HandleInterstitialAdWillShow(string result) { Debug.Log($"Interstitial ad will show: {result}"); OnWillShow?.Invoke(result); }
    public void HandleInterstitialAdClosed(string result) { Debug.Log($"Interstitial ad closed: {result}"); OnClosed?.Invoke(result); }
    public void HandleInterstitialAdClicked(string result) { Debug.Log($"Interstitial ad clicked: {result}"); OnClicked?.Invoke(result); }
    public void HandleInterstitialAdImpression(string result) { Debug.Log($"Interstitial ad impression: {result}"); OnImpression?.Invoke(result); }

    private void SimulateInterstitialLoaded() => HandleInterstitialAdLoaded("Success");
}

