<script lang="ts">
	import MdiIcon from './MdiIcon.svelte';

	export interface MultiEntityItem {
		value: string;
		label: string;
		icon?: string;
		desc?: string;
	}

	let {
		items = [],
		values = $bindable<string[]>(),
		placeholder = 'Select...',
		size = 'default',
		onchange,
	}: {
		items: MultiEntityItem[];
		values: string[];
		placeholder?: string;
		size?: 'sm' | 'default';
		onchange?: (values: string[]) => void;
	} = $props();

	let open = $state(false);
	let query = $state('');
	let highlightIdx = $state(0);
	let inputEl: HTMLInputElement;
	let listEl: HTMLDivElement;

	const selectedItems = $derived(items.filter(i => (values || []).includes(i.value)));

	const filtered = $derived.by(() => {
		const q = query.toLowerCase().trim();
		return q
			? items.filter(i => i.label.toLowerCase().includes(q) || (i.desc || '').toLowerCase().includes(q))
			: items;
	});

	function openPalette() {
		open = true;
		query = '';
		highlightIdx = 0;
		requestAnimationFrame(() => inputEl?.focus());
	}

	function closePalette() {
		open = false;
		query = '';
	}

	function toggleItem(item: MultiEntityItem) {
		const current = values || [];
		if (current.includes(item.value)) {
			values = current.filter(v => v !== item.value);
		} else {
			values = [...current, item.value];
		}
		onchange?.(values);
	}

	function removeItem(value: string) {
		values = (values || []).filter(v => v !== value);
		onchange?.(values);
	}

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape') { closePalette(); return; }
		if (e.key === 'ArrowDown') {
			e.preventDefault();
			highlightIdx = Math.min(highlightIdx + 1, filtered.length - 1);
			scrollToHighlight();
		} else if (e.key === 'ArrowUp') {
			e.preventDefault();
			highlightIdx = Math.max(highlightIdx - 1, 0);
			scrollToHighlight();
		} else if (e.key === 'Enter') {
			e.preventDefault();
			if (filtered[highlightIdx]) toggleItem(filtered[highlightIdx]);
		}
	}

	function scrollToHighlight() {
		requestAnimationFrame(() => {
			listEl?.querySelector('.mes-highlight')?.scrollIntoView({ block: 'nearest' });
		});
	}

	$effect(() => { query; highlightIdx = 0; });
</script>

