<script>
    import { onMount } from 'svelte'
    import { flip } from 'svelte/animate'
    import { receive, send } from 'animations/crossfade'
    import { locations, continents } from 'utils/store'
    import { throttle } from 'utils/functions'
    // Components
    import Button from 'atoms/Button'
    import Location from 'molecules/Location'
    import Newsletter from 'organisms/Newsletter'
    // Animations
    import { animateIn } from 'animations/Locations'

    // Variables
    const transitionDuration = 800
    let list
    let continentsToDisplay = []
    let continentsFiltered = []
    $: filteredLocations = $locations.filter(location => continentsFiltered.includes(location.country.continent))

    // Define continents to show
    $continents.forEach(cont => !!cont.countries && continentsToDisplay.push(cont))
    continentsFiltered = [...continentsToDisplay]

    // Filter by continent
    // Detects if click difference if too short with a throttled function
    const toggleContinents = throttle((event, continent) => {
        continentsFiltered = (!continent) ? [...continentsToDisplay] : [continent]
    }, transitionDuration)


    /*
    ** Run code when mounted
    */
    onMount(() => {
        // Entering transition
        animateIn(list)
    })
</script>

<div class="browse wrap">
    <div class="browse__description style-description">
        <p>Browse all the cities and countries</p>
    </div>

    <ul class="browse__continents" id="continents">
        {#if continentsToDisplay.length > 1}
        <li on:click={e => toggleContinents(e)}>
            <Button type="button" text="All" class="button-outline {(continentsFiltered.length <= 1) ? 'disabled' : ''}" />
        </li>
        {/if}
        {#each continentsToDisplay as continent}
        <li on:click={e => toggleContinents(e, continent)}>
            <Button type="button" text={continent.name} class="button-outline {(!continentsFiltered.includes(continent)) ? 'disabled' : ''}" />
        </li>
        {/each}
    </ul>

    <div class="browse__locations" id="locations_list" role="list" bind:this={list}>
    {#each filteredLocations as location (location.id)}
        <div
            animate:flip="{{ duration: transitionDuration }}"
            in:receive="{{ key: location.id }}"
            out:send="{{ key: location.id }}"
        >
            <Location {location} />
        </div>
    {/each}
    </div>
</div>

<Newsletter />