<script>
    import { onMount, createEventDispatcher } from 'svelte'
    import { currentLocation } from '../store'
    const dispatch = createEventDispatcher()

    // Props
    export let photos
    export let paginatedPhotos
    export let photosPerPage

    // Variables
    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: [...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}
    >
        <div class="pagination__info">page</div>
        <div class="pagination__numbers">
            <div class="scroll" style="transform: translateY(-{pageTranslate}%);">
                {#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">
        <h3>That's all folks!</h3>
        <p class="pagination__caption style-caps">Come back later to check out <br>new photos of {$currentLocation.name}</p>
    </div>
    {/if}
    {/if}
</section>
