import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { Dropdown } from '../../src/components/Dropdown';

const choices = [
    { id: 'USER', label: 'User' },
    { id: 'ADMIN', label: 'Admin' },
];

describe('Dropdown', () => {
    it('calls onChange with selected value', () => {
        const onChange = vi.fn();
        render(<Dropdown label="Role" value="USER" choices={choices} onChange={onChange} />);

        fireEvent.change(screen.getByLabelText('Role'), { target: { value: 'ADMIN' } });
        expect(onChange).toHaveBeenCalledWith('ADMIN');
    });

    it('supports inline layout and disabled/required state', () => {
        const { container } = render(
            <Dropdown
                label="Rows"
                value="10"
                choices={[{ id: '10', label: '10' }]}
                layout="inline"
                disabled
                required
            />,
        );

        const select = screen.getByLabelText('Rows');
        expect(select).toBeDisabled();
        expect(select).toBeRequired();
        expect(container.querySelector('label')).toHaveClass('inline-flex');
    });

    it('renders error and custom class names', () => {
        const { container } = render(
            <Dropdown
                label="Role"
                value="USER"
                choices={choices}
                error="Role is invalid"
                className="custom-wrapper"
                selectClassName="custom-select"
            />,
        );

        const select = container.querySelector('select');
        expect(select).toBeInstanceOf(HTMLSelectElement);
        expect(screen.getByText('Role is invalid')).toBeInTheDocument();
        expect(select).toHaveClass('custom-select');
        expect(screen.getByText('Role').closest('label')).toHaveClass('custom-wrapper');
    });

    it('supports rendering without a label', () => {
        const { container } = render(<Dropdown value="USER" choices={choices} />);
        expect(container.querySelector('label > span')).toBeNull();
    });
});
