import App from "./App.vue"
import { createApp, type App as VueApp } from "vue"
import initI18n from "./setup/i18n"
import initVuetify from "./setup/vuetify"
import router from "./router"
import "./assets/styles/main.scss"
import "./assets/styles/tailwindStyles.css"
import "./assets/styles/vuetifyStyles.scss"
import { orchestratorPlugins } from "@racletteCore/setup/plugin-system"
import DefaultLoginApp from "./LoginApp.vue"
import log from "@racletteCore/lib/logger"
import { initPluginRegistration } from "@racletteCore/main"
let loginVueApp: VueApp<Element> | undefined

export const createVueApp = async (el: string): Promise<VueApp> => {
  if (loginVueApp) {
    loginVueApp.unmount()
    loginVueApp = undefined
  }

  const vueApp = createApp(App)
  const { i18nInstance, instanceAdapter, dateLocale } = await initI18n()
  await initPluginRegistration()
  const vuetify = initVuetify(instanceAdapter, dateLocale)
  vueApp.use(i18nInstance)
  vueApp.use(vuetify)
  vueApp.use(router)

  if (orchestratorPlugins.length) {
    log.orchestrator("raclette-vue will use vue plugin", orchestratorPlugins)
    orchestratorPlugins.forEach((plugin) =>
      vueApp.use(plugin.dependency, plugin.options),
    )
  }

  vueApp.mount(el)
  return vueApp
}

export const createLoginVueApp = async (
  el: string,
  loginMethod: Function,
  noUsers: boolean,
): Promise<VueApp> => {
  const vueApp = createApp(DefaultLoginApp, { loginMethod, noUsers })

  const { i18nInstance, instanceAdapter, dateLocale } = await initI18n()
  vueApp.use(i18nInstance)

  const vuetify = initVuetify(instanceAdapter, dateLocale)
  vueApp.use(vuetify)

  vueApp.mount(el)

  loginVueApp = vueApp
  return vueApp
}

export default {
  createVueApp,
  createLoginVueApp,
}
