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

import '~tests/helpers/match-media.mock';
import { getCookie } from '~helpers/cookies';
import MainProvider from '~context/MainProvider';
import CookieConsent from '.';

const children = (
  <p>
    Hello this is a<b>cookie test</b>
  </p>
);

function renderComponent() {
  return render(
    <MainProvider
      value={{
        bannerIsActive: false,
        cookieAccepted: true,
      }}
    >
      <CookieConsent acceptText="Accept Me" declineText="Decline Me" declineURL="/">
        {children}
      </CookieConsent>
    </MainProvider>
  );
}

describe('cookie consent component', () => {
  test('Children and declineButton', () => {
    const { container, getByText } = renderComponent();

    expect(container.querySelectorAll('div.cookieConsent')).toHaveLength(1);

    expect(container.querySelectorAll('p')).toHaveLength(1);
    expect(container.querySelectorAll('b')).toHaveLength(1);
    expect(getByText('cookie test')).toBeTruthy();
    const declineButton = getByText('Decline Me');
    fireEvent.click(declineButton);
    expect(navigate).toHaveBeenCalled();
  });
  test('Buttons', () => {
    const { getByText } = renderComponent();
    expect(getByText('Accept Me')).toBeTruthy();
    expect(getByText('Decline Me')).toBeTruthy();
  });
  test('Hide on accept', () => {
    const { container, getByText } = renderComponent();
    const btn = getByText('Accept Me');
    fireEvent.click(btn);
    expect(container.querySelector('div.cookieConsent')).not.toHaveClass('show');
    expect(Boolean(getCookie('CookieConsent'))).toBe(true);
  });
});
afterEach(() => {
  cleanup();
  document.cookie = `CookieConsent=; expires=Thu, 01 Jan 1970 00:00:00; path=/`;
  sessionStorage.removeItem('CookieConsentDecline');
});
