import React, { useEffect, useRef } from 'react';

interface HeadAvatarProps {
  skinUrl?: string;
  size?: number;
  style?: React.CSSProperties;
  version?: number;
}

const DEFAULT_SKIN =
  'https://static.planetminecraft.com/files/resource_media/skin/original-steve-15053860.png';

export const HeadAvatar: React.FC<HeadAvatarProps> = ({
  skinUrl,
  size = 24,
  style,
  version = 0,
  ...canvasProps
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const requestIdRef = useRef(0);

  useEffect(() => {
    requestIdRef.current += 1;
    const requestId = requestIdRef.current;

    const baseUrl = skinUrl?.trim() ? skinUrl : DEFAULT_SKIN;
    const finalSkinUrl = `${baseUrl}${baseUrl.includes('?') ? '&' : '?'}v=${version}`;

    const canvas = canvasRef.current;
    if (!canvas) return;

    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.src = finalSkinUrl;

    img.onload = () => {
      // ✅ игнорим старые onload
      if (requestIdRef.current !== requestId) return;

      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      canvas.width = size;
      canvas.height = size;

      ctx.clearRect(0, 0, size, size);
      ctx.imageSmoothingEnabled = false;

      ctx.drawImage(img, 8, 8, 8, 8, 0, 0, size, size);
      ctx.drawImage(img, 40, 8, 8, 8, 0, 0, size, size);
    };

    img.onerror = (e) => {
      if (requestIdRef.current !== requestId) return;
      console.error('Не удалось загрузить скин для HeadAvatar:', e);
    };

    return () => {
      // ✅ гарантированно “убиваем” обработчики старого запроса
      img.onload = null;
      img.onerror = null;
    };
  }, [skinUrl, size, version]);

  return (
    <canvas
      ref={canvasRef}
      {...canvasProps}
      style={{
        width: size,
        height: size,
        borderRadius: 4,
        imageRendering: 'pixelated',
        ...style,
      }}
    />
  );
};
