import { Sparkles } from "lucide-react";

import { useNativeAd } from "@/hooks/useNativeAd";
import { recordClick, recordImpression } from "@/lib/nativeAds";
import { useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";

/**
 * InlineAdSlot — A "Sponsored" card slot that interleaves inside the
 * Movies / Series / Live TV grids.
 *
 * Layout contract (May 2026 — locked):
 *   • Outer container: `flex flex-col` matching the surrounding
 *     FocusableTile so total height = MovieCard total height.
 *   • Image area: STRICT `aspect-ratio: 2 / 3` via inline style. Tailwind
 *     `aspect-[2/3]` worked on phones but lost the constraint on some
 *     landscape Samsung WebView builds — inline style guarantees it.
 *   • Metadata strip: 2 lines, identical typography to MovieCard, so
 *     the row's auto-rows-max picks the SAME pixel height for ad and
 *     poster. No vertical "weird gap".
 *
 * Three render paths:
 *   1. Real Native Ad (Android APK only). Test mode → Google's universal
 *      test creative `ca-app-pub-3940256099942544/2247696110`.
 *   2. Fallback "Upgrade" placeholder (web / iOS / Tizen / webOS / no
 *      fill / ads disabled).
 *   3. `row` variant — light pill for Live TV's row list view.
 */
type Props = {
  variant?: "tile" | "row";
  testId?: string;
  onClick?: () => void;
  /**
   * Aspect ratio of the IMAGE area. Defaults to 2/3 (movie poster).
   * Pass "4 / 3" inside Live TV grid where channel tiles are square-ish.
   */
  aspectRatio?: string;
};

const InlineAdSlot = ({
  variant = "tile",
  testId = "inline-ad-slot",
  onClick,
  aspectRatio = "2 / 3",
}: Props) => {
  const navigate = useNavigate();
  // Bug-fix 2026-06 — the InlineAdSlot used to be silently un-clickable
  // when the calling page (Movies / Series / Live TV row variant)
  // forgot to pass an `onClick`. The card looked tappable
  // (`cursor-pointer`) but did nothing. We now ALWAYS have a
  // meaningful fallback: route the user to the Subscription / Premium
  // upsell page — the same action the placeholder card visually
  // promises ("Upgrade to Premium · Tap to learn more").
  const handleClick = () => {
    if (onClick) {
      onClick();
      return;
    }
    try {
      navigate("/subscription");
    } catch {
      /* navigation may fail outside Router context — fail silently */
    }
  };

  if (variant === "row") {
    return (
      <div
        data-testid={testId}
        role="button"
        tabIndex={0}
        onClick={handleClick}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            handleClick();
          }
        }}
        className="glass-card rounded-xl px-4 py-3 flex items-center gap-3 border border-primary/20 cursor-pointer hover:border-primary/40 transition-colors"
        // Same pointer-events / z-index defence as the tile variant —
        // some pages mount a global scroll-shield overlay that can
        // eat clicks on chips like this row.
        style={{
          background:
            "linear-gradient(135deg, hsla(40,80%,55%,0.06), hsla(200,30%,10%,0.6))",
          pointerEvents: "auto",
          position: "relative",
          zIndex: 1,
        }}
      >
        <span className="w-8 h-8 rounded-md bg-primary/15 flex items-center justify-center">
          <Sparkles className="w-4 h-4 text-primary" />
        </span>
        <div className="flex-1 min-w-0">
          <p className="text-[10px] tracking-[0.3em] uppercase text-primary/90">
            Sponsored
          </p>
          <p className="text-foreground text-xs truncate">
            Nadiplayer Premium — Enjoy ad-free streaming
          </p>
        </div>
      </div>
    );
  }

  return (
    <NativeAdTile testId={testId} onClick={handleClick} aspectRatio={aspectRatio} />
  );
};

