import { useState } from "react";

// Official OEM mark with a proven fallback chain:
//   0: SELF-HOSTED /logos/oem/{slug}.png — downloaded best-available mark (no CDN dependence).
//   1: Google favicon CDN (sz=128) — its "no icon" placeholder is exactly 16×16;
//      onLoad advances only at this stage.
//   2: DuckDuckGo icon CDN — the site's real favicon (any size accepted).
//   3: favicon.im — second independent resolver.
//   4: typographic monogram tile — always visible, never blank.
export default function OemLogo({ domain, name, slug, className = "h-9 w-9", tileCls = "h-9 w-9 border border-[#E2E7EF] bg-[#F0F3F7] grid place-items-center text-[11px] font-tech text-mist/70" }) {
  const [stage, setStage] = useState(0);
  const [localChecked, setLocalChecked] = useState(false);
  const initials = (name || "?").split(" ").map((w) => w[0]).slice(0, 2).join("").toUpperCase();
  if (!domain || (stage === 0 && localChecked) || stage === 4) {
    return <span className={tileCls} aria-hidden="true">{initials}</span>;
  }
  const SRCS = [
    slug ? `/logos/oem/${slug}.png` : "",
    `https://www.google.com/s2/favicons?domain=${domain}&sz=128`,
    `https://icons.duckduckgo.com/ip3/${domain}.ico`,
    `https://favicon.im/${domain}?larger=true`,
  ];
  const src = SRCS[stage];
  const onLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const img = e.currentTarget;
    if (stage === 0) {
      // Local file missing/broken (404 page or 0 bytes) — advance; also set flag so
      // a failed local probe never renders a broken-image icon.
      if (img.naturalWidth === 0) { setLocalChecked(true); setStage(1); }
      else if (img.naturalWidth <= 16) { setLocalChecked(true); setStage(1); }
      return;
    }
    const tiny = img.naturalWidth > 0 && img.naturalWidth <= 16 && img.naturalHeight <= 16;
    if (stage === 1 && tiny) setStage(2); // only Google's placeholder is swapped away
  };
  return (
    <img
      src={src}
      alt={`${name} official logo`}
      loading="lazy"
      onError={() => {
        if (stage === 0) setLocalChecked(true);
        setStage((s) => Math.min(s + 1, 4));
      }}
      onLoad={onLoad}
      className={`${className} object-contain`}
    />
  );
}
