import { useEffect, useState } from 'react';
import { isRemoteAvatarUrl, peekAvatarUrl, resolveAvatarUrl } from '../data/avatarCache';

const FALLBACK_ICON = 'assets/account.svg';

export function UserAvatar({ user, size = 24, className = '' }) {
  // avatarUrl carries a full URL/data URL (e.g. a user-uploaded pfp);
  // avatar is a bundled asset filename from the mock roster.
  const wanted = user?.avatarUrl ?? (user?.avatar ? `assets/${user.avatar}` : FALLBACK_ICON);
  const isFallback = !user?.avatarUrl && !user?.avatar;

  // Remote (http/https) avatars can't be plain <img src> — the webview blocks
  // plain-http loads from non-localhost servers as mixed content. They are
  // downloaded through apiFetch into a cached object URL instead; re-render
  // once the download lands.
  const remote = isRemoteAvatarUrl(wanted);
  const cached = remote ? peekAvatarUrl(wanted) : undefined;
  const [, setLanded] = useState(0);
  useEffect(() => {
    if (!remote || cached !== undefined) return undefined;
    let alive = true;
    resolveAvatarUrl(wanted).then(() => {
      if (alive) setLanded((n) => n + 1);
    });
    return () => {
      alive = false;
    };
  }, [wanted, remote, cached]);

  const src = remote ? cached ?? FALLBACK_ICON : wanted;

  // A resolved avatar can still transiently fail to render (e.g. a revoked
  // object URL after a hot reload). Without a handler that leaves a permanent
  // broken-image glyph, so fall back to the account icon on error instead.
  const onError = (e) => {
    if (e.currentTarget.src.endsWith(FALLBACK_ICON)) return;
    e.currentTarget.src = FALLBACK_ICON;
  };

  return (
    <span
      className={`user-avatar${isFallback ? ' user-avatar--fallback' : ''} ${className}`.trim()}
      style={{ width: size, height: size }}
    >
      <img src={src} alt="" onError={onError} />
    </span>
  );
}
