/* eslint-disable react/display-name */
import React from 'react';
import ReactDOM from 'react-dom/client';
import i18next from 'i18next'
import { i18nextReactInitConfig } from '@brojs/cli';

import App from './app';
import { keycloak } from "./__data__/kc";
import { createStore } from "./__data__/store";

i18next.t = i18next.t.bind(i18next)
const i18nextPromise = i18nextReactInitConfig(i18next)

if(!module.hot) {
  import('./ym');
}

export default (props) => <App {...props} />;
  
let rootElement: ReactDOM.Root
  
export const mount = async (Component, element = document.getElementById('app')) => {
  let user = null;
  try {
    await keycloak.init({ onLoad: 'login-required' })

    const userInfo = await keycloak.loadUserInfo()

    if (userInfo && keycloak.tokenParsed) {
      user = { ...userInfo, ...keycloak.tokenParsed }
    } else {
      console.error('No userInfo or tokenParsed', userInfo, keycloak.tokenParsed)
    }
  } catch (error) {
    console.error('Failed to initialize adapter:', error)
    keycloak.login()
  }
  const store = createStore({ user });
  await i18nextPromise

  rootElement = ReactDOM.createRoot(element);
  rootElement.render(<Component store={store} />);

  if(module.hot) {
      module.hot.accept('./app', ()=> {
        rootElement.render(<Component store={store} />);
      })
  }
};

export const unmount = () => {
  rootElement.unmount();
};
