"use client";
import { useEffect, useState } from "react";

// Shared module-level cache so the many CrossBadge instances on a page (one
// per name in Partners in Mission, plus the header points badge) only fetch
// the setting once, not once per instance.
let cachedIconUrl: string | null | undefined = undefined;
let fetchPromise: Promise<string | null> | null = null;

function getBadgeIconUrl(): Promise<string | null> {
  if (cachedIconUrl !== undefined) return Promise.resolve(cachedIconUrl as string | null);
  if (!fetchPromise) {
    fetchPromise = fetch("/api/badge-icon")
      .then((r) => r.json())
      .then((d) => {
        cachedIconUrl = d.badgeIconUrl;
        return (cachedIconUrl ?? null) as string | null;
      })
      .catch(() => null);
  }
  return fetchPromise;
}

export default function CrossBadge({ size = 14 }: { size?: number }) {
  const [iconUrl, setIconUrl] = useState<string | null>(cachedIconUrl ?? null);

  useEffect(() => {
    let mounted = true;
    getBadgeIconUrl().then((url) => {
      if (mounted) setIconUrl(url);
    });
    return () => {
      mounted = false;
    };
  }, []);

  if (iconUrl) {
    return (
      <img
        src={iconUrl}
        alt="Verified"
        className="inline-block rounded-full shrink-0 object-cover"
        style={{ width: size, height: size }}
      />
    );
  }

  return (
    <span
      className="inline-flex items-center justify-center rounded-full shrink-0"
      style={{
        width: size,
        height: size,
        background: "linear-gradient(135deg, #fbbf24, #d97706)",
        animation: "cross-pulse 2.5s ease-in-out infinite",
      }}
      title="Verified"
    >
      <span
        style={{
          fontSize: size * 0.65,
          lineHeight: 1,
          color: "#3a2a05",
          fontWeight: 900,
        }}
      >
        ✝
      </span>
    </span>
  );
}
