/**
 * useNativeAd — React hook that fetches a single Google Native
 * Advanced ad on Android via the custom NativeAdsPlugin and exposes
 * its asset metadata (headline / icon / image / CTA) to the React
 * grid. The InlineAdSlot renders these inside a 2:3 portrait card so
 * the ad sits flush with the surrounding movie posters.
 *
 * v2 changes (May 2026):
 *   • Verbose console logs under [useNativeAd] so the user can open
 *     `chrome://inspect` → device webview and see exactly which step
 *     is failing (config fetch / platform check / plugin call).
 *   • Auto-retry once after 1s if the very first call hits a SDK
 *     init race. Cuts the "first scroll = no ad" complaint.
 */
import { useEffect, useState } from "react";

import {
  loadNativeAd,
  destroyNativeAd,
  type NativeAdAssets,
  nativeAdsAvailable,
} from "@/lib/nativeAds";
import { useEntitlement } from "@/hooks/useEntitlement";

interface AdConfigResponse {
  enabled: boolean;
  testing: boolean;
  native_id: string;
}

let cachedCfg: AdConfigResponse | null = null;
let inflightCfg: Promise<AdConfigResponse | null> | null = null;

const apiBase = (): string => {
  const env: any = (import.meta as any).env || {};
  return (
    env.VITE_REACT_APP_BACKEND_URL ||
    env.REACT_APP_BACKEND_URL ||
    env.VITE_BACKEND_URL ||
    ""
  );
};

const fetchAdConfig = async (): Promise<AdConfigResponse | null> => {
  if (cachedCfg) return cachedCfg;
  if (inflightCfg) return inflightCfg;
  inflightCfg = (async () => {
    try {
      const url = `${apiBase()}/api/public/ad-config`;
      const r = await fetch(url, { cache: "no-cache" });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const j = (await r.json()) as AdConfigResponse;
      cachedCfg = j;
      console.info("[useNativeAd] ad-config:", j);
      return j;
    } catch (e) {
      console.warn("[useNativeAd] ad-config fetch failed:", e);
      return null;
    } finally {
      inflightCfg = null;
    }
  })();
  return inflightCfg;
};

type State = {
  ad: NativeAdAssets | null;
  testing: boolean;
  loading: boolean;
};

export const useNativeAd = (_slotKey?: string): State => {
  const [state, setState] = useState<State>({ ad: null, testing: false, loading: true });
  // BUG-5 FEATURE (2026-05): respect the central entitlement flag so the
  // rewarded-unlock "ad-free window" and admin Users-vs-Guests toggles
  // also suppress native grid ads — not just banner / interstitial.
  const { adsEnabled } = useEntitlement();

  useEffect(() => {
    let cancelled = false;
    let createdAdId: string | null = null;

    // Short-circuit: ads disabled by entitlement → don't even touch the
    // SDK. Render the static "Upgrade to Premium" placeholder OR (when
    // wrapped by the caller's adsEnabled gate) nothing at all.
    if (!adsEnabled) {
      setState({ ad: null, testing: false, loading: false });
      return () => { cancelled = true; };
    }

    const tryLoad = async (attempt: number): Promise<void> => {
      if (!nativeAdsAvailable()) {
        console.info("[useNativeAd] not on Android native — skipping");
        if (!cancelled) setState({ ad: null, testing: false, loading: false });
        return;
      }

      const cfg = await fetchAdConfig();
      if (!cfg) {
        if (!cancelled) setState({ ad: null, testing: false, loading: false });
        return;
      }
      if (!cfg.enabled) {
        console.info("[useNativeAd] ads disabled in admin");
        if (!cancelled) setState({ ad: null, testing: false, loading: false });
        return;
      }
      if (!cfg.native_id) {
        console.warn("[useNativeAd] no native_id in admin config");
        if (!cancelled) setState({ ad: null, testing: cfg.testing, loading: false });
        return;
      }

      console.info(
        `[useNativeAd] attempt #${attempt} — loadNativeAd unit=${cfg.native_id} testing=${cfg.testing}`,
      );
      const result = await loadNativeAd(cfg.native_id, cfg.testing);
      if (cancelled) {
        if (result) void destroyNativeAd(result.adId);
        return;
      }
      if (result) {
        createdAdId = result.adId;
        console.info("[useNativeAd] ✓ ad loaded", {
          adId: result.adId,
          headline: result.headline,
          imageUrl: result.imageUrl,
        });
        setState({ ad: result, testing: cfg.testing, loading: false });
      } else if (attempt < 2) {
        // Retry once after the SDK init / network has settled.
        console.info("[useNativeAd] no fill on first try — retrying in 1s");
        await new Promise((r) => setTimeout(r, 1000));
        if (!cancelled) await tryLoad(attempt + 1);
      } else {
        console.warn("[useNativeAd] ✗ failed after retry — falling back to placeholder");
        setState({ ad: null, testing: cfg.testing, loading: false });
      }
    };

    void tryLoad(1);

    return () => {
      cancelled = true;
      if (createdAdId) void destroyNativeAd(createdAdId);
    };
  }, [adsEnabled]);

  return state;
};
