import React, { lazy, Suspense } from 'react'
import { render } from 'react-dom'

import { initRequestConfiguration } from 'utils/request'
import {
  createShadowDom,
  initializeTagManager,
  setLocales,
  setToken
} from 'startup/utils'
import handleFederatedApp from 'utils/federatedApp'

import 'config/requestRegister'

const App = lazy(() => import('startup/umd/app'))
const Root = () => {
  return (
    <div id={process.env.PROJECT_NAME}>
      <Suspense fallback={null}>
        <App />
      </Suspense>
    </div>
  )
}

const renderApp = async (rootElement: any, {
  baseUrl = '/',
  lang,
  token
}) => {
  // eslint-disable-next-line camelcase
  __webpack_public_path__ = baseUrl
  const { setAppRoot } = handleFederatedApp()

  const shadowRoot = createShadowDom(rootElement)

  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  setAppRoot(process.env.PROJECT_NAME!, shadowRoot)

  if (!token) {
    throw new Error('Missing valid token param')
  }

  await setLocales(lang)
  setToken(token)
  initRequestConfiguration(token)
  initializeTagManager()

  render(<Root />, shadowRoot)
}

export default renderApp
