/**
 * TS bridge for the custom Capacitor `NativeAds` plugin (Java side
 * lives in android/app/src/main/java/com/nadi/player/nativeads/).
 *
 * On non-Android (web / iOS / Tizen / webOS), every method is a no-op
 * returning null so callers can simply fall back to the static
 * "Sponsored" placeholder card without any platform branching at the
 * call site.
 */
import { Capacitor, registerPlugin } from "@capacitor/core";

export interface NativeAdAssets {
  adId: string;
  headline: string;
  body: string;
  callToAction: string;
  advertiser: string;
  store: string;
  price: string;
  starRating?: number;
  iconUrl?: string;
  imageUrl?: string;
}

interface NativeAdsBridge {
  loadNativeAd(opts: { adUnitId: string; testing?: boolean }): Promise<NativeAdAssets>;
  recordImpression(opts: { adId: string }): Promise<{ ok: boolean; note?: string }>;
  recordClick(opts: { adId: string }): Promise<{ ok: boolean }>;
  destroy(opts: { adId: string }): Promise<{ ok: boolean }>;
}

const NativeAds = registerPlugin<NativeAdsBridge>("NativeAds");

const isAndroidNative =
  Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android";

export const nativeAdsAvailable = (): boolean => isAndroidNative;

export const loadNativeAd = async (
  adUnitId: string,
  testing: boolean,
): Promise<NativeAdAssets | null> => {
  if (!isAndroidNative || !adUnitId) return null;
  try {
    return await NativeAds.loadNativeAd({ adUnitId, testing });
  } catch (e) {
    console.warn("[nativeAds] loadNativeAd failed:", e);
    return null;
  }
};

export const recordImpression = async (adId: string): Promise<void> => {
  if (!isAndroidNative || !adId) return;
  try {
    await NativeAds.recordImpression({ adId });
  } catch (e) {
    console.warn("[nativeAds] recordImpression failed:", e);
  }
};

export const recordClick = async (adId: string): Promise<void> => {
  if (!isAndroidNative || !adId) return;
  try {
    await NativeAds.recordClick({ adId });
  } catch (e) {
    console.warn("[nativeAds] recordClick failed:", e);
  }
};

export const destroyNativeAd = async (adId: string): Promise<void> => {
  if (!isAndroidNative || !adId) return;
  try {
    await NativeAds.destroy({ adId });
  } catch (e) {
    console.warn("[nativeAds] destroy failed:", e);
  }
};
