<template>
	<v-popover class="filters-container">
		<div class="filters">
			<div
				v-if="selectedTags.length > 0"
				class="applied"
			>{{ selectedTags.length }} selected</div>

			<div
				v-else
				class="applied empty"
			>Filter by tags</div>

			<Icon icon="filter" />
		</div>

		<div slot="popover">
			<ul class="tags nolist">
				<li
					v-for="tag in availableTags"
					:key="`tag-${tag.id}`"
					class="tag"
					:class="{ selected: selectedTags.includes(tag.slug) }"
				>
					<router-link :to="{ query: { ...getNewRange(tag.slug) } }">
						<Icon
							icon="checkmark"
							class="include"
						/>
					</router-link>

					<router-link
						:to="{ query: { ...(selectedTags.length === 1 && selectedTags.includes(tag.slug) ? null : { tags: tag.slug }) } }"
						class="name"
					>{{ tag.name }}</router-link>
				</li>
			</ul>
		</div>
	</v-popover>
</template>

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

		return {};
	}

	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: () => [],
		},
	},
	computed: {
		selectedTags,
	},
	methods: {
		getNewRange,
	},
};
</script>

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

.filters {
	display: inline-flex;
	align-items: center;

	.icon {
		fill: var(--shadow);
		margin: 0 .5rem 0 0;
	}
}

.applied {
	flex-grow: 1;
	padding: .75rem .5rem;
	font-size: 1rem;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	text-align: right;

	&.empty {
		color: var(--shadow);
	}
}

.tags {
	padding: .5rem 0;
}

.tag {
	display: flex;
	align-items: center;

	.include {
		width: 1rem;
		height: 1rem;
		padding: .5rem .75rem .5rem 1rem;
		fill: var(--darken-hint);

		&:hover {
			cursor: pointer;
		}
	}

	.name {
		min-width: 8rem;
		display: flex;
		justify-content: space-between;
		flex-grow: 1;
		padding: .5rem 1rem .5rem .75rem;
		color: var(--text);
		text-decoration: none;
	}

	&:hover {
		background: var(--darken-hint);
		cursor: pointer;
	}

	.include:hover,
	.name:hover {
		background: var(--darken-hint);
	}

	.include:hover,
	&.selected .include {
		fill: var(--success);
	}
}
</style>
