<script>
    import { fullscreen } from 'utils/store'
    import { throttle, getThumbnail } from 'utils/functions'

    // Dependencies
    import imagesLoaded from 'imagesloaded'

    // Components
    import IconGlobe from 'atoms/IconGlobe'
    import IconZoomOut from 'atoms/IconZoomOut'

    // Variables
    let scope
    let loading = false
    let open = false
    let closed = false

    // Wait for fullscreen store value
    $: if ($fullscreen) openFullscreen($fullscreen)


    /*
    ** Functions
    */
    // Open fullscreen
    const openFullscreen = throttle(currentPhoto => {
        const { name, image, location } = currentPhoto
        loading = true

        if (!open) {
            const img = document.createElement('img')
            const imgContainer = scope.querySelector('.fullscreen__image')
            img.src = getThumbnail(image.private_hash, null, 1600, 'crop', 80)
            img.alt = `${name}, ${location.name}, ${location.country.name}`
            img.width = 2400
            img.height = 1600
            imgContainer.append(img)

            // Show fullscreen when new image is loaded
            imagesLoaded(scope, instance => {
                open = true
                loading = false
                closed = false

                // Scroll to photo's center
                imgContainer.scrollTo((img.clientWidth - scope.clientWidth) / 2, 0)
            })
        }
    }, 800)

    // Close fullscreen
    const closeFullscreen = throttle(() => {
        // Reset values
        open = false
        closed = true

        // Clear image and reset fullscreen store value
        if (scope) {
            setTimeout(() => {
                scope.querySelector('.fullscreen__image').innerHTML = ''
                fullscreen.set()
            }, 800) // Transition duration
        }
    }, 800)
</script>

<div class="fullscreen" bind:this={scope}>
    <div class="fullscreen__image" class:is-open={open} on:click={closeFullscreen} />

    <div class="fullscreen__loading" class:is-hidden={!loading}>
        <IconGlobe width="24" color="#fff" animated="true" />
    </div>

    <div class="fullscreen__close" class:is-visible={open}>
        <button class="button-control button-control--gray button-control--shadow dir-top" aria-label="Close"
            on:click={closeFullscreen}
        >
            <IconZoomOut color="#fff" width="22" class="icon" />
            <IconZoomOut color="#fff" width="22" class="icon" hidden="true" />
        </button>
    </div>
</div>
