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

import { get } from '#/src/api.js';

defineProps({
	disabled: {
		type: Boolean,
		default: false,
	},
});

const emit = defineEmits(['tag']);
const dropdownId = useId();

const pageContext = inject('pageContext');

const tagNames = {
	dp: 'double penetration',
};

const defaultTags = pageContext.pageProps.tagIds
	? Object.entries(pageContext.pageProps.tagIds).map(([slug, id]) => ({
			id,
			slug,
			name: tagNames[slug] || slug,
		}))
	: [];

const tags = ref(defaultTags);
const query = ref(null);
const queryInput = ref(null);

async function search() {
	tags.value = await get('/tags', { query: query.value });
}

function focus() {
	setTimeout(() => {
		queryInput.value?.focus();
	}, 100);
}
</script>

<template>
	<VDropdown
		:aria-id="dropdownId"
		:disabled="disabled"
		class="trigger"
		@show="focus"
	>
		<slot />

		<template #popper>
			<div>
				<input
					ref="queryInput"
					v-model="query"
					placeholder="Search tag"
					class="input"
					@input="search"
				>

				<ul class="tags nolist">
					<li
						v-for="tag in tags"
						:key="`tag-${tag.slug}`"
						v-close-popper
						class="tag"
						@click="emit('tag', tag); query = '';"
					>{{ tag.name }}</li>
				</ul>
			</div>
		</template>
	</VDropdown>
</template>

<style scoped>
.trigger {
	height: 100%;
	overflow: hidden;
}

.tag {
	display: block;
	padding: .25rem .5rem;

	&:hover {
		background: var(--glass-weak-50);
		color: var(--primary);
		cursor: pointer;
	}
}
</style>
