'use client';

import { useState } from 'react';
import { getHeadshotUrl, type HeadshotSport } from '@/lib/playerHeadshot';
import { accentColor } from '@/lib/teamMeta';

/**
 * PlayerAvatar (DS0) — real headshot; fallback = TEAM-COLORED MONOGRAM, never
 * the gray silhouette (DESIGN-SPEC Part 2). A player always renders with
 * identity. When the CDN 404s (roster gaps) we draw the player's initials on
 * a disc tinted with their team color — branded, legible, never a gray blob.
 */
function initials(name: string): string {
  const parts = String(name || '').trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '?';
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

export default function PlayerAvatar({
  name,
  sport = 'mlb',
  playerId,
  espnId,
  headshotUrl,
  team,
  size = 36,
}: {
  name: string;
  sport?: HeadshotSport;
  /** League-native id (MLBAM for MLB, cdn.nba/cdn.wnba for NBA/WNBA). */
  playerId?: string | number | null;
  /** ESPN athlete id — the NBA/WNBA (and dormant NFL/NHL) headshot source. */
  espnId?: string | number | null;
  /** Wave 2B — a resolved absolute ESPN headshot URL; wins over a constructed one. */
  headshotUrl?: string | null;
  team?: string | null;
  size?: number;
}) {
  const [broken, setBroken] = useState(false);
  // Wave 2A/2B — resolve from whichever real asset we have. A direct
  // headshotUrl (ESPN's exact href) wins; else getHeadshotUrl routes by sport:
  // MLB→mlbstatic via playerId; NBA/WNBA→a.espncdn via espnId. Nothing → null →
  // team-colored monogram (never a gray silhouette).
  const url = (headshotUrl || playerId != null || espnId != null)
    ? getHeadshotUrl({ sport, playerId, espnId, headshotUrl })
    : null;
  const accent = (team && accentColor(team, String(sport))) || '#B8BCC8'; // Design neutral (was orphaned B-blue)
  const showImg = url && url !== '/images/player-silhouette.svg' && !broken;

  const Monogram = (
    <span
      title={name}
      className="mono"
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: size, height: size, borderRadius: '50%', flexShrink: 0,
        background: `color-mix(in srgb, ${accent} 22%, #0E0E16)`,
        border: `1px solid color-mix(in srgb, ${accent} 50%, transparent)`,
        color: accent, fontWeight: 800, fontSize: Math.max(9, size * 0.34), letterSpacing: '0.01em',
      }}
    >
      {initials(name)}
    </span>
  );

  if (!showImg) return Monogram;

  return (
    <span
      style={{
        display: 'inline-flex', width: size, height: size, borderRadius: '50%',
        overflow: 'hidden', flexShrink: 0, background: '#0E0E16',
        border: `1px solid color-mix(in srgb, ${accent} 40%, transparent)`,
      }}
    >
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={url as string}
        alt={name}
        width={size}
        height={size}
        loading="eager"
      decoding="async"
        onError={() => setBroken(true)}
        style={{ width: size, height: size, objectFit: 'cover', objectPosition: 'top center' }}
      />
    </span>
  );
}
