<template>
	<ul
		class="tags nolist"
		:class="{ disabled: !editing.has(item.key) }"
	>
		<li
			v-for="tag in [...item.value, ...newTags]"
			:key="`tag-${tag.id}`"
			class="tag"
			:class="{ deleted: edits.tags && !edits.tags.some((tagId) => tagId === tag.id) }"
		>
			<span class="tag-name">{{ tag.name }}</span>

			<Icon
				v-if="edits.tags && !edits.tags.some((tagId) => tagId === tag.id)"
				icon="checkmark"
				class="add"
				@click="emit('tags', edits.tags.concat(tag.id))"
			/>

			<Icon
				v-else
				icon="cross2"
				class="remove"
				@click="emit('tags', edits.tags.filter((tagId) => tagId !== tag.id))"
			/>
		</li>

		<li class="new">
			<TagSearch
				:disabled="!editing.has(item.key)"
				@tag="addTag"
			>
				<Icon
					icon="plus3"
					class="add"
				/>
			</TagSearch>
		</li>
	</ul>
</template>

<script setup>
import { ref, watch } from 'vue';

import events from '#/src/events.js';

import TagSearch from '#/components/tags/search.vue';

const newTags = ref([]);

const props = defineProps({
	item: {
		type: Object,
		default: null,
	},
	scene: {
		type: Object,
		default: null,
	},
	edits: {
		type: Object,
		default: () => {},
	},
	editing: {
		type: Set,
		default: null,
	},
});

const emit = defineEmits(['tags']);

function addTag(tag) {
	if (props.edits.tags.some((tagId) => tagId === tag.id)) {
		events.emit('feedback', {
			type: 'error',
			message: 'Tag already added',
		});

		return;
	}

	newTags.value = newTags.value.concat(tag);

	emit('tags', props.edits.tags.concat(tag.id));
}

watch(() => props.scene, () => { newTags.value = []; });
</script>

<style scoped>
.tags {
	display: flex;
	flex-wrap: wrap;
	gap: .35rem .25rem;

	&.disabled {
		.tag {
			background: var(--glass-weak-50);
			color: var(--glass-strong-10);

			.remove,
			.add {
				fill: var(--shadow-weak-30);
				background: var(--shadow-weak-50);
			}
		}

		.new .icon {
			background: var(--shadow-weak-40);
		}
	}

	.new {
		display: flex;
		align-items: center;
		margin-left: .25rem;

		&:hover {
			box-shadow: 0 0 3px var(--shadow-weak-20);
		}

		.icon {
			height: 100%;
			padding: 0 .5rem;
			background: var(--success);
			fill: var(--text-light);
		}
	}
}

.tag {
	display: flex;
	align-items: stretch;
	border-radius: .25rem;
	background: var(--background);
	box-shadow: 0 0 3px var(--shadow-weak-30);

	&.deleted  {
		color: var(--glass);
		text-decoration: line-through;
	}
}

.tag,
.new {
	.remove,
	.add {
		height: auto;
		padding: .25rem .3rem;
		border-radius: .25rem;
		fill: var(--highlight-strong-10);

		&:hover {
			fill: var(--text-light);
			cursor: pointer;
		}
	}

	.remove {
		fill: var(--error);

		&:hover {
			background: var(--error);
		}
	}

	.add {
		fill: var(--success);

		&:hover {
			background: var(--success);
		}
	}
}

.tag-name {
	padding: .25rem .5rem;
}
</style>
