import { app } from '@/main'
import { genMount } from './mount'
import LocaleEnv from '@/components/locale-env/index.vue'
import { getCurrentInstance, h, onDeactivated, onUnmounted, watch } from 'vue'
import { router } from '@/router'

export const mount = genMount(app)

export const renderCompoent = <P>(comp: ComponentConstructor<P>, props: P) => {
  const element = document.createElement('div')
  const { destroy } = mount(LocaleEnv, {
    element,
    children: { default: () => h(comp as any, props as any) }
  })
  // const { destroy } = mount(comp, { props, element })
  return () => {
    destroy()
    if (document.body.contains(element)) {
      document.body.removeChild(element)
    }
  }
}

export const renderModal = <P>(
  comp: ComponentConstructor<P>,
  propsRaw: Omit<P, 'onCancel'>
) => {
  const props = {
    ...propsRaw,
    onCancel: () => {
      destroy && destroy()
    }
  } as P
  const destroy = renderCompoent(comp, props)

  watch(
    () => router.currentRoute.value?.name,
    () => {
      destroy()
    }
  )

  if (getCurrentInstance()) {
    onUnmounted(destroy)
    onDeactivated(destroy)
  }
}
