<script>
    import { onMount } from 'svelte'
    import Hero from "./components/Hero/Hero.svelte";
    import Services from "./components/Services/Services.svelte";
    import Footer from "./components/Footer/Footer.svelte";
    import Header from "./components/Header/Header.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";

    let pathname = '/'

    const normalizePath = (path) => {
        if (!path) return '/'
        const trimmed = path.trim()
        return trimmed.endsWith('/') && trimmed.length > 1
            ? trimmed.slice(0, -1)
            : trimmed
    }

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

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

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

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

        pathname = window.location.pathname

        const handlePopstate = () => {
            pathname = window.location.pathname
        }

        window.addEventListener('popstate', handlePopstate)
        return () => window.removeEventListener('popstate', handlePopstate)
    })
</script>

<div class="app">
    <Header />
    <main class:center-content={isCenteredMain}>
        {#if currentRoute === 'home'}
            <Hero />
            <Services />
        {: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 />
</div>