import { useEffect, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { X } from "lucide-react";
import { useEntitlement } from "@/hooks/useEntitlement";
import { showInterstitialNow, onInterstitialEvent, getHouseAdConfig, type HouseAd } from "@/lib/admob";
import { isSmartTV } from "@/lib/platform";
import { API_BASE } from "@/lib/nadiAuth";

/**
 * PeriodicInterstitial — fires an AdMob interstitial every N minutes on
 * a global timer (active anywhere in the app while mounted).
 *
 *  • On native (Capacitor Android) the actual fullscreen ad is shown
 *    by AdMob; the AdMob UI provides its own close button.
 *  • On web / preview (no AdMob runtime) OR when AdMob fails to fill
 *    in 4-6 seconds, we render a luxury fallback full-screen overlay
 *    with a countdown skip timer so the UX is the same shape.
 *
 * BUG-4 FIX (2026-05): three lifecycle bugs squashed —
 *   1. The fallback overlay's countdown started BEFORE we knew whether
 *      a real ad would arrive — so a slow-loading real ad would stack
 *      on top of the fallback. We now show the fallback ONLY after
 *      `showInterstitialNow()` resolves with `false`.
 *   2. We subscribe to AdMob's `onInterstitialAdShowed` event via
 *      `onInterstitialEvent` so the fallback auto-dismisses the
 *      instant a real ad takes over the screen.
 *   3. We add a hard maximum lifetime on the fallback overlay so it
 *      can never permanently lock the UI if React state desyncs.
 *
 *  Premium / expired-trial users (adsEnabled === false) never see this.
 */
type Props = {
  intervalMinutes?: number;
  skipAfterSeconds?: number;
  initialDelayMinutes?: number;
};

const FALLBACK_MAX_LIFETIME_MS = 30_000;

/**
 * Pick the best background image for the current device. Admin can supply
 * separate Phone / Tablet / TV images so PNG/JPEG art scales correctly on
 * every screen size; each falls back to the default `image_url`.
 */
function pickHouseImage(ha: HouseAd): string {
  if (typeof window === "undefined") return ha.image_url || "";
  const w = window.innerWidth;
  if (isSmartTV() || w >= 1280) return ha.image_url_tv || ha.image_url || "";
  if (w >= 768) return ha.image_url_tablet || ha.image_url || "";
  return ha.image_url || "";
}

const PeriodicInterstitial = ({
  intervalMinutes = 5,
  skipAfterSeconds = 5,
  initialDelayMinutes = 2,
}: Props) => {
  const { adsEnabled } = useEntitlement();
  const [overlayOpen, setOverlayOpen] = useState(false);
  const [skipLeft, setSkipLeft] = useState(skipAfterSeconds);
  const overlayMountedRef = useRef(false);
  // Admin-controlled sponsored popup config (enable/disable + content).
  const [houseAd, setHouseAd] = useState<HouseAd | null>(null);
  const houseAdRef = useRef<HouseAd | null>(null);

  useEffect(() => {
    let alive = true;
    void getHouseAdConfig(API_BASE).then((ha) => {
      if (!alive) return;
      setHouseAd(ha);
      houseAdRef.current = ha;
    });
    return () => { alive = false; };
  }, []);

  // Auto-dismiss the fallback the moment AdMob serves a real ad. This
  // is a global subscription kept for the lifetime of the component.
  useEffect(() => {
    const off = onInterstitialEvent((evt) => {
      if (evt === "showed" || evt === "impression") {
        if (overlayMountedRef.current) {
          console.log("[PeriodicInterstitial] real AdMob ad showed → dismissing fallback overlay");
          setOverlayOpen(false);
        }
      }
    });
    return off;
  }, []);

  useEffect(() => {
    overlayMountedRef.current = overlayOpen;
  }, [overlayOpen]);

  useEffect(() => {
    if (!adsEnabled) return;
    const initial = Math.max(10_000, initialDelayMinutes * 60_000);
    const repeat = Math.max(30_000, intervalMinutes * 60_000);

    let everyT: number | undefined;
    let hardCloseT: number | undefined;

    const trigger = async () => {
      try {
        const shown = await showInterstitialNow();
        if (shown) {
          // Real AdMob ad is on screen — make sure no stale fallback is showing.
          setOverlayOpen(false);
          return;
        }
      } catch (e) {
        console.warn("[PeriodicInterstitial] showInterstitialNow threw:", e);
      }
      // Real ad did NOT fire — surface the fallback sponsored popup,
      // but ONLY if the admin has enabled the house ad. If it's disabled
      // (or config not loaded), skip silently — no fake card.
      const ha = houseAdRef.current;
      if (!ha || !ha.enabled) return;
      setSkipLeft(ha.skip_secs ?? skipAfterSeconds);
      setOverlayOpen(true);
      // Hard safety net — close the overlay after FALLBACK_MAX_LIFETIME_MS
      // no matter what, so a stuck timer can never permanently block the UI.
      if (hardCloseT) window.clearTimeout(hardCloseT);
      hardCloseT = window.setTimeout(() => {
        setOverlayOpen(false);
      }, FALLBACK_MAX_LIFETIME_MS);
    };

    const initialT = window.setTimeout(() => {
      void trigger();
      everyT = window.setInterval(() => void trigger(), repeat);
    }, initial);

    return () => {
      window.clearTimeout(initialT);
      if (everyT) window.clearInterval(everyT);
      if (hardCloseT) window.clearTimeout(hardCloseT);
    };
  }, [adsEnabled, intervalMinutes, initialDelayMinutes, skipAfterSeconds]);

  // Countdown for fallback overlay — runs ONLY while overlay is visible.
  useEffect(() => {
    if (!overlayOpen) return;
    if (skipLeft <= 0) return;
    const t = window.setInterval(() => {
      setSkipLeft((s) => Math.max(0, s - 1));
    }, 1000);
    return () => window.clearInterval(t);
  }, [overlayOpen, skipLeft]);

  if (!adsEnabled) return null;

  const bgImage = houseAd ? pickHouseImage(houseAd) : "";

  return (
    <AnimatePresence>
      {overlayOpen && houseAd && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.3 }}
          className="fixed inset-0 z-[80] overflow-hidden"
          data-testid="periodic-interstitial-overlay"
        >
          {/* Full-bleed background image (centerCrop / cover) */}
          {bgImage ? (
            <button
              type="button"
              onClick={() => { if (houseAd.link_url) window.open(houseAd.link_url, "_blank"); }}
              aria-label={houseAd.title || "Sponsored"}
              className="absolute inset-0 w-full h-full bg-center bg-no-repeat bg-cover"
              style={{ backgroundImage: `url("${bgImage}")` }}
              data-testid="house-ad-image"
            />
          ) : (
            <div
              className="absolute inset-0"
              style={{ background: "radial-gradient(ellipse at center, hsl(200,30%,10%), hsl(200,30%,4%))" }}
            />
          )}

          {/* Dark scrim gradient for legibility (~60–90% black, heavier at the bottom) */}
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              background:
                "linear-gradient(to top, rgba(0,0,0,0.92) 0%, rgba(0,0,0,0.7) 36%, rgba(0,0,0,0.32) 62%, rgba(0,0,0,0.55) 100%)",
            }}
          />

          {/* Top bar: SPONSORED tag + close (after skip elapses) */}
          <div className="absolute top-0 inset-x-0 flex items-center justify-between p-5 sm:p-7">
            <span
              className="text-[10px] sm:text-xs tracking-[0.45em] uppercase text-primary font-medium px-3 py-1 rounded-full bg-black/40 backdrop-blur"
              data-testid="house-ad-sponsored"
            >
              Sponsored
            </span>
            {skipLeft <= 0 && (
              <button
                type="button"
                onClick={() => setOverlayOpen(false)}
                aria-label="Close ad"
                className="w-9 h-9 rounded-full bg-black/40 backdrop-blur flex items-center justify-center hover:bg-black/60 transition-colors"
              >
                <X className="w-4 h-4 text-white" />
              </button>
            )}
          </div>

          {/* Content layer — anchored cleanly at the bottom, on top of the scrim */}
          <div className="absolute inset-x-0 bottom-0 px-6 pb-9 sm:px-10 sm:pb-14">
            <motion.div
              initial={{ y: 24, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ delay: 0.12, duration: 0.4 }}
              className="w-full max-w-2xl"
            >
              <h3
                className="font-display text-3xl sm:text-5xl gold-text tracking-[0.12em] mb-3 leading-tight"
                style={{ fontFamily: "Cinzel, serif" }}
                data-testid="house-ad-title"
              >
                {houseAd.title || "NADIPLAYER PREMIUM"}
              </h3>
              <p
                className="text-white/85 text-sm sm:text-base mb-7 leading-relaxed max-w-xl"
                data-testid="house-ad-body"
              >
                {houseAd.body ||
                  "Enjoy Nadiplayer with no ads, faster channel switching and exclusive premium streams."}
              </p>

              <div className="flex flex-col sm:flex-row gap-3">
                {houseAd.link_url ? (
                  <button
                    type="button"
                    onClick={() => window.open(houseAd.link_url, "_blank")}
                    data-testid="house-ad-cta"
                    className="px-8 py-3.5 rounded-full text-xs sm:text-sm tracking-[0.2em] uppercase bg-primary text-primary-foreground hover:bg-primary/90 transition-colors font-medium"
                  >
                    {houseAd.cta || "Learn More"}
                  </button>
                ) : null}

                <button
                  type="button"
                  disabled={skipLeft > 0}
                  onClick={() => setOverlayOpen(false)}
                  data-testid="periodic-interstitial-skip"
                  className={`px-8 py-3.5 rounded-full text-xs sm:text-sm tracking-[0.25em] uppercase transition-colors backdrop-blur ${
                    skipLeft > 0
                      ? "bg-white/10 text-white/50 cursor-not-allowed"
                      : "bg-white/15 text-white hover:bg-white/25"
                  }`}
                >
                  {skipLeft > 0 ? `Skip in ${skipLeft}s` : "Skip Ad"}
                </button>
              </div>
            </motion.div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export default PeriodicInterstitial;
