<script>
	import Select from 'svelte-select';
	import { tagList } from '$lib/stores.js';

	let items = tagList.map((x) => ({ value: x, label: x }));

	let value = [];
	export let checked = [];
	let isChecked = {};
	export let remainingTags = [];
	export let listOpen;

	$: computeValue(checked);
	$: computeIsChecked(checked);

	function computeIsChecked() {
		isChecked = {};
		checked.forEach((c) => (isChecked[c] = true));
	}

	function computeValue() {
		value = checked.map((c) => items.find((i) => i.value === c));
	}

	function handleSelectable() {
		items = items.map((item) => {
			return { ...item, selectable: !checked.includes(item.value) };
		});
	}

	function handleChange(e) {
		if (e.type === 'clear' && Array.isArray(e.detail)) checked = [];
		else
			checked.includes(e.detail.value)
				? (checked = checked.filter((i) => i != e.detail.value))
				: (checked = [...checked, e.detail.value]);
		handleSelectable();
	}

	let itemFilter = function (label, filterText, option) {
		return (
			remainingTags.includes(option['value']) &&
			label.toLowerCase().includes(filterText.toLowerCase())
		);
	};
</script>

<Select
	{items}
	{value}
	bind:listOpen
	multiple={true}
	placeholder="Tag Filter..."
	filterSelectedItems={true}
	closeListOnChange={false}
	on:select={handleChange}
	on:clear={handleChange}
	{itemFilter}
	--max-height="42px"
	listOffset={0}
>
	<div class="item" slot="item" let:item>
		<label for={item.value}>
			<input type="checkbox" id={item.value} bind:checked={isChecked[item.value]} />
			{item.label}
		</label>
	</div>
</Select>

<style>
	.item {
		pointer-events: none;
	}

	:global(.svelte-select:hover) {
		max-height: unset !important;
	}
</style>
