<script lang="ts">
    import '../style/global.scss'

    import { browser } from '$app/env'
    import { navigating, page } from '$app/stores'
    import { beforeNavigate } from '$app/navigation'
    import type { PageData } from './$types'
    import { onMount, setContext } from 'svelte'
    import { pageLoading, previousPage } from '$utils/stores'
    import { DURATION } from '$utils/contants'
    import '$utils/polyfills'
    import { PUBLIC_ANALYTICS_KEY, PUBLIC_ANALYTICS_URL } from '$env/static/public'
    // Components
    import SVGSprite from '$components/SVGSprite.svelte'
    import SmoothScroll from '$components/SmoothScroll.svelte'
    import Analytics from '$components/Analytics.svelte'
    import Switcher from '$components/molecules/Switcher.svelte'
    import Footer from '$components/organisms/Footer.svelte'

    export let data: PageData


    // Fonts to preload
    const fonts = [
        'G-Light',
        'G-Regular',
        'G-Medium',
        'G-Semibold',
        'J-Extralight',
        'J-Light',
    ]

    // Set global data
    setContext('global', data)


    /**
     * On page change
     */
    // Store previous page (for photo Viewer close button)
    beforeNavigate(({ from }) => {
        $previousPage = from.pathname
    })

    // Define page loading from navigating store
    navigating.subscribe((store: any) => {
        if (store) {
            $pageLoading = true

            // Turn page loading when changing page
            setTimeout(() => {
                $pageLoading = false
            }, DURATION.PAGE_IN * 1.25)
        }
    })

    onMount(() => {
        // Avoid FOUC
        document.body.style.opacity = '1'
    })
</script>

<svelte:head>
    {#each fonts as font}
        <link rel="preload" href="/fonts/{font}.woff2" as="font" type="font/woff2" crossorigin="anonymous">
    {/each}
</svelte:head>


<Switcher isOver={!!$page.params.location && !!$page.params.photo} />

<slot />

{#if !$page.params.photo}
    <Footer />
{/if}

{#if $pageLoading}
    <div class="page-loading" />
{/if}

<SVGSprite />
<SmoothScroll />

{#if browser}
    <Analytics
        appKey={PUBLIC_ANALYTICS_KEY}
        url={PUBLIC_ANALYTICS_URL}
    />
{/if}