import React from 'react';
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Avatar } from '@/components/ui/Avatar';

describe('Avatar', () => {
  it('renders initials when no src provided', () => {
    render(<Avatar name="Max Mustermann" />);
    expect(screen.getByText('MM')).toBeInTheDocument();
  });

  it('renders single initial for single name', () => {
    render(<Avatar name="Anna" />);
    expect(screen.getByText('A')).toBeInTheDocument();
  });

  it('has role=img and aria-label', () => {
    render(<Avatar name="Max Mustermann" />);
    expect(screen.getByRole('img')).toHaveAttribute('aria-label', 'Avatar von Max Mustermann');
  });

  it('renders image when src provided', () => {
    render(<Avatar name="Test" src="https://example.com/avatar.png" />);
    const img = screen.getByRole('img').querySelector('img')!;
    expect(img).not.toBeNull();
  });

  it('falls back to initials on image error', () => {
    render(<Avatar name="Max Mustermann" src="https://example.com/broken.png" />);
    const img = screen.getByRole('img').querySelector('img')!;
    fireEvent.error(img);
    expect(screen.getByText('MM')).toBeInTheDocument();
  });
});
