import 'babel-polyfill';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
// import createHistory from 'history/lib/createBrowserHistory';
// import { applyRouterMiddleware, Router, useRouterHistory } from 'react-router';
// import { useScroll } from 'react-router-scroll';
import history from 'utils/history';
import CapSomethingWentWrong from '@capillarytech/cap-ui-library/CapSomethingWentWrong';
import { addLocizeSavedHandler, startStandalone } from 'locize';
import Bugsnag from '@bugsnag/js';
import BugsnagPluginReact from '@bugsnag/plugin-react';
// import { makeSelectLocationState } from 'containers/Cap/selectors';
import LanguageProvider from 'v2Containers/LanguageProvider';
import FontFaceObserver from 'fontfaceobserver';
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
/* eslint-enable import/no-unresolved, import/extensions */
import { configureStore }  from '@capillarytech/vulcan-react-sdk/utils';
import { initialReducer } from './initialReducer';
import { translationMessages } from './i18n';
import './global-styles';
import initialState from './initialState';
import './styles/vendor/semantic/dist/semantic.min.css';
import './styles/main.scss';
import pathConfig from './config/path';
import ignoredErrorMessages from './utils/ignoredErrorMessages';
import App from './containers/App';

try {
  const { setupNewrelicWebVitals } = require('./newRelic/utils'); 
  // Setup New Relic WebVitals tracking
  setupNewrelicWebVitals();
} catch (error) {
  Bugsnag.notify(error);
}

// const browserHistory = useRouterHistory(createHistory)({
//   basename: pathConfig.publicPath,
// });

const store = configureStore(initialState, initialReducer, history);
const MOUNT_NODE = document.getElementById('app');

// const history = syncHistoryWithStore(browserHistory, store, {
//   selectLocationState: makeSelectLocationState(),
// });
const BUGSNAG_APP_VERSION = `creatives-ui__${new Date().getTime()}`;
const BUGSNAG_API_KEY = 'c4d96446438ff7dc7c08da08ef94c5b2';

const bugSnagErrorCallback = (event) => {
  const { app: { releaseStage } = {}, originalError } = event || {};
  const errorMessage = originalError && originalError.message;
  if (
    (releaseStage || '').includes('nightly') ||
    process.env.NODE_ENV !== 'production' ||
    ignoredErrorMessages.includes(errorMessage)
  ) {
    return false;
  }
  let userId;
  let userName;
  let userEmail;
  let orgId;
  let orgName;
  try {
    const {
      id,
      firstName,
      lastName,
      loginName,
      proxyOrgList,
    } = JSON.parse(window.localStorage.getItem('user'));
    orgId = window.localStorage.getItem('orgID');
    userId = id;
    userName = `${firstName} ${lastName}`;
    userEmail = loginName;
    orgName = proxyOrgList.find(({ orgID }) => orgID === Number(orgId)).orgName;
  } catch (error) {
    userId = '';
    userName = '';
    userEmail = '';
    orgId = '';
    orgName = '';
  }
  event.addMetadata('org', {
    name: orgName,
    id: orgId,
  });
  event.setUser(userId, userEmail, userName);
  if (window.FS && window.FS.getCurrentSessionURL) {
    event.addMetadata('fullstory', {
      urlAtTime: window.FS.getCurrentSessionURL(true),
    });
  }
};

Bugsnag.start({
  appVersion: BUGSNAG_APP_VERSION,
  apiKey: BUGSNAG_API_KEY,
  releaseStage: window.location.hostname,
  plugins: [new BugsnagPluginReact()],
  onError: bugSnagErrorCallback,
});

const ErrorBoundary = Bugsnag.getPlugin('react').createErrorBoundary(React);

export const BugsnagClient = Bugsnag;

const ErrorScreen = () => <CapSomethingWentWrong url={`${pathConfig.publicPath}/v2`} />
const root = createRoot(MOUNT_NODE);
const render = (messages) => {
  root.render(
    <Provider store={store}>
        <LanguageProvider messages={messages}>
          <ErrorBoundary FallbackComponent={ErrorScreen}>
            <App />
          </ErrorBoundary>
        </LanguageProvider>
    </Provider>,
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// for auto render UI on locize saved, since we cache the translations in redis it can't be update on real time as of now
// need to comment as of now
// addLocizeSavedHandler(res => {
//   res.updated.forEach(item => {
//     const { lng, ns, key, data } = item
//     // load the translations somewhere...
//     // and maybe rerender your UI
//   })
// })

// start
startStandalone();

const openSansObserver = new FontFaceObserver('Roboto', {});
// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}
