'use client';

import { useState } from 'react';
import { teamLogoUrl, accentColor, resolveTeam } from '@/lib/teamMeta';

/**
 * TeamLogo (DS0) — a team renders as ITSELF: real ESPN-CDN logo, with a
 * team-colored monogram fallback (NEVER a gray box or bare abbr). The whole
 * entity layer's job is that "MIL @ PIT" stops being flat text.
 *
 * On a 404 / unknown team we draw the abbr on a disc in the team's accent
 * color — still branded, still legible, never a fallback that reads broken.
 */
export default function TeamLogo({
  team,
  sport = 'mlb',
  size = 28,
  title,
}: {
  team: string;
  sport?: string;
  size?: number;
  title?: string;
}) {
  const [broken, setBroken] = useState(false);
  const url = teamLogoUrl(team, sport);
  const meta = resolveTeam(team, sport);
  const accent = accentColor(team, sport) || 'var(--text-1)';
  const label = meta?.abbr || String(team || '').toUpperCase().slice(0, 3);

  if (!url || broken) {
    // Team-colored monogram disc — branded fallback, never gray.
    return (
      <span
        title={title || meta?.name || label}
        className="mono"
        style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: size, height: size, borderRadius: '50%', flexShrink: 0,
          background: `color-mix(in srgb, ${accent} 20%, #0E0E16)`,
          border: `1px solid color-mix(in srgb, ${accent} 55%, transparent)`,
          color: accent, fontWeight: 800, fontSize: Math.max(8, size * 0.36),
          letterSpacing: '0.02em',
        }}
      >
        {label.slice(0, 3)}
      </span>
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={url}
      alt={meta?.name || label}
      title={title || meta?.name || label}
      width={size}
      height={size}
      loading="eager"
      decoding="async"
      onError={() => setBroken(true)}
      style={{ width: size, height: size, objectFit: 'contain', flexShrink: 0, display: 'block' }}
    />
  );
}
