import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

let root: ReactDOM.Root | null = null

function render(props: any = {}) {
  const { container } = props
  const target = container ? container.querySelector('#root') : document.getElementById('root')
  root = ReactDOM.createRoot(target!)
  root.render(
    <React.StrictMode>
      <App qiankunProps={props} />
    </React.StrictMode>
  )
}

renderWithQiankun({
  mount(props) {
    console.log('sub-react mount')
    render(props)
  },
  bootstrap() {
    console.log('sub-react bootstrap')
  },
  unmount() {
    console.log('sub-react unmount')
    root?.unmount()
    root = null
  },
  update() {
    console.log('sub-react update')
  }
})

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render()
}
