import { Sentiment } from '../common';
import { render, screen, mockMatchMedia, fireEvent } from '../test-utils';

import AvatarWrapper from '.';

mockMatchMedia();

const name = 'Elizabeth Alexandra Mary Windsor';

describe('FlowNavigationAvatar', () => {
  describe('with a name', () => {
    it('shows the initials for a long name', () => {
      render(<AvatarWrapper name={name} />);

      expect(screen.getByText('EW')).toBeInTheDocument();
    });

    it('shows the first letter for a mononym', () => {
      render(<AvatarWrapper name="Zichaleangeol" />);

      expect(screen.getByText('Z')).toBeInTheDocument();
    });

    describe('AND profileType', () => {
      describe('FlowNavigationAvatar', () => {
        describe('with a name', () => {
          it('shows the initials for a long name', () => {
            render(<AvatarWrapper name={name} />);

            expect(screen.getByText('EW')).toBeInTheDocument();
          });

          it('shows the first letter for a mononym', () => {
            render(<AvatarWrapper name="Michelangelo" />);

            expect(screen.getByText('M')).toBeInTheDocument();
          });
        });
      });

      describe('with nothing passed', () => {
        it('renders aria-label', () => {
          render(<AvatarWrapper aria-label="test" />);

          expect(screen.getByLabelText('test')).toBeInTheDocument();
        });
      });

      describe('with a badge status icon passed', () => {
        it('renders the badge', () => {
          render(<AvatarWrapper badgeStatusIcon={Sentiment.POSITIVE} />);

          expect(screen.getByTestId('check-icon')).toBeInTheDocument();
        });

        it('renders aria-label', () => {
          render(<AvatarWrapper badgeStatusIcon={Sentiment.POSITIVE} aria-label="test" />);

          expect(screen.getByLabelText('test')).toBeInTheDocument();
        });
      });

      describe('with image URL', () => {
        it('falls back to initials when image fails to load', () => {
          const { container } = render(<AvatarWrapper name="John Doe" url="invalid-url.jpg" />);

          const img = container.querySelector('img');
          if (img) {
            fireEvent.error(img);
          }

          expect(screen.getByText('JD')).toBeInTheDocument();
        });

        it('resets error state when url prop changes', () => {
          const { container, rerender } = render(
            <AvatarWrapper name="John Doe" url="invalid-url-1.jpg" />,
          );

          const img = container.querySelector('img');
          if (img) {
            fireEvent.error(img);
          }

          expect(screen.getByText('JD')).toBeInTheDocument();

          rerender(<AvatarWrapper name="John Doe" url="valid-url.jpg" />);

          const newImg = container.querySelector('img');
          expect(newImg).toHaveAttribute('src', 'valid-url.jpg');
        });
      });
    });
  });
});
