<template>
	<v-popover class="filter-container">
		<div class="filter">
			<Icon icon="price-tag4" />

			<div
				v-if="selectedTags.length > 0"
				class="filter-applied"
			>{{ selectedTags.length }} {{ selectedTags.length > 1 ? 'tags' : 'tag' }}</div>

			<div
				v-else
				class="filter-applied empty"
			>Tags</div>
		</div>

		<div slot="popover">
			<select
				v-model="mode"
				class="filter-mode"
				@change="$router.push({ query: { ...$route.query, mode }, params: { pageNumber: 1 } })"
			>
				<option value="all">match all selected</option>
				<option value="any">match any selected</option>
			</select>

			<router-link
				class="filter-clear"
				:to="{ query: { ...$route.query, tags: undefined, mode: undefined } }"
				:class="{ active: selectedTags.length > 0 }"
			>clear all<Icon icon="cross2" /></router-link>

			<ul class="filter-items nolist">
				<li
					v-for="tag in availableTags"
					:key="`tag-${tag.id}`"
					class="filter-item"
					:class="{ selected: selectedTags.includes(tag.slug) }"
				>
					<router-link
						:to="{ query: { ...$route.query, tags: tag.slug, mode }, params: { pageNumber: 1 } }"
						class="filter-name"
					>{{ tag.name }}</router-link>

					<router-link
						:to="{ query: { ...$route.query, ...getNewRange(tag.slug), mode }, params: { pageNumber: 1 } }"
						class="filter-include"
						:class="{ selected: selectedTags.includes(tag.slug) }"
					>
						<Icon
							icon="checkmark"
							class="filter-add"
						/>

						<Icon
							icon="cross2"
							class="filter-remove"
						/>
					</router-link>
				</li>
			</ul>
		</div>
	</v-popover>
</template>

<script>
function getNewRange(tag) {
	if (this.selectedTags.includes(tag)) {
		return { tags: this.selectedTags.filter(selectedTag => selectedTag !== tag).join(',') || undefined };
	}

	return { tags: this.selectedTags.concat(tag).join(',') };
}

function selectedTags() {
	return this.$route.query.tags ? this.$route.query.tags.split(',') : [];
}

export default {
	props: {
		filter: {
			type: Array,
			default: () => [],
		},
		compact: {
			type: Boolean,
			default: false,
		},
		availableTags: {
			type: Array,
			default: () => [],
		},
	},
	data() {
		return {
			mode: this.$route.query.mode || 'all',
		};
	},
	computed: {
		selectedTags,
	},
	methods: {
		getNewRange,
	},
};
</script>

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

</style>
