<script lang="ts">
    import { getContext } from 'svelte'
    import { spring } from 'svelte/motion'
    import dayjs from 'dayjs'
    import { lerp } from '$utils/functions'
    // Components
    import Image from '$components/atoms/Image.svelte'
    import Badge from '$components/atoms/Badge.svelte'

    export let location: any

    const { settings: { limit_new }}: any = getContext('global')
    const { name, slug, country, date_updated } = location

    // Location date limit
    const dateNowOffset = dayjs().subtract(limit_new, 'day')
    const dateLocationUpdated = dayjs(date_updated)
    const isNew = dateLocationUpdated.isAfter(dateNowOffset)

    let locationEl: HTMLElement
    let photoIndex = 0
    const offset = spring({ x: 0, y: 0 }, {
		stiffness: 0.075,
		damping: 0.9
	})

    // Moving cursor over
    const handleMouseMove = ({ clientX }: MouseEvent) => {
        const { width, left } = locationEl.getBoundingClientRect()
        const moveProgress = (clientX - left) / width // 0 to 1

        // Move horizontally
        offset.update($c => ({
            x: lerp(-56, 56, moveProgress),
            y: 0
        }))

        // Change photo index from mouse position percentage
        photoIndex = Math.round(lerp(0, Number(import.meta.env.VITE_PREVIEW_COUNT) - 1, moveProgress))
    }

    // Leaving mouseover
    const handleMouseLeave = (event: MouseEvent) => {
        offset.update($c => ({
            x: $c.x,
            y: 40
        }))
    }
</script>

<div class="location" role="listitem" bind:this={locationEl}
    style="--offset-x: {$offset.x}px; --offset-y: {$offset.y}px; --rotate: {$offset.x * 0.125}deg"
>
    <a href="/{country.slug}/{slug}"
        on:mousemove={handleMouseMove}
        on:mouseleave={handleMouseLeave}
        sveltekit-noscroll
    >
        <Image class="location__flag" id={country.flag.id} alt="Flag of {country.name}" width={32} height={32} />
        <div class="text">
            <dl>
                <dt class="location__name">
                    {name}
                </dt>
                <dd class="location__country text-label">
                    {country.name}
                </dd>
            </dl>
            {#if isNew}
                <Badge text="New" />
            {/if}
        </div>
    </a>
    {#if location.photos.length}
        <div class="location__photos">
            {#each location.photos as photo, index}
                <Image
                    class={index === photoIndex ? 'is-visible' : null}
                    id={photo.image.id} alt={photo.image.title}
                    width={340} height={226} quality={70}
                />
            {/each}
        </div>
    {/if}
</div>
