// This test in written using React Testing library. Written during setting up this library to make sure tests are working.
import React from 'react';
import { injectIntl } from 'react-intl';
import '@testing-library/jest-dom';
import { screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import cloneDeep from 'lodash/cloneDeep';
import { configureStore } from '@capillarytech/vulcan-react-sdk/utils';
import history  from '../../../utils/history';
import { initialReducer } from '../../../initialReducer';
import { render } from '../../../utils/test-utils';
import { Cap } from '../index';
import mockData from '../../mockdata';
import { Router } from 'express';
const {
  demoVideoAndLinkJSONData,
  // history,
  location,
  match,
  Global,
} = mockData;

const ComponentToRender = injectIntl(Cap);

const renderComponent = (props) => {
  const store = configureStore({}, initialReducer, history);
return  render(
    <Provider store={store}>
      <Router history={history}>
       <ComponentToRender {...props} />
       </Router>
    </Provider>,
  );
};

jest.setTimeout(15000);
jest.mock('@capillarytech/cap-ui-utils', () => ({
  ...jest.requireActual('@capillarytech/cap-ui-utils'),
  GA: {
    initialize: jest.fn(),
    timeTracker: {
      stopTimer: jest.fn(),
      startTimer: jest.fn(),
    },
    setCustomDimension: jest.fn(),
    getCallerName: jest.fn(),
  },
  Auth: {
    hasAccess: () => jest.fn(() => true),
    hasFeatureAccess: () => jest.fn(() => true),
    authHoc: jest.fn(),
    initialize: jest.fn(),
  },
  multipleOrgSwitch: {
    logNewTab: jest.fn(),
    utilsGetOrgNameFromId: () => 'org2',
    tabBeforeUnloadEventHandler: jest.fn(),
    utilsHandleStorageChange: () => jest.fn(() => true),
    isMultipleTabsOpen: () => jest.fn(() => true),
  },
  utilsSessionStorageApi: {
    loadSessionItem: () => true,
    saveSessionItem: jest.fn(),
  },
}));

// jest.mock('../../../components/NavigationBar');

jest.mock('@capillarytech/cap-ui-library/CapSupportVideosWrapper', () => {
  const ChildComponent = (props) => {
    const { targetElements } = props;
    const DEMO_LABEL =
      targetElements[Object.keys(targetElements)[1]]?.support_video?.target_url
        ?.default?.label;
    return <h4>{DEMO_LABEL}</h4>;
  };
  return ChildComponent;
});

describe('Cap', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  const actions = {
    authenticate: jest.fn(),
    addMessageToQueue: jest.fn(),
    changeOrg: jest.fn(),
    changeOu: jest.fn(),
    changeOuFailure: jest.fn(),
    changeOuSuccess: jest.fn(),
    fetchMenuSearchResults: jest.fn(),
    clearTopbarMenuData: jest.fn(),
    getAllUsers: jest.fn(),
    getStartOfWeekForOrg: jest.fn(),
    getTopbarMenuData: jest.fn(),
    getUserData: jest.fn(),
    loginSuccess: jest.fn(),
    logout: jest.fn(),
    removeMessageFromQueue: jest.fn(),
    setActiveReportStatus: jest.fn(),
    getSupportedLocales: jest.fn(),
    getSupportVideosConfig: jest.fn(),
  };

  // Assign the mock window object to the global object
  const originalLocation = window.location;
  delete window.location;
  window.location = { ...originalLocation, pathname: '/creatives/ui/v2' };

  const props = {
    demoVideoAndLinkJSONData,
    history,
    location: { ...location, query: { type: '' }},
    match,
    Global,
    actions,
    appActions: {
      getSidebar: jest.fn(),
    },
    loader: { localeLoading: false },
    intl: { formatMessage: jest.fn() },
  };

  const mockReplaceDynamicAndCompare = () => {
    // Mocking replaceDynamicAndCompare function to get the currentPathJSON
    jest.mock(
      '@capillarytech/cap-ui-library/CapSupportVideosWrapper/utils',
      () => ({
        replaceDynamicAndCompare: jest.fn((pathname, route) => {
          if (pathname === '/creatives/ui/v2') {
            return {
              target_elements: { element1: 'video1', element2: 'video2' },
            };
          }
          return null;
        }),
      }),
    );
  };

  const { findByText, queryByText } = screen;


  it('Should not show Demo text for video support if targetELements not found', async () => {
    mockReplaceDynamicAndCompare();
    const updatedProps = cloneDeep(props);
    delete updatedProps.demoVideoAndLinkJSONData.demoVideoAndLinkJSON
      .json_config?.[0]?.target_elements;
    renderComponent(updatedProps);
    expect(queryByText(/Demo/i)).toBeNull();
  });
});
