"use client";

import { useEffect, useRef } from "react";
import AppImage from "@/components/ui/AppImage";

interface Ad {
  slug?: string;
  campaign_id?: string;
  label: string;
  size: string;
  src?: string;
  alt?: string;
  click_url?: string;
}

const RMP_TRACK_URL =
  (process.env.NEXT_PUBLIC_RMP_ADS_API || "https://advertising.relevantmediaproperties.com") +
  "/api/track/impression";

export default function AdImage({
  ad,
  page,
  priority,
}: {
  ad: Ad;
  page?: string;
  priority?: boolean;
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const beaconMount = useRef(false);

  useEffect(() => {
    if (!ad.src) return;
    const id = ad.campaign_id || ad.slug;
    if (!id) return;

    if (!beaconMount.current) {
      beaconMount.current = true;
      sendImpression(id, ad.slug, page, false);
    }
  }, [ad.src, ad.slug, ad.campaign_id, page]);

  if (!ad.src) return null;

  const [w, h] = ad.size.split("x").map((n) => parseInt(n, 10));
  const clickHref = ad.click_url || (ad.campaign_id ? `/r/${ad.campaign_id}` : ad.slug ? `/r/${ad.slug}` : "");

  return (
    <div
      ref={containerRef}
      className="ad-container"
      data-campaign-id={ad.campaign_id || undefined}
      data-ad-slug={ad.slug || undefined}
      data-banner="1"
    >
      {clickHref ? (
        <a href={clickHref} target="_blank" rel="sponsored noopener noreferrer">
          <AppImage src={ad.src} alt={ad.alt || ad.label} width={w} height={h} priority={priority} />
        </a>
      ) : (
        <AppImage src={ad.src} alt={ad.alt || ad.label} width={w} height={h} priority={priority} />
      )}
    </div>
  );
}

function sendImpression(
  id: string,
  slug: string | undefined,
  page: string | undefined,
  viewport: boolean,
) {
  if (typeof window === "undefined") return;
  const payload = JSON.stringify({
    campaign_id: id,
    slug: slug || undefined,
    page_path: page || window.location.pathname,
    page_url: window.location.href,
    viewport,
  });
  try {
    const ok =
      typeof navigator.sendBeacon === "function" &&
      navigator.sendBeacon(RMP_TRACK_URL, new Blob([payload], { type: "application/json" }));
    if (ok) return;
  } catch {
    /* fall through */
  }
  fetch(RMP_TRACK_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: payload,
    keepalive: true,
    mode: "cors",
  }).catch(() => undefined);
}
