<script lang="ts">
	import Svelecte from 'svelecte';
	import type { Tag } from '$lib/server/db/schema';

	interface Props {
		availableTags: Tag[];
		selectedTags: Tag[];
		onchange: (tags: Tag[]) => void;
	}

	let { availableTags, selectedTags, onchange }: Props = $props();

	// Transform tags to Svelecte format
	let options = $derived(availableTags.map((t) => ({ value: t.id, label: t.name })));

	// Internal state bound to Svelecte
	let selectedValues = $state(selectedTags.map((t) => t.id));

	// Sync selected values when selectedTags prop changes
	$effect(() => {
		selectedValues = selectedTags.map((t) => t.id);
	});

	function handleChange(selection: { value: string; label: string }[] | null) {
		const selected = selection || [];

		// Map back to Tag format, handling new tags (where value === label means new)
		const tags: Tag[] = selected.map((item) => {
			// If value matches an existing tag id, use that tag
			const existing = availableTags.find((t) => t.id === item.value);
			if (existing) return existing;

			// Otherwise it's a new tag - create placeholder (will be created on save)
			return {
				id: item.label, // Use label as temp id for new tags
				name: item.label,
				createdAt: new Date().toISOString()
			};
		});

		onchange(tags);
	}
</script>

<Svelecte
	{options}
	value={selectedValues}
	multiple
	creatable
	valueField="value"
	labelField="label"
	placeholder="Add tags..."
	onChange={handleChange}
	class="tag-input"
/>

<style>
	:global(.tag-input) {
		--sv-bg: white;
		--sv-border: 1px solid #e5e7eb;
		--sv-border-radius: 0.5rem;
		--sv-min-height: 42px;
	}
</style>
