<script>
    import { onMount } from 'svelte'
    import Footer from "./components/Footer/Footer.svelte";
    import Header from "./components/Header/Header.svelte";
    import CookiePopUp from "./components/CookiePopUp/CookiePopUp.svelte";
    import IndexPage from "./pages/index.svelte";
    import Contacts from "./pages/contacts.svelte";
    import Forbidden from "./pages/403.svelte";
    import ServerError from "./pages/500.svelte";
    import ErrorGeneric from "./pages/errore.svelte";
    import NotFound from "./pages/404.svelte";
    import { initializeStoredConsent } from "./lib/cookieConsent";
    import { applyTheme, getSavedTheme } from "./lib/theme";
    import { getErrorPath, resolvePathname } from "./lib/errorRouting";
    import { navigateTo } from "./lib/navigation";

    let pathname = $state(typeof window !== 'undefined' ? window.location.pathname : '/')

    const getRoute = (path) => {
        const normalized = resolvePathname(path)

        if (normalized === '/') return 'home'
        if (normalized === '/contatti' || normalized === '/contacts') return 'contacts'
        if (normalized === '/403') return '403'
        if (normalized === '/404') return '404'
        if (normalized === '/500') return '500'
        if (normalized === '/errore') return 'error'
        return '404'
    }

    let currentRoute = $derived(getRoute(pathname))
    let isCenteredMain = $derived(['403', '404', '500', 'error'].includes(currentRoute))

    const syncRouteFromLocation = () => {
        const resolved = resolvePathname(window.location.pathname)
        if (resolved !== window.location.pathname) {
            window.history.replaceState({}, '', resolved)
        }
        pathname = resolved
    }

    onMount(() => {
        console.log("Svelte App.svelte mounted!");
        console.log("Current pathname:", pathname);
        console.log("Current route:", currentRoute);
        initializeStoredConsent()

        try {
            const saved = getSavedTheme()
            if (saved) {
                applyTheme(saved)
            } else {
                const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
                const theme = prefersDark ? 'dark' : 'light'
                applyTheme(theme)
            }
        } catch (e) {
            document.documentElement.setAttribute('data-theme', 'light')
        }

        syncRouteFromLocation()

        const handlePopstate = () => {
            syncRouteFromLocation()
        }

        const handleErrorRedirect = (event) => {
            const code = event?.detail?.code ?? event?.detail?.status
            navigateTo(getErrorPath(code))
        }

        window.addEventListener('popstate', handlePopstate)
        window.addEventListener('app:error-redirect', handleErrorRedirect)
        return () => {
            window.removeEventListener('popstate', handlePopstate)
            window.removeEventListener('app:error-redirect', handleErrorRedirect)
        }
    })
</script>

<div class="app">
    <Header />
    <main class:center-content={isCenteredMain}>
        {#if currentRoute === 'home'}
            <IndexPage />
        {:else if currentRoute === 'contacts'}
            <Contacts />
        {:else if currentRoute === '403'}
            <Forbidden />
        {:else if currentRoute === '500'}
            <ServerError />
        {:else if currentRoute === 'error'}
            <ErrorGeneric />
        {:else}
            <NotFound />
        {/if}
    </main>
    <Footer />
    <CookiePopUp />
</div>