<script>
    import { stores } from '@sapper/app'
    import { pageReady, animDurationLong, pageTransition } from './store'
    const { page } = stores()

    // Components
    import TitleSite from '../atoms/TitleSite'
    import IconGlobe from '../atoms/IconGlobe'

    // Animations
    import { animateIn, animateOut } from '../animations/Transition'


    /*
    ** PAGE LOADING PROCESS
    ** 1. Set pageReady to false
    ** 1. Runs the Loader transition In
    ** ?. The next page changes the value of pageReady when mounted (or later)
    ** 2. The Loader detects the value change of pageReady
    ** 3. Hide the loader with transition Out
    ** 4. The Loader runs the page transition In via pageTransition
    */
    let firstLoad = true

    // 1. Watch page change
    page.subscribe(() => {
        // Run the loader animation (only after first load)
        if (!firstLoad && process.browser) {
            animateIn()
        }
        // Set pageReady to false (?)
        pageReady.set(false)
    })

    // 2. Watch when loaded changes
    pageReady.subscribe(loaded => {
        if (loaded) {
            setTimeout(() => {
                // Scroll back to top of page
                window.scrollTo(0,0)
                // 3. Hide the loader
                // Also sets firstLoad to false in order to show the second icon afterwards
                animateOut(() => firstLoad = false)
            }, 200) // This duration allows to not come over the transition In
            // [OU ALORS] les pages changent la valeur de loaded plus tard

            // 4. Run the page's transition in, but a little bit before the end of the loader
            setTimeout(() => {
                pageTransition.onAnimationEnd()
            }, animDurationLong * 0.666 + 200)
        }
    })
</script>

<div class="transition" id="transition" aria-hidden="true">
    <div class="loader">
        {#if firstLoad}
        <TitleSite />
        {:else}
        <IconGlobe width="44" color="#fff" animated="true" />
        {/if}
    </div>
</div>
