<script lang="ts">
  import { cn } from '@/lib/utils'

  interface Props {
    src?: string
    alt?: string
    fallback: string
    class?: string
  }

  let { src, alt = '', fallback, class: className }: Props = $props()

  let imageError = $state(false)
  let imageLoaded = $state(false)

  function handleError() {
    imageError = true
  }

  function handleLoad() {
    imageLoaded = true
  }
</script>

<div
  data-slot="avatar"
  class={cn(
    'relative flex size-8 shrink-0 overflow-hidden rounded-full',
    className
  )}
>
  {#if src && !imageError}
    <img
      data-slot="avatar-image"
      {src}
      {alt}
      class={cn('aspect-square size-full object-cover', !imageLoaded && 'opacity-0')}
      onload={handleLoad}
      onerror={handleError}
    />
  {/if}

  {#if !src || imageError || !imageLoaded}
    <span
      data-slot="avatar-fallback"
      class={cn(
        'bg-muted flex size-full items-center justify-center rounded-full text-xs font-medium',
        src && imageLoaded && 'hidden'
      )}
    >
      {fallback}
    </span>
  {/if}
</div>
