import * as React from 'react';
import {ModalContainer} from '../index';
import {act, fireEvent, render} from '../../test-utils';



describe('ModalContainer', () => {

  let mountingDiv: HTMLElement;
  const scrollToSpy = jest.fn();

  beforeEach(() => {
    //being rendered as a React.Portal we need to have the 'root' div defined
    mountingDiv = document.createElement('div');
    mountingDiv.id = 'root';
    document.body.appendChild(mountingDiv);
    window.scrollTo = scrollToSpy;
    document.body.style.position = '';
    document.body.style.left = '';
    document.body.style.top = '';
    document.body.style.right = '';

  });

  afterEach(() => {
    document.body.removeChild(mountingDiv);
    scrollToSpy.mockReset();
  });

  it('should not render content', () => {
    const wrapper = render(<ModalContainer showModal={false} closeModal={jest.fn()} children={'text'}/>);

    expect(wrapper.queryByText('text')).not.toBeInTheDocument();
  });

  it('should render children inside react modal', () => {
    const wrapper = render(<ModalContainer showModal={true} closeModal={jest.fn()} children={'text'}/>);

    expect(wrapper.queryByText('text')).toBeInTheDocument();
  });

  it('should call onClose when react modal closes', () => {
    const onClose = jest.fn();
    const wrapper = render(<ModalContainer showModal={true} closeModal={onClose} children={'text'}/>);

    act(() => {
      fireEvent.click(document.querySelector('.ReactModal__Overlay')!);
    });

    expect(onClose).toHaveBeenCalled();
  });

  it('should append custom styles when modal is mounted', () => {
    const wrapper = render(<ModalContainer showModal={false} closeModal={jest.fn()} children={'text'}/>);

    expect(document.querySelectorAll('[modal-custom-styling="active"]')).toHaveLength(1);
  });

  it('should prevent scroll when modal is open', () => {
    Object.defineProperty(window, 'scrollY', {value: 5, writable: true});

    const wrapper = render(<ModalContainer showModal={true} closeModal={jest.fn()} children={'text'}/>);

    expect(document.body.style.top).toEqual('-5px');
    expect(document.body.style.position).toEqual('fixed');
  });

  it('should not touch scroll if modal was not opened yet', async () => {
    Object.defineProperty(window, 'scrollY', {value: 5, writable: true});

    const wrapper = render(<ModalContainer showModal={false} closeModal={jest.fn()} children={'text'}/>);

    expect(document.body.style.top).toBeFalsy();
    expect(document.body.style.position).toBeFalsy();
  });

});
