<script lang="ts">
    import { getContext } from 'svelte'
    import { flip } from 'svelte/animate'
    import { quartOut } from 'svelte/easing'
    import { send, receive } from '$animations/crossfade'
    import { throttle } from '$utils/functions'
    // Components
    import Button from '$components/atoms/Button.svelte'
    import Location from '$components/molecules/Location.svelte'

    export let locations: any


    const { continents, settings: { explore_list }} = getContext('global')

    // Continents filtering logic
    let currentContinent: string = undefined
    $: filteredLocations = locations.filter(({ country: { continent }}: any) => {
        if (!currentContinent) {
            // Show all locations by default
            return true
        } else {
            // Location's continent matches the clicked continent
            return continent.slug === currentContinent
        }
    })


    /**
     * Filter locations from continent
     */
    const filterLocation = throttle((continent: string) => {
        if (continent !== currentContinent) {
            currentContinent = continent
        } else {
            currentContinent = undefined
        }
    }, 700)
</script>

<div class="browse" id="locations">
    <div class="browse__description">
        <p>{explore_list}</p>
    </div>

    <ul class="browse__continents" role="navigation">
        {#each continents as { name, slug }}
            <li class:is-disabled={currentContinent && currentContinent !== slug}>
                <Button
                    tag="button" text={name} size="small"
                    on:click={() => filterLocation(slug)}
                />
            </li>
        {/each}
    </ul>

    <ul class="browse__locations" role="list">
        {#each filteredLocations as location (location)}
            <li
                animate:flip={{ duration: 1000, easing: quartOut }}
                in:receive={{ key: location.slug }}
                out:send={{ key: location.slug }}
            >
                <Location
                    location={location}
                    latestPhoto={location.photos[0]}
                />
            </li>
        {/each}
    </ul>
</div>