import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/foundation.dart';
import 'package:onsolgo/core/constants.dart';

class AdHandler {
  static InterstitialAd? _interstitialAd;

  static void loadInterstitialAd() {
    if (kIsWeb) return; // Skip on PWA

    InterstitialAd.load(
      adUnitId: kInterstitialAdUnitId,
      request: const AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (ad) => _interstitialAd = ad,
        onAdFailedToLoad: (error) => _interstitialAd = null,
      ),
    );
  }

  static void showInterstitialAd(Function onAdClosed) {
    if (kIsWeb || _interstitialAd == null) {
      onAdClosed(); // If web or ad not ready, just open the chapter
      return;
    }

    _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
      onAdDismissedFullScreenContent: (ad) {
        ad.dispose();
        loadInterstitialAd(); // Load next one
        onAdClosed(); // Open the chapter
      },
      onAdFailedToShowFullScreenContent: (ad, error) {
        ad.dispose();
        onAdClosed();
      },
    );

    _interstitialAd!.show();
    _interstitialAd = null;
  }
}