/* eslint-disable no-lone-blocks */
/* eslint-disable no-unused-expressions */
import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import PrettyLink from '.';

const data = (activeStatus = 'active') => ({
  operator: {
    status: activeStatus,
    links: {
      main: 'https://www.google.com',
    },
    short_name: 'operator',
  },
  pageTemplate: 'default',
  tracker: 'main',
  children: <h1>Test children</h1>,
});

describe('PrettyLink Component', () => {
  test('PrettyLink children and link', () => {
    const { getByText, container } = render(<PrettyLink {...data()} />);
    expect(getByText('Test children')).toBeTruthy();
    expect(container.querySelector('a').getAttribute('href')).toEqual('/no/visit/operator');
  });

  test('Affiliate object in cookie', () => {
    window = Object.create(window);
    const url = 'http://test.com/?fbclid=param1&msclkid=param2&gclid=param3';
    Object.defineProperty(window, 'location', {
      value: {
        href: url,
      },
      writable: true, // possibility to override
    });
    const { container } = render(
      <PrettyLink
        {...data()}
        pageTemplate="test"
        module="test2"
        tracker="testing"
        clickedElement="cta"
      />
    );
    const button = container.querySelector('a');
    fireEvent.click(button);
    const affObject = JSON.parse(document.cookie.split('=')[1]);
    expect(affObject.page_type).toEqual('test');
    expect(affObject.module).toEqual('test2');
    expect(affObject.request_url).toEqual('http://test.com/');
    expect(affObject.facebook_click_id).toEqual('param1');
    expect(affObject.microsoft_click_id).toEqual('param2');
    expect(affObject.google_click_id).toEqual('param3');
    expect(affObject.tracker_name).toEqual('testing');
    expect(affObject.clicked_element).toEqual('cta');
  });

  test('Default Affiliate object in cookie', () => {
    window = Object.create(window);
    const url = 'http://testdomain.com/';
    Object.defineProperty(window, 'location', {
      value: {
        href: url,
      },
      writable: true, // possibility to override
    });
    const { container } = render(<PrettyLink {...data()} />);
    const button = container.querySelector('a');
    fireEvent.click(button);
    const affObject = JSON.parse(document.cookie.split('=')[1]);
    expect(affObject.page_type).toEqual('default');
    expect(affObject.request_url).toEqual('http://testdomain.com/');
  });
});

afterEach(() => {
  cleanup();
});
