<template>
    <div class="networks">
        <form
            class="search"
            @submit.prevent="searchSites"
        >
            <input
                v-model="query"
                :placeholder="`Find ${siteCount} sites in ${networks.length} networks`"
                class="query"
                @input="searchSites"
            >

            <button
                type="submit"
                class="search-button"
            ><Icon icon="search" /></button>
        </form>

        <div
            v-if="query.length"
            class="network-tiles"
        >
            <Site
                v-for="site in searchResults"
                :key="`site-tile-${site.slug}`"
                :site="site"
            />

            <span v-if="searchResults.length === 0">No results for "{{ query }}"</span>
        </div>

        <div
            v-if="query.length === 0"
            class="network-tiles"
        >
            <Network
                v-for="network in networks"
                :key="`network-tile-${network.slug}`"
                :network="network"
            />
        </div>
    </div>
</template>

<script>
import Network from '../tile/network.vue';
import Site from '../tile/site.vue';

async function searchSites() {
    this.searchResults = await this.$store.dispatch('searchSites', {
        query: this.query,
        limit: 20,
    });
}

async function mounted() {
    this.networks = await this.$store.dispatch('fetchNetworks');
    this.pageTitle = 'Networks';
}

function siteCount() {
    return this.networks.map(network => network.sites).flat().length;
}

export default {
    components: {
        Network,
        Site,
    },
    data() {
        return {
            query: '',
            pageTitle: null,
            networks: [],
            searchResults: [],
        };
    },
    computed: {
        siteCount,
    },
    mounted,
    methods: {
        searchSites,
    },
};
</script>

<style lang="scss" scoped>
@import 'theme';

.networks {
    padding: 0 1rem;
}

.search {
    display: flex;
    width: 100%;
    max-width: 40rem;
}

.query {
    color: var(--text);
    background: var(--background);
    flex-grow: 1;
    box-sizing: border-box;
    padding: 1rem;
    border: none;
    box-sizing: border-box;
    box-shadow: 0 0 3px var(--darken-weak);
    margin: 1rem 0;
    font-size: 1rem;
    outline: none;

    &:focus {
        box-shadow: 0 0 3px var(--primary);
    }
}

.search-button {
    padding: 1rem;
    background: none;
    border: none;

    .icon {
        fill: var(--shadow);
    }

    &:hover {
        cursor: pointer;

        .icon {
            fill: var(--primary);
        }
    }
}

.network-tiles {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
    grid-gap: 1rem;
    padding: 1rem 0;
}

@media(max-width: $breakpoint) {
    .networks {
        grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
    }
}
</style>