import React from 'react';
import { useAvatarDecoration } from '../../hooks/useAvatarDecoration';
import { decorationUrl } from '../../features/lotus/avatarDecorations';

const DEFAULT_INSET = 8;

type AvatarDecorationProps = {
  userId: string;
  children: React.ReactNode;
  inset?: number;
};

export function AvatarDecoration({
  userId,
  children,
  inset = DEFAULT_INSET,
}: AvatarDecorationProps) {
  const slug = useAvatarDecoration(userId);

  if (!slug) {
    return <>{children}</>;
  }

  return (
    <div
      style={{
        position: 'relative',
        display: 'inline-flex',
        flexShrink: 0,
      }}
    >
      {children}
      <img
        src={decorationUrl(slug)}
        style={{
          position: 'absolute',
          top: -inset,
          left: -inset,
          right: -inset,
          bottom: -inset,
          width: `calc(100% + ${inset * 2}px)`,
          height: `calc(100% + ${inset * 2}px)`,
          pointerEvents: 'none',
          zIndex: 10,
          objectFit: 'contain',
        }}
        alt=""
        aria-hidden="true"
        loading="lazy"
        decoding="async"
        onError={(e) => {
          (e.currentTarget as HTMLImageElement).style.display = 'none';
        }}
      />
    </div>
  );
}
