/**
 * TVBanner — Custom "House Ad" banner for Smart-TV builds only.
 *
 * Why this exists
 * ---------------
 * AdMob is strictly mobile (Android / iOS). Samsung Tizen and LG webOS
 * cannot run the Google Mobile Ads SDK, so on those platforms the
 * useGlobalBanner() hook is a no-op. This component fills that gap by
 * rendering an admin-configured banner anchored to the bottom of the
 * screen on TV builds, so revenue / house-ad campaigns still get a slot.
 *
 * Render contract
 * ---------------
 * • Mounts ONLY when `isSmartTV()` returns true.
 * • Reads the admin config via `fetchAppInfo()` → `tv_banner` object.
 * • When `tv_banner.enabled === false` OR the selected payload is empty,
 *   renders nothing (no empty strip).
 * • Two modes:
 *     – "image" → <img> wrapped in <a target="_blank"> when click_url set.
 *     – "html"  → raw HTML snippet (admin's responsibility to sanitise;
 *                 same trust model as AdMob native ads which also render
 *                 admin-trusted markup).
 *
 * The banner is fixed at the bottom (z-index 40) so it sits ON TOP of
 * PageLayout's main content area. PageLayout reserves the bottom space
 * by reading `--tv-banner-h` which we set on mount / unset on unmount.
 *
 * FEATURE (2026-01).
 */
import { useEffect, useState } from "react";

import { fetchAppInfo, type AppTVBannerInfo } from "@/lib/appInfo";
import { isSmartTV } from "@/native/tvPlatform";

/** Fixed banner height in CSS pixels. Picked to match the AdMob standard
 *  adaptive banner (50–60px) but slightly taller (72px) because TV
 *  screens are viewed from 2–3 m away. */
const TV_BANNER_HEIGHT_PX = 72;

const TVBanner = () => {
  const [banner, setBanner] = useState<AppTVBannerInfo | null>(null);

  // Only TVs ever try to load the banner config.
  const enabledPlatform = isSmartTV();

  useEffect(() => {
    if (!enabledPlatform) return;
    let cancelled = false;
    void fetchAppInfo()
      .then((info) => {
        if (cancelled) return;
        if (info?.tv_banner) setBanner(info.tv_banner);
      })
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, [enabledPlatform]);

  // Decide whether we have a renderable payload BEFORE we touch the
  // CSS variable so we don't reserve dead space when the banner is off.
  const hasPayload = (() => {
    if (!banner || !banner.enabled) return false;
    if (banner.type === "html") return !!banner.html.trim();
    return !!banner.image_url.trim();
  })();

  // Expose the banner height to PageLayout via a CSS variable so the
  // app's scroll containers shrink to make room. Cleared when the
  // banner is hidden so non-TV / disabled state runs edge-to-edge.
  useEffect(() => {
    if (typeof document === "undefined") return;
    const root = document.documentElement;
    if (enabledPlatform && hasPayload) {
      root.style.setProperty("--tv-banner-h", `${TV_BANNER_HEIGHT_PX}px`);
    } else {
      root.style.removeProperty("--tv-banner-h");
    }
    return () => {
      root.style.removeProperty("--tv-banner-h");
    };
  }, [enabledPlatform, hasPayload]);

  if (!enabledPlatform || !hasPayload || !banner) return null;

  return (
    <div
      data-testid="tv-house-banner"
      style={{
        position: "fixed",
        bottom: 0,
        left: 0,
        right: 0,
        height: TV_BANNER_HEIGHT_PX,
        zIndex: 40,
        background: "rgba(0,0,0,0.85)",
        borderTop: "1px solid hsla(40, 80%, 55%, 0.25)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        overflow: "hidden",
      }}
    >
      {banner.type === "html" ? (
        // Admin-trusted HTML. Inner wrapper centres + clips so a
        // mis-sized snippet can't blow the layout.
        <div
          data-testid="tv-house-banner-html"
          style={{ width: "100%", height: "100%", overflow: "hidden" }}
          dangerouslySetInnerHTML={{ __html: banner.html }}
        />
      ) : banner.click_url ? (
        <a
          href={banner.click_url}
          target="_blank"
          rel="noopener noreferrer"
          data-testid="tv-house-banner-image-link"
          style={{ display: "block", height: "100%" }}
        >
          <img
            src={banner.image_url}
            alt="Sponsored"
            data-testid="tv-house-banner-image"
            style={{ height: "100%", width: "auto", display: "block" }}
            loading="lazy"
          />
        </a>
      ) : (
        <img
          src={banner.image_url}
          alt="Sponsored"
          data-testid="tv-house-banner-image"
          style={{ height: "100%", width: "auto", display: "block" }}
          loading="lazy"
        />
      )}
    </div>
  );
};

export default TVBanner;