<!-- Trigger: chips + button -->
<div class="mes-trigger-wrap" class:mes-sm={size === 'sm'}>
	{#if selectedItems.length > 0}
		<div class="mes-chips">
			{#each selectedItems as item}
				<span class="mes-chip">
					{#if item.icon}<span class="mes-chip-icon"><MdiIcon name={item.icon} size={12} /></span>{/if}
					<span class="mes-chip-label">{item.label}</span>
					<button type="button" class="mes-chip-remove" onclick={() => removeItem(item.value)}>&times;</button>
				</span>
			{/each}
		</div>
	{/if}
	<button type="button" class="mes-trigger" onclick={openPalette}>
		<MdiIcon name="mdiPlus" size={14} />
		<span>{(values || []).length === 0 ? placeholder : `${(values || []).length} selected`}</span>
		<span class="mes-trigger-arrow"><MdiIcon name="mdiChevronDown" size={14} /></span>
	</button>
</div>

<!-- Palette overlay -->
{#if open}
	<div class="mes-overlay" onclick={closePalette} role="presentation"></div>

	<div class="mes-container">
		<div class="mes-search-row">
			<MdiIcon name="mdiMagnify" size={18} />
			<input
				bind:this={inputEl}
				bind:value={query}
				placeholder="Search..."
				class="mes-input"
				type="text"
				autocomplete="off"
				spellcheck="false"
				onkeydown={handleKeydown}
			/>
			<span class="mes-count">{(values || []).length}/{items.length}</span>
			<kbd class="mes-kbd">ESC</kbd>
		</div>

		<div class="mes-list" bind:this={listEl} role="listbox">
			{#if filtered.length === 0}
				<div class="mes-empty">No matches</div>
			{:else}
				{#each filtered as item, i}
					{@const checked = (values || []).includes(item.value)}
					<button
						class="mes-item"
						class:mes-highlight={i === highlightIdx}
						class:mes-checked={checked}
						role="option"
						aria-selected={checked}
						onclick={() => toggleItem(item)}
						onmouseenter={() => highlightIdx = i}
						type="button"
					>
						<span class="mes-item-check">
							<MdiIcon name={checked ? 'mdiCheckboxMarked' : 'mdiCheckboxBlankOutline'} size={16} />
						</span>
						{#if item.icon}
							<span class="mes-item-icon"><MdiIcon name={item.icon} size={18} /></span>
						{/if}
						<span class="mes-item-label">{item.label}</span>
						{#if item.desc}
							<span class="mes-item-desc">{item.desc}</span>
						{/if}
					</button>
				{/each}
			{/if}
		</div>
	</div>
{/if}

<style>
	.mes-trigger-wrap {
		display: flex;
		flex-direction: column;
		gap: 0.375rem;
	}
	.mes-chips {
		display: flex;
		flex-wrap: wrap;
		gap: 0.25rem;
	}
	.mes-chip {
		display: inline-flex;
		align-items: center;
		gap: 0.25rem;
		font-size: 0.75rem;
		padding: 0.125rem 0.5rem;
		border-radius: 9999px;
		background: color-mix(in srgb, var(--color-primary) 10%, transparent);
		color: var(--color-primary);
		border: 1px solid color-mix(in srgb, var(--color-primary) 30%, transparent);
	}
	.mes-chip-icon {
		display: flex;
		align-items: center;
	}
	.mes-chip-label {
		max-width: 12rem;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.mes-chip-remove {
		cursor: pointer;
		font-size: 0.875rem;
		line-height: 1;
		opacity: 0.6;
		transition: opacity 0.1s;
	}
	.mes-chip-remove:hover {
		opacity: 1;
	}

	.mes-trigger {
		display: flex;
		align-items: center;
		gap: 0.375rem;
		width: 100%;
		padding: 0.375rem 0.625rem;
		border: 1px solid var(--color-border);
		border-radius: 0.375rem;
		font-size: 0.8rem;
		background: var(--color-background);
		color: var(--color-muted-foreground);
		cursor: pointer;
		transition: border-color 0.15s;
	}
	.mes-sm .mes-trigger {
		padding: 0.25rem 0.5rem;
		font-size: 0.75rem;
	}
	.mes-trigger:hover {
		border-color: var(--color-primary);
	}
	.mes-trigger-arrow {
		margin-left: auto;
		flex-shrink: 0;
	}

	/* Overlay */
	.mes-overlay {
		position: fixed;
		inset: 0;
		z-index: 9998;
		background: rgba(0, 0, 0, 0.4);
		backdrop-filter: blur(2px);
	}

	/* Palette container */
	.mes-container {
		position: fixed;
		top: min(20vh, 120px);
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
		width: min(460px, 90vw);
		max-height: 60vh;
		background: var(--color-card);
		border: 1px solid var(--color-border);
		border-radius: 0.75rem;
		box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	.mes-search-row {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.625rem 0.875rem;
		border-bottom: 1px solid var(--color-border);
		color: var(--color-muted-foreground);
	}
	.mes-input {
		flex: 1;
		border: none;
		outline: none;
		background: transparent;
		font-size: 0.9rem;
		color: var(--color-foreground);
		padding: 0;
	}
	.mes-count {
		font-size: 0.7rem;
		color: var(--color-muted-foreground);
		white-space: nowrap;
	}
	.mes-kbd {
		font-size: 0.55rem;
		font-family: var(--font-mono);
		padding: 0.1rem 0.3rem;
		border-radius: 0.2rem;
		background: var(--color-muted);
		color: var(--color-muted-foreground);
		border: 1px solid var(--color-border);
	}

	.mes-list {
		overflow-y: auto;
		scrollbar-width: thin;
		padding: 0.25rem 0;
	}
	.mes-empty {
		padding: 1rem;
		text-align: center;
		color: var(--color-muted-foreground);
		font-size: 0.85rem;
	}

	.mes-item {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		width: 100%;
		padding: 0.4rem 0.875rem;
		border: none;
		background: transparent;
		color: var(--color-foreground);
		font-size: 0.875rem;
		cursor: pointer;
		text-align: left;
		transition: background 0.1s;
	}
	.mes-item:hover, .mes-item.mes-highlight {
		background: var(--color-muted);
	}
	.mes-item-check {
		flex-shrink: 0;
		display: flex;
		align-items: center;
		color: var(--color-muted-foreground);
	}
	.mes-item.mes-checked .mes-item-check {
		color: var(--color-primary);
	}
	.mes-item-icon {
		flex-shrink: 0;
		display: flex;
		align-items: center;
		color: var(--color-muted-foreground);
	}
	.mes-item-label {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.mes-item-desc {
		font-size: 0.75rem;
		color: var(--color-muted-foreground);
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 40%;
	}
</style>
