"use client";

import { useCallback, useEffect, useState } from "react";
import { ExternalLink } from "lucide-react";
import { Avatar } from "./Avatar";
import type { AdCampaign } from "@/lib/types";

/**
 * An advert in the feed.
 *
 * Marked as one plainly. A post that looks like a post but isn't is the
 * thing people resent most, and it costs nothing to be honest about it.
 */
export function AdSlot() {
  const [ad, setAd] = useState<AdCampaign | null>(null);
  const [seen, setSeen] = useState(false);

  const load = useCallback(() => {
    fetch("/api/ads/serve")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => setAd(d?.ad ?? null))
      .catch(() => {});
  }, []);

  useEffect(load, [load]);

  // A view is counted once, when it's actually been on screen.
  useEffect(() => {
    if (!ad || seen) return;

    const timer = setTimeout(() => {
      setSeen(true);
      fetch(`/api/ads/${ad.id}/view`, { method: "POST" }).catch(() => {});
    }, 1200);

    return () => clearTimeout(timer);
  }, [ad, seen]);

  if (!ad) return null;

  return (
    <a
      href={ad.linkUrl}
      target="_blank"
      rel="noreferrer nofollow sponsored"
      onClick={() => {
        fetch(`/api/ads/${ad.id}/click`, { method: "POST" }).catch(() => {});
      }}
      className="ad-slot"
    >
      <span className="ad-head">
        <Avatar user={ad.advertiser} size={34} />
        <span className="min-w-0">
          <b>{ad.advertiser.name}</b>
          <em>Sponsored</em>
        </span>
        <ExternalLink size={15} className="ad-out" />
      </span>

      <p className="ad-title">{ad.title}</p>
      {ad.body && <p className="ad-body">{ad.body}</p>}

      {ad.imageUrl && (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={ad.imageUrl} alt="" className="ad-image" />
      )}
    </a>
  );
}
