import { Input } from '../inputs/Input';
import { lorem10, render, screen } from '../test-utils';
import { Label } from './Label';

describe('Label', () => {
  it('renders string labels', () => {
    render(
      <Label>
        Phone number
        <Input readOnly />
      </Label>,
    );

    expect(screen.getByLabelText(/Phone number/)).toBeInTheDocument();
  });

  it('renders string labels with (Optional) suffix', () => {
    render(
      <Label>
        <Label.Optional>Phone number</Label.Optional>
        <Input readOnly />
      </Label>,
    );

    expect(screen.getByLabelText(/Phone number/)).toBeInTheDocument();
    expect(screen.getByLabelText(/(Optional)/)).toBeInTheDocument();
  });

  it('renders description', () => {
    const inputId = 'input-id';
    const descriptionId = 'desc-test';
    render(
      <>
        <Label htmlFor={inputId}>Phone number</Label>
        <Label.Description id={descriptionId}>{lorem10}</Label.Description>
        <Input id={inputId} readOnly aria-describedby={descriptionId} />
      </>,
    );

    expect(screen.getByLabelText('Phone number')).toBeInTheDocument();
    expect(screen.getByText(lorem10)).toBeInTheDocument();
    expect(screen.getByText(lorem10)).toHaveAttribute('id', descriptionId);
  });

  it('renders description with optional', () => {
    const descriptionId = 'desc-test';
    render(
      <>
        <Label htmlFor="test">
          <Label.Optional>Phone number</Label.Optional>
        </Label>
        <Label.Description id={descriptionId}>{lorem10}</Label.Description>
        <Input id="test" readOnly aria-describedby={descriptionId} />
      </>,
    );

    expect(screen.getByLabelText(/Phone number/)).toBeInTheDocument();
    expect(screen.getByText(lorem10)).toBeInTheDocument();
    expect(screen.getByText(lorem10)).toHaveAttribute('id', descriptionId);
  });

  it('connects label with form control via `id` + `aria-labelledby`', () => {
    const labelId = 'label-id';
    render(
      <>
        <Label id={labelId}>Phone number</Label>
        <div role="group" aria-labelledby={labelId}>
          Custom complex component
        </div>
      </>,
    );

    expect(screen.getByLabelText('Phone number')).toHaveAttribute('aria-labelledby', labelId);
  });
});
