<script>
    import { onMount } from 'svelte'
    import { flip } from 'svelte/animate'
    import { fly, fade } from 'svelte/transition'
    import { locations, countries, continents } from '../store'
    import { crossfadeReceive, crossfadeSend } from '../animations'
    import * as fn from '../functions'

    // Dependencies
    import AOS from 'aos'

    // Components
    import Button from '../atoms/Button'
    import Location from '../molecules/Location'

    // Variables
    const transitionDuration = 800
    let filterLocations
    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 = fn.throttle((event, continent) => {
        continentsFiltered = (!continent) ? [...continentsToDisplay] : [continent]
    }, transitionDuration)


    /*
    ** Run code on browser only
    */
    onMount(() => {
        // Scroll apparitions
        if (process.browser) {
            AOS.init()
        }
    })
</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">
    {#each filteredLocations as location (location.id)}
        <div animate:flip="{{ duration: transitionDuration }}"
            in:crossfadeReceive="{{ key: location.id }}"
            out:crossfadeSend="{{ key: location.id }}"
        >
            <Location {location} />
        </div>
    {/each}
    </div>
</div>
