import './assets/main.css'
// Icon webfont: menu entries arrive from the API as arbitrary `mdi-*` names,
// so the full font is loaded rather than a tree-shaken subset.
import '@mdi/font/css/materialdesignicons.min.css'

import { createPinia } from 'pinia'
import { createApp } from 'vue'

import App from './App.vue'
import { i18n } from './i18n'
import router from './router'
import { setErrorNotifier, setSessionExpiredHandler } from './services/http'
import { useAuthStore } from './stores/auth'
import { useUiStore } from './stores/ui'
import { useUserStore } from './stores/user'

const app = createApp(App)

app.use(createPinia())
app.use(i18n)

// Wire the HTTP layer to the app *after* Pinia exists but *before* the router,
// so the very first navigation already reports errors properly.
const ui = useUiStore()
const auth = useAuthStore()
const user = useUserStore()

// Every failed request becomes a red toast unless it opted out via meta.silent.
setErrorNotifier((error) => ui.notifyApiError(error))

// The refresh flow gave up: drop the session and send the visitor to the login
// page, keeping where they were so they can come back after signing in.
setSessionExpiredHandler(async () => {
  auth.clearSession()
  user.clear()
  const current = router.currentRoute.value
  if (current.name !== 'login') {
    await router.push({ name: 'login', query: { redirect: current.fullPath } })
  }
})

app.use(router)

// Keep <html lang> aligned with the initial locale for a11y and SEO.
document.documentElement.setAttribute('lang', i18n.global.locale.value)

app.mount('#app')
