import { createApp } from 'vue'
import { i18next, I18NextVue } from './i18n'
import router from './router'
import { db } from './db/database.js'
import { bootstrapDatabase } from './db/bootstrap.js'
import { settingsRepository } from './db/repositories/settingsRepository.js'
import { exerciseRepository } from './db/repositories/exerciseRepository.js'
import { comboRepository } from './db/repositories/comboRepository.js'
import { sessionRepository } from './db/repositories/sessionRepository.js'
import { collectionRepository } from './db/repositories/collectionRepository.js'
import { executionLogRepository } from './db/repositories/executionLogRepository.js'
import { suffixRepository } from './db/repositories/suffixRepository.js'
import 'bootstrap-icons/font/bootstrap-icons.css'
import './styles/variables.css'
import './styles/layout.css'
import App from './App.vue'

const app = createApp(App)
app.use(I18NextVue, { i18next })
app.use(router)

// Ask the browser to exempt this origin's storage (OPFS database, PWA
// precache — including the icon font) from automatic eviction after long
// periods of inactivity. Fire-and-forget: the app works either way, denial
// just leaves storage best-effort.
if (navigator.storage?.persist) {
  navigator.storage
    .persist()
    .then((granted) => console.log('Persistent storage:', granted ? 'granted' : 'not granted'))
    .catch(() => {})
}

// Initialize database (before mount so App.vue can subscribe to the promise).
// The sequence lives in bootstrapDatabase() so App.vue can rerun it from the
// Retry button after a failed first load.
const dbReady = bootstrapDatabase()

// Expose for testing
window.__db = db
window.__dbReady = dbReady
window.__repos = {
  settings: settingsRepository,
  exercises: exerciseRepository,
  combos: comboRepository,
  sessions: sessionRepository,
  collections: collectionRepository,
  executionLogs: executionLogRepository,
  suffixes: suffixRepository,
}

app.mount('#app')
