import 'dart:io';

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

/// Reusable banner ad widget. Uses test ad unit IDs in debug; for production
/// replace with your real AdMob banner ad unit IDs per platform.
class BannerAdWidget extends StatefulWidget {
  const BannerAdWidget({super.key, String? adUnitId})
      : _adUnitId = adUnitId;

  final String? _adUnitId;

  @override
  State<BannerAdWidget> createState() => _BannerAdWidgetState();
}

class _BannerAdWidgetState extends State<BannerAdWidget> {
  BannerAd? _bannerAd;
  bool _isLoaded = false;

  /// Test banner ad unit IDs (Google sample); replace with your IDs for production.
  // Google Mobile Ads test ad unit IDs:
  // Android: ca-app-pub-3940256099942544/6300978111
  // iOS:    ca-app-pub-3940256099942544/2934735716
  static String get _testAdUnitId {
    if (Platform.isIOS) {
      // iOS test AdMob banner ad unit ID
      return 'ca-app-pub-9051626064733383/6237884449';
    }
    // Android test AdMob banner ad unit ID
    return 'ca-app-pub-9051626064733383/6892490569';
  }

  @override
  void initState() {
    super.initState();
    _loadAd();
  }

  Future<void> _loadAd() async {
    final adUnitId = widget._adUnitId ?? _testAdUnitId;
    _bannerAd = BannerAd(
      adUnitId: adUnitId,
      size: AdSize.banner,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          if (mounted) setState(() => _isLoaded = true);
        },
        onAdFailedToLoad: (ad, error) {
          ad.dispose();
          if (mounted) setState(() => _bannerAd = null);
        },
      ),
    );
    await _bannerAd!.load();
  }

  @override
  void dispose() {
    _bannerAd?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!_isLoaded || _bannerAd == null) {
      return const SizedBox.shrink();
    }
    return SizedBox(
      width: _bannerAd!.size.width.toDouble(),
      height: _bannerAd!.size.height.toDouble(),
      child: AdWidget(ad: _bannerAd!),
    );
  }
}