const NativeAdTile = ({
  testId,
  onClick,
  aspectRatio,
}: {
  testId: string;
  onClick?: () => void;
  aspectRatio: string;
}) => {
  const { ad, testing } = useNativeAd();
  const impressionFired = useRef(false);

  useEffect(() => {
    if (!ad || impressionFired.current) return;
    impressionFired.current = true;
    void recordImpression(ad.adId);
  }, [ad]);

  // Outer wrapper — identical class set to MovieCard's FocusableTile so
  // grid auto-rows-max gives ad + poster IDENTICAL pixel heights.
  const cardCls =
    "glass-card rounded-xl overflow-hidden flex flex-col cursor-pointer relative border border-primary/20";
  const cardBg =
    "linear-gradient(160deg, hsla(40,80%,55%,0.10) 0%, hsla(200,30%,10%,0.65) 60%, hsla(200,30%,5%,0.85) 100%)";

  // Real Native Ad → render real assets, strict 2:3.
  if (ad) {
    return (
      <div
        data-testid={testId}
        data-ad-state="loaded"
        role="button"
        tabIndex={0}
        onClick={() => {
          void recordClick(ad.adId);
          onClick?.();
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            void recordClick(ad.adId);
            onClick?.();
          }
        }}
        className={cardCls}
        // ── Bug 2026-06 fix: the tile looked clickable but native ad
        // images sometimes rendered with their own `<img>` event swallowing
        // the click. Force `pointer-events: auto` on the card root and a
        // local stacking context with z-index:1 so it always sits ABOVE
        // any sibling overlay (skeleton fade, infinite-scroll sentinel).
        style={{
          background: cardBg,
          pointerEvents: "auto",
          position: "relative",
          zIndex: 1,
        }}
      >
        <div
          className="w-full relative bg-muted/20 overflow-hidden flex items-center justify-center"
          style={{ aspectRatio }}
        >
          {ad.imageUrl ? (
            <img
              src={ad.imageUrl}
              alt={ad.headline || "Sponsored"}
              className="w-full h-full object-cover"
              loading="lazy"
              draggable={false}
              style={{ pointerEvents: "none" }}
            />
          ) : ad.iconUrl ? (
            <img
              src={ad.iconUrl}
              alt={ad.headline || "Sponsored"}
              className="w-3/5 h-3/5 object-contain"
              loading="lazy"
              draggable={false}
              style={{ pointerEvents: "none" }}
            />
          ) : (
            <Sparkles className="w-10 h-10 text-primary/80" strokeWidth={1.4} />
          )}
          <span
            className={`absolute top-2 left-2 text-[9px] tracking-[0.25em] uppercase px-1.5 py-0.5 rounded ${
              testing
                ? "bg-amber-500/30 text-amber-300 border border-amber-500/50"
                : "bg-primary/25 text-primary border border-primary/40"
            }`}
            style={{ pointerEvents: "none" }}
            data-testid={testing ? "native-ad-test-badge" : "native-ad-live-badge"}
          >
            {testing ? "Test Ad" : "Ad"}
          </span>
        </div>
        <div className="p-2.5">
          <p className="text-foreground text-xs font-medium truncate">
            {ad.headline || "Sponsored"}
          </p>
          <div className="flex items-center justify-between mt-1">
            <span className="text-muted-foreground text-[10px] truncate">
              {ad.callToAction || ad.advertiser || "Nadiplayer Sponsored"}
            </span>
            {ad.starRating ? (
              <span className="text-muted-foreground text-[10px]">
                ★ {ad.starRating.toFixed(1)}
              </span>
            ) : null}
          </div>
        </div>
      </div>
    );
  }

  // Placeholder — same exact structure as MovieCard.
  return (
    <div
      data-testid={testId}
      data-ad-state="placeholder"
      role="button"
      tabIndex={0}
      onClick={onClick}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onClick?.();
        }
      }}
      className={cardCls}
      // Bug-fix 2026-06 — same defence as the real-ad branch above.
      style={{
        background: cardBg,
        pointerEvents: "auto",
        position: "relative",
        zIndex: 1,
      }}
    >
      <div
        className="w-full relative flex flex-col items-center justify-center p-3 text-center gap-1.5 overflow-hidden"
        style={{ aspectRatio }}
      >
        <Sparkles className="w-7 h-7 text-primary opacity-80" strokeWidth={1.4} />
        <p className="text-[9px] tracking-[0.4em] uppercase text-primary/90">
          Sponsored
        </p>
        <p
          className="font-display text-sm gold-text tracking-[0.2em] leading-tight"
          style={{ fontFamily: "Cinzel, serif" }}
        >
          NADIPLAYER
        </p>
        <p className="text-muted-foreground text-[9px] leading-snug max-w-[90%]">
          Go Premium · Ad-free · Faster zaps
        </p>
      </div>
      <div className="p-2.5">
        <p className="text-foreground text-xs font-medium truncate">
          Upgrade to Premium
        </p>
        <div className="flex items-center justify-between mt-1">
          <span className="text-primary/80 text-[10px] truncate">
            Tap to learn more
          </span>
        </div>
      </div>
    </div>
  );
};

export default InlineAdSlot;
