import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from '../App.vue'

import naive from 'naive-ui'

import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'

import '../assets/styles/main.css'
import '@fortawesome/fontawesome-free/css/all.min.css'

import { useAuthStore } from '../shared/stores/auth'
import { useToolsStore } from '../shared/stores/tools'
import { usePermissionStore } from '../shared/stores/permissions'
import { useRealtimeStore } from '../shared/stores/realtime'
import { initSlugMapping } from '../shared/utils/slug'
import '../shared/utils/axiosConfig'
import '../shared/utils/fetchInterceptor'
import { loadTranslationsFromBackend } from '../shared/i18n'
import { loadAppExtensions } from '../shared/extensions'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)
app.use(naive)

async function bootstrap() {
  const authStore = useAuthStore()
  await authStore.initAuth()
  
  // Initialize slug -> PageType mapping from user's can_read list
  if (authStore.user?.can_read?.length) {
    initSlugMapping(authStore.user.can_read)
  }

  if (authStore.isLoggedIn) {
    await loadTranslationsFromBackend()
    await loadAppExtensions()
  }

  const toolsStore = useToolsStore()
  toolsStore.initToolRoutes(router)

  if (authStore.isLoggedIn) {
    const permissionStore = usePermissionStore()
    await permissionStore.loadPermissions().catch(() => {})

    // Initialize realtime connection for logged-in users
    const realtimeStore = useRealtimeStore()
    realtimeStore.init()
  }

  app.mount('#app')
}

bootstrap()
