import React from 'react';
import { render, cleanup, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import Accordion from '.';

const module = {
  items: [
    { title: 'one', content: 'first content' },
    { title: 'two', content: 'second content' },
    { title: 'three', content: 'third content' },
  ],
};
describe('Accordions Component', () => {
  test('render with props', () => {
    const { container, getByText } = render(
      <Accordion module={module} openAll={false} closeOthers={false} />
    );
    expect(container.querySelectorAll('button.title')).toHaveLength(3);
    expect(getByText('one')).toBeTruthy();
    expect(getByText('second content')).toBeTruthy();
  });

  test('open item', async () => {
    const { container } = render(
      <Accordion module={module} openAll={false} openItem={2} closeOthers={false} />
    );
    await waitFor(() => {
      expect(container.querySelectorAll('button.title')[1].getAttribute('class')).toContain(
        'invertArrow'
      );
    });
  });

  test('open all', async () => {
    const { container } = render(<Accordion module={module} openAll closeOthers={false} />);
    await waitFor(() => {
      expect(container.querySelectorAll('button.invertArrow')).toHaveLength(3);
    });
  });

  test('close others when open one', () => {
    const { container } = render(
      <Accordion module={module} openItem={1} openAll={false} closeOthers />
    );

    const thirdtItemBtn = container.querySelectorAll('button')[2];
    fireEvent.click(thirdtItemBtn);
    const items = container.querySelectorAll('button.title');
    expect(items[2].getAttribute('class')).toContain('invertArrow');
    expect(items[1].getAttribute('class')).toEqual('title accordion-gtm btn-cta');
    expect(items[0].getAttribute('class')).toEqual('title accordion-gtm btn-cta');
  });

  test('do not close others when open one', () => {
    const { container } = render(
      <Accordion module={module} openItem={1} openAll={false} closeOthers={false} />
    );

    const thirdtItemBtn = container.querySelectorAll('button')[2];
    fireEvent.click(thirdtItemBtn);
    const items = container.querySelectorAll('button.title');
    expect(items[2].getAttribute('class')).toContain('invertArrow');
    expect(items[1].getAttribute('class')).toEqual('title accordion-gtm btn-cta');
    expect(items[0].getAttribute('class')).toContain('invertArrow');
  });
});
afterEach(() => {
  cleanup();
});
