import { ImageOff } from 'lucide-react';
import { useAuthedFileUrl } from '../../lib/authedFile';

interface Props {
  src: string;
  alt?: string;
  className?: string;
  onClick?: () => void;
}

/**
 * An `<img>` for `/api/files/*` attachments. The file is fetched with the auth token
 * (see `useAuthedFileUrl`) and rendered from a blob URL, because a native `<img src>`
 * request can't carry the Bearer token that `/api/files` now requires. While the fetch
 * is in flight a subtle pulsing placeholder is shown in its place so the layout doesn't
 * jump; if it failed (deleted / 401 / 5xx) a "broken image" fallback is shown instead.
 */
export default function AuthedImage({ src, alt, className, onClick }: Props) {
  const { url: resolvedSrc, status } = useAuthedFileUrl(src);

  if (status === 'error') {
    return (
      <div
        className={`${className ?? ''} flex items-center justify-center bg-black/10 text-muted-foreground/50`}
        onClick={onClick}
        title={alt || 'Image not found'}
      >
        <ImageOff className="h-5 w-5" />
      </div>
    );
  }

  if (!resolvedSrc) {
    return <div className={`${className ?? ''} bg-white/10 animate-pulse`} onClick={onClick} />;
  }

  return <img src={resolvedSrc} alt={alt} className={className} onClick={onClick} />;
}
