import { render, screen, userEvent } from '../test-utils';

import Link from '.';

describe('Link', () => {
  const props = {
    className: 'a-class',
    href: '/test',
  };

  it('renders Link component', () => {
    render(<Link {...props}>link text</Link>);

    const link = screen.getByRole('link', { name: 'link text' });

    expect(link).toHaveAttribute('href', props.href);
    expect(link).toHaveClass(props.className);
    expect(link).not.toHaveAttribute('target');
    expect(link).not.toHaveAttribute('rel');
  });

  it('renders target and rel attributes when target is _blank', () => {
    render(
      <Link {...props} target="_blank">
        link text
      </Link>,
    );

    const link = screen.getByText('link text');

    expect(link).toHaveAttribute('target', '_blank');
    expect(link).toHaveAttribute('rel', 'noreferrer');
  });

  it('renders as link (`a` element) when href and onClick provided', async () => {
    const href = 'wise.com';
    const onClick = jest.fn();
    render(
      <Link href={href} onClick={onClick}>
        link text
      </Link>,
    );
    expect(onClick).toHaveBeenCalledTimes(0);

    const link = screen.getByText('link text');

    expect(link).toHaveAttribute('href', href);
    await userEvent.click(link);
    expect(link.tagName).toBe('A');
    expect(onClick).toHaveBeenCalledTimes(1);
  });

  it('renders as button element when only onClick provided', async () => {
    const onClick = jest.fn();
    // eslint-disable-next-line jsx-a11y/click-events-have-key-events
    render(<Link onClick={onClick}>link text</Link>);
    expect(onClick).toHaveBeenCalledTimes(0);

    const link = screen.getByText('link text');

    await userEvent.click(link);
    expect(link.tagName).toBe('BUTTON');
    expect(onClick).toHaveBeenCalledTimes(1);
  });

  it('renders with the provided aria-label', () => {
    render(
      <Link {...props} aria-label="make me accessible">
        link text
      </Link>,
    );

    const link = screen.getByText('link text');

    expect(link).toHaveAttribute('aria-label', 'make me accessible');
  });

  it('renders disabled button with attribute and class', () => {
    const onClick = jest.fn();
    render(
      // eslint-disable-next-line jsx-a11y/click-events-have-key-events
      <Link disabled onClick={onClick}>
        button as link
      </Link>,
    );

    const link = screen.getByText('button as link');
    expect(link.tagName).toBe('BUTTON');
    expect(link).toHaveClass('np-link--disabled');
    expect(link).toBeDisabled();
  });

  it('passes disabled attribute to anchor element when rendered as link', () => {
    render(
      <Link {...props} disabled>
        disabled link
      </Link>,
    );

    const link = screen.getByText('disabled link');

    expect(link).toHaveClass('np-link--disabled');
    expect(link.tagName).toBe('A');
  });
});
