<script>
    import { onMount, createEventDispatcher } from 'svelte'
    import { site, currentLocation } from 'utils/store'
    // Components
    import Newsletter from 'organisms/Newsletter'
    // Props
    export let photos
    export let paginatedPhotos
    export let photosPerPage

    // Variables
    const dispatch = createEventDispatcher()
    let currentIndex = photosPerPage
    const pagesTotal = Math.ceil(photos.length / photosPerPage)
    const pagesArray = Array.from({ length: pagesTotal }, (v, k) => k + 1).reverse()
    let pageTranslate = 100 - (100 / pagesTotal)

    // Add more photos to the loop
    const displayMorePhotos = () => {
        if (currentIndex < photos.length) {
            // Display the X next hidden photos
            const photosToAppend = photos.filter(photo => photo.hidden === true).splice(0, photosPerPage)
            photosToAppend.forEach(photo => photo.hidden = false)

            // Merge new photos to show to the existing ones
            dispatch('updatePagination', [...paginatedPhotos, ...photosToAppend])

            // Increment current index
            currentIndex = currentIndex + photosPerPage

            // Animate the pagination
            pageTranslate = pageTranslate - (100 / pagesTotal)
        } else {
            currentIndex = photos.length
        }
    }
</script>

<section class="pagination">
    {#if photos.length && currentIndex < photos.length}
    <div class="pagination__page" class:disabled={currentIndex === photos.length}
        on:click={displayMorePhotos}
        on:mouseenter={() => pageTranslate = pageTranslate - (100 / pagesTotal) * 0.666}
        on:mouseleave={() => pageTranslate = pageTranslate + (100 / pagesTotal) * 0.666}
        rel="next"
    >
        <div class="pagination__info">page</div>
        <div class="pagination__numbers">
            <div class="scroll" style="transform: translateY(-{pageTranslate}%) translateZ(0);">
                {#each pagesArray as page}
                <span>{page}</span>
                {/each}
            </div>
        </div>
        /{pagesTotal}
    </div>
    <p class="pagination__caption style-caps">See more photos</p>

    {:else if $currentLocation}
    <div class="pagination__message">
        <Newsletter
            title="That's all folks!"
            brightness="light"
        />
    </div>
    {/if}
</section>
