---
/**
 * Avatar Component
 * Displays user avatars with fallback initials
 */
import type { HTMLAttributes } from 'astro/types';
import { cn } from '@/lib/cn';
import { avatarVariants } from './avatar.variants';

interface Props extends HTMLAttributes<'div'> {
  src?: string;
  alt?: string;
  fallback?: string;
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
}

const { src, alt = '', fallback, size = 'md', class: className, ...attrs } = Astro.props;

// Generate initials from alt text or fallback
const initials = fallback || alt
  .split(' ')
  .map((word) => word[0])
  .join('')
  .slice(0, 2)
  .toUpperCase();
---

<div class={cn(avatarVariants({ size }), className)} {...attrs}>
  {src ? (
    <img
      src={src}
      alt={alt}
      class="w-full h-full object-cover"
      loading="lazy"
      decoding="async"
      data-avatar-img
    />
    <span class="hidden items-center justify-center w-full h-full" aria-hidden="true" data-avatar-fallback>
      {initials || '?'}
    </span>
  ) : (
    <span aria-hidden="true">{initials || '?'}</span>
  )}
  <span class="sr-only">{alt || 'User avatar'}</span>
</div>

<script>
  function initAvatarFallbacks() {
    const avatarImgs = document.querySelectorAll<HTMLImageElement>('[data-avatar-img]');
    avatarImgs.forEach((img) => {
      if (img.dataset.avatarInit) return;
      img.dataset.avatarInit = 'true';

      img.addEventListener('error', () => {
        img.classList.add('hidden');
        const fallback = img.nextElementSibling as HTMLElement | null;
        if (fallback && fallback.hasAttribute('data-avatar-fallback')) {
          fallback.classList.remove('hidden');
          fallback.classList.add('flex');
        }
      });
    });
  }

  initAvatarFallbacks();
  document.addEventListener('astro:page-load', initAvatarFallbacks);
</script>
