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

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

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


    // Check if path is excluded
    const isExcluded = path => path.includes(['/viewer/'])

    /*
    ** 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 scope
    let firstLoad = true
    let previousPage = ''

    // 1. Watch page change
    page.subscribe(page => {
        // Run transition if page is not excluded
        if (!isExcluded(previousPage) || !isExcluded(page.path)) {
            // Run the loader animation (first load only)
            if (!firstLoad) {
                animateIn(scope)
            }

            // Reset pageReady when changing page
            pageReady.set(false)
        }

        // Update page for viewer navigation checking
        previousPage = page.path
    })

    // 2. Watch when loaded changes
    pageReady.subscribe(loaded => {
        if (loaded) {
            // 3. Hide the loader and set firstLoad to false (in order to show the second icon afterwards)
            animateOut(scope, () => firstLoad = false)

            // Scroll back to top of page
            setTimeout(() => window.scrollTo(0,0), transitionDelay)

            // 4. Run page entering animation
            pageTransition.onAnimationEnd()
        }
    })
</script>

<div class="transition" id="transition" aria-hidden="true" bind:this={scope}>
    <div class="transition__loader">
        {#if firstLoad}
        <TitleSite init="true" />

        {:else}
        <IconGlobe width="44" color="#fff" animated="true" />
        {/if}
    </div>
    <div class="transition__background" />
</div>
