import { i18n } from './i18n.js'
import { auth } from './services/auth.js'
import { favoritesService } from './services/favorites.js'
import { notificationsService } from './services/notifications.js'
import { setupGlobalErrorHandler } from './components/error-boundary.js'

async function initApp() {
    // Setup global error handling first
    setupGlobalErrorHandler()

    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
        document.documentElement.dataset.theme = savedTheme
    }

    await i18n.init()
    
    // Restore auth session before loading components
    await auth.tryRestoreSession()
    favoritesService.init()
    notificationsService.init()

    auth.subscribe((loggedIn) => {
        if (loggedIn) {
            notificationsService.init()
        } else {
            notificationsService.destroy()
        }
    })

    await import('./components/app-shell.js')
    
    document.getElementById('app').innerHTML = '<app-shell></app-shell>'

    if ('serviceWorker' in navigator) {
        try {
            const registration = await navigator.serviceWorker.register('/service-worker.js')
            console.log('SW registered:', registration.scope)
        } catch (error) {
            console.log('SW registration failed:', error)
        }
    }
}

initApp()
