import React from 'react';
import { render } from '@testing-library/react';
import * as reactImage from 'react-image';
import { UserThumbProps, UserThumb } from '../userThumb';

describe('<UserThumb>', () => {
    const renderComponent = (props: UserThumbProps) => render(<UserThumb {...props} />);

    test('renders empty placeholder if no name and no url', () => {
        const { container } = renderComponent({});
        expect(container.querySelector('.UserThumb-image')).toBeNull();
        expect(container.querySelector('.UserThumb-placeholder')).toBeVisible();
    });

    test('renders image', async () => {
        const image = 'https://placehold.co/64.png';

        vi.spyOn(reactImage, 'useImage').mockReturnValue({
            src: image,
            isLoading: false,
            error: undefined,
        });

        const { container } = renderComponent({ image });

        const element = container.querySelector('.UserThumb-image');
        expect(element).toBeVisible();
        expect(element?.getAttribute('src')).toEqual(image);
        expect(container.querySelector('.UserThumb-placeholder')).toBeNull();
    });

    describe('no image', () => {
        test('renders user initials', () => {
            const name = 'Test user';
            const { getByText, container } = renderComponent({ name });

            const element = getByText('TU');
            expect(element).toBeVisible();
            expect(element).toHaveClass('UserThumb-title');
            expect(container.querySelector('.UserThumb-image')).toBeNull();
            expect(container.querySelector('.UserThumb-placeholder')).toBeVisible();
        });

        test('initials are only two chars long', () => {
            const name = 'Test middle name last';
            const { getByText } = renderComponent({ name });

            const element = getByText('TL');
            expect(element).toBeVisible();
        });

        test('background color class is applied', () => {
            const name = 'Test user';
            const { getByText } = renderComponent({ name });

            const element = getByText('TU');
            const imageContainer = element.parentElement?.parentElement;
            expect(imageContainer).toHaveClass('bg-pink');
        });
    });
});
