import { createApp } from 'vue'
import { i18next, I18NextVue } from './i18n'
import router from './router'
import { db } from './db/database.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)

// Initialize database (before mount so App.vue can subscribe to the promise)
const dbReady = db
  .init()
  .then(async (info) => {
    console.log('Database initialized:', info)

    // Apply persisted settings before first render
    const lang = await settingsRepository.get('language')
    if (lang) {
      i18next.changeLanguage(lang)
    }
    const theme = await settingsRepository.get('theme')
    if (theme) {
      document.documentElement.setAttribute('data-theme', theme)
    }

    if (db.migrationPending) {
      // App stays paused: App.vue shows the blocking migration screen
      document.documentElement.setAttribute('data-db-migration', 'pending')
      return { migrationPending: db.migrationPending }
    }

    document.documentElement.setAttribute('data-db-ready', 'true')
    return {}
  })
  .catch((err) => {
    console.error('Database initialization failed:', err)
    document.documentElement.setAttribute('data-db-error', err.message)
    throw err
  })

// 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')
