import { router } from '../router.js'
import { i18n } from '../i18n.js'
import { auth } from '../services/auth.js'
import './app-header.js'
import './app-footer.js'

class AppShell extends HTMLElement {
    constructor() {
        super()
        this.main = null
    }

    connectedCallback() {
        if (!this.querySelector('#router-outlet')) {
            this.innerHTML = /* html */`
                <app-header></app-header>
                <main class="container" id="router-outlet"></main>
                <app-footer></app-footer>
                <div id="auth-modal-slot"></div>
            `
        }
        this.main = this.querySelector('#router-outlet')
        this.setupRouter()
        this.loadAuthModal()
        
        i18n.subscribe(() => {
            this.querySelector('app-header').updateTranslations()
            this.querySelector('app-footer').updateTranslations()
        })
    }

    async loadAuthModal() {
        await import('./auth-modal.js')
        this.querySelector('#auth-modal-slot').innerHTML = '<auth-modal hidden></auth-modal>'
    }

    setupRouter() {
        router.setOutlet(this.main)
        
        const lazy = (path) => () => import(path)

        router.setNotFoundLoader(lazy('./pages/page-not-found.js'))
        router
            .register('/', 'page-home', lazy('./pages/page-home.js'))
            .register('/search', 'page-home', lazy('./pages/page-home.js'))
            .register('/listing/:id', 'page-listing', lazy('./pages/page-listing.js'))
            .register('/create', 'page-create', lazy('./pages/page-create.js'))
            .register('/edit/:id', 'page-create', lazy('./pages/page-create.js'))
            .register('/favorites', 'page-favorites', lazy('./pages/page-favorites.js'))
            .register('/my-listings', 'page-my-listings', lazy('./pages/page-my-listings.js'))
            .register('/messages', 'page-messages', lazy('./pages/page-messages.js'))
            .register('/settings', 'page-settings', lazy('./pages/page-settings.js'))
            .register('/notifications', 'page-notifications', lazy('./pages/page-notifications.js'))
            .register('/privacy', 'page-privacy', lazy('./pages/page-privacy.js'))
            .register('/terms', 'page-terms', lazy('./pages/page-terms.js'))
            .register('/about', 'page-about', lazy('./pages/page-about.js'))
            .register('/contact', 'page-contact', lazy('./pages/page-contact.js'))
            .register('/imprint', 'page-imprint', lazy('./pages/page-imprint.js'))
        
        router.handleRouteChange()
    }
}

customElements.define('app-shell', AppShell)
