// LogoBadge — renders a remote logo image scaled so its VISUAL
// (non-transparent / non-background) content reaches a target height.
// Two strategies:
//   1. CORS trimming — draw to canvas, find tight bbox of non-transparent
//      / non-uniform-background pixels, compute a scale factor so bbox
//      height == targetHeight.
//   2. Fallback — use the `manualScale` multiplier applied to the plain
//      image height (useful when the host blocks CORS).
//
// Visual treatment: grayscale + multiply blend so all logos share tone.

const LogoBadge = ({ src, alt, targetHeight = 26, manualScale = 1, lumTolerance = 18 }) => {
  const [scale, setScale] = React.useState(manualScale);
  const [cropY, setCropY] = React.useState({ top: 0, bottom: 0 });
  const [ready, setReady] = React.useState(false);
  const imgRef = React.useRef(null);

  const handleLoad = React.useCallback(() => {
    const img = imgRef.current;
    if (!img) { setReady(true); return; }
    const w = img.naturalWidth, h = img.naturalHeight;
    if (!w || !h) { setReady(true); return; }

    try {
      // CORS attempt: re-fetch through a separate Image with crossOrigin
      const probe = new Image();
      probe.crossOrigin = 'anonymous';
      probe.onload = () => {
        try {
          const maxDim = 400;
          const sc = Math.min(1, maxDim / Math.max(w, h));
          const cw = Math.max(1, Math.round(w * sc));
          const ch = Math.max(1, Math.round(h * sc));
          const canvas = document.createElement('canvas');
          canvas.width = cw; canvas.height = ch;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(probe, 0, 0, cw, ch);
          const data = ctx.getImageData(0, 0, cw, ch).data;

          // Sample the four corners — assume any one of those is the bg
          const corner = (x, y) => {
            const o = (y * cw + x) * 4;
            return { r: data[o], g: data[o + 1], b: data[o + 2], a: data[o + 3] };
          };
          const corners = [corner(0, 0), corner(cw - 1, 0), corner(0, ch - 1), corner(cw - 1, ch - 1)];
          // Pick the most common corner color (simple)
          const bg = corners[0];

          const isBg = (o) => {
            const a = data[o + 3];
            if (a < 12) return true; // transparent
            // compare to bg within tolerance
            const dr = data[o] - bg.r, dg = data[o + 1] - bg.g, db = data[o + 2] - bg.b;
            return Math.abs(dr) < lumTolerance && Math.abs(dg) < lumTolerance && Math.abs(db) < lumTolerance;
          };

          let minY = ch, maxY = -1;
          for (let y = 0; y < ch; y++) {
            for (let x = 0; x < cw; x++) {
              const o = (y * cw + x) * 4;
              if (!isBg(o)) {
                if (y < minY) minY = y;
                if (y > maxY) maxY = y;
                break;
              }
            }
            // Short-circuit: check from the other side too
          }
          // Re-scan for maxY from bottom
          for (let y = ch - 1; y > maxY; y--) {
            for (let x = 0; x < cw; x++) {
              const o = (y * cw + x) * 4;
              if (!isBg(o)) { if (y > maxY) maxY = y; break; }
            }
          }

          if (maxY > minY) {
            const visualH = (maxY - minY + 1);
            const ratio = ch / visualH; // scale factor to make visual H equal ch
            const autoScale = ratio;
            // Clamp sensible range
            const safe = Math.max(0.8, Math.min(2.5, autoScale));
            setScale(safe);
            setCropY({ top: minY / ch, bottom: (ch - 1 - maxY) / ch });
          }
        } catch (e) {
          // tainted canvas — fall back silently to manualScale
        }
        setReady(true);
      };
      probe.onerror = () => setReady(true);
      probe.src = src;
    } catch (e) { setReady(true); }
  }, [src, lumTolerance]);

  // Fallback: if no load fires within 800ms, just show with manualScale
  React.useEffect(() => {
    const t = setTimeout(() => setReady(true), 800);
    return () => clearTimeout(t);
  }, [src]);

  // Use an outer container with fixed height = targetHeight; inner img
  // is scaled so its visual content fills that height.
  return (
    <div
      style={{
        height: targetHeight,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
        opacity: ready ? 0.65 : 0,
        transition: 'opacity 0.25s',
      }}
      aria-label={alt}
    >
      <img
        ref={imgRef}
        src={src}
        alt={alt}
        onLoad={handleLoad}
        style={{
          height: targetHeight * scale,
          width: 'auto',
          objectFit: 'contain',
          transform: cropY.top || cropY.bottom
            ? `translateY(${((cropY.bottom - cropY.top) / 2) * targetHeight * scale}px)`
            : 'none',
          filter: 'grayscale(1) contrast(0.85)',
          mixBlendMode: 'multiply',
          maxWidth: 'none',
        }}
      />
    </div>
  );
};

window.LogoBadge = LogoBadge;
