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

import { getExtraField, imagePrettyUrl, getBonus } from 'gatsby-core-theme/src/helpers/getters';
import MainProvider from '~context/MainProvider';
import getPageData from '../../../../../../../tests/factories/pages/default.factory';
import TemplateTwo from '.';

const translations = {
  claim_reward: 'Claim Rewards',
  welcome_bonus: 'Welcome Bonus',
};

function renderComponent(pageData) {
  return render(
    <MainProvider
      value={{
        cookieAccepted: true,
        translations,
      }}
    >
      <TemplateTwo extraFields={pageData.extra_fields} imageObj={pageData.featured_image_object} />
    </MainProvider>
  );
}

let data;

beforeEach(() => {
  data = getPageData();
});
describe('Show template two', () => {
  test('render without featured image', () => {
    data.featured_image_object = null;

    // eslint-disable-next-line global-require
    const func = require('gatsby-core-theme/src/helpers/device-detect');
    func.isNativeImageLazyLoadingSupported = jest.fn(() => true);

    const { container } = renderComponent(data);
    expect(container.querySelector('img')).toBeFalsy();
    expect(container.querySelector('.blendColors')).toBeInTheDocument();
  });
  test('show correct oneLiner', () => {
    const { container } = renderComponent(data);
    expect(container.querySelector('.headerContainer').querySelector('h1')).toBeInTheDocument();
    expect(container.querySelector('.headerContainer').querySelector('h1').innerHTML).toBe(
      getBonus('main', getExtraField(data?.extra_fields, 'operator'))
        .one_liner.replace('+', '&')
        .replace('&', '&amp;')
    );
  });
  test('show correct url', () => {
    const { container } = renderComponent(data);
    expect(
      container.querySelector('.headerContainer').querySelector('a').innerHTML.split('<svg')[0]
    ).toEqual(getExtraField(data?.extra_fields, 'link'));
  });
  test('show correct image', () => {
    const imgObj = data.featured_image_object;

    // eslint-disable-next-line global-require
    const func = require('gatsby-core-theme/src/helpers/device-detect');
    func.isNativeImageLazyLoadingSupported = jest.fn(() => true);
    const { container } = renderComponent(data);

    expect(container.querySelector('img')).toHaveAttribute(
      'src',
      imagePrettyUrl(imgObj.filename, imgObj.width, imgObj.height)
    );
    expect(container.querySelector('img')).toHaveAttribute('loading', 'eager');
  });
  test('show correct tcn', () => {
    const { container } = renderComponent(data);
    expect(container.querySelector('.tnc').innerHTML).toBe(
      '18+ New Players only. Play responsibly.'
    );
  });
});
afterEach(() => {
  cleanup();
});
