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

	export interface EntityItem {
		value: string | number;
		label: string;
		icon?: string;
		desc?: string;
	}

	let {
		items = [],
		value = $bindable(),
		placeholder = 'Select...',
		allowNone = false,
		noneLabel = '—',
		disabled = false,
	}: {
		items: EntityItem[];
		value: string | number | null;
		placeholder?: string;
		allowNone?: boolean;
		noneLabel?: string;
		disabled?: boolean;
	} = $props();

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

	const selected = $derived(items.find(i => String(i.value) === String(value)));

	const filtered = $derived.by(() => {
		const q = query.toLowerCase().trim();
		let result: EntityItem[] = [];
		if (allowNone) {
			result.push({ value: '', label: noneLabel, icon: '' });
		}
		const matching = q
			? items.filter(i => i.label.toLowerCase().includes(q) || (i.desc || '').toLowerCase().includes(q))
			: items;
		return [...result, ...matching];
	});

	function openPalette() {
		if (disabled) return;
		open = true;
		query = '';
		highlightIdx = Math.max(0, filtered.findIndex(i => String(i.value) === String(value)));
		requestAnimationFrame(() => inputEl?.focus());
	}

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

	function selectItem(item: EntityItem) {
		value = item.value || null;
		closePalette();
	}

	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]) selectItem(filtered[highlightIdx]);
		} else if (e.key === 'Tab') {
			e.preventDefault();
		}
	}

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

	// Reset highlight when query changes
	$effect(() => {
		query; // track
		highlightIdx = 0;
	});
</script>

<!-- Trigger button -->
<button type="button" class="es-trigger" onclick={openPalette}
	style="opacity: {disabled ? 0.5 : 1}; cursor: {disabled ? 'default' : 'pointer'};">
	{#if selected}
		{#if selected.icon}
			<span class="es-trigger-icon"><MdiIcon name={selected.icon} size={16} /></span>
		{/if}
		<span class="es-trigger-label">{selected.label}</span>
	{:else}
		<span class="es-trigger-label es-trigger-none">{placeholder}</span>
	{/if}
	<span class="es-trigger-arrow"><MdiIcon name="mdiChevronDown" size={14} /></span>
</button>

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

	<div class="ep-container">
		<div class="ep-search-row">
			<MdiIcon name="mdiMagnify" size={18} />
			<input
				bind:this={inputEl}
				bind:value={query}
				placeholder={placeholder}
				class="ep-input"
				type="text"
				autocomplete="off"
				spellcheck="false"
				onkeydown={handleKeydown}
			/>
			<kbd class="ep-kbd">ESC</kbd>
		</div>

		<div class="ep-list" bind:this={listEl}>
			{#if filtered.length === 0}
				<div class="ep-empty">No matches</div>
			{:else}
				{#each filtered as item, i}
					<button
						class="ep-item"
						class:ep-highlight={i === highlightIdx}
						class:ep-current={String(item.value) === String(value)}
						onclick={() => selectItem(item)}
						onmouseenter={() => highlightIdx = i}
						type="button"
					>
						{#if item.icon}
							<span class="ep-item-icon"><MdiIcon name={item.icon} size={18} /></span>
						{/if}
						<span class="ep-item-label">{item.label}</span>
						{#if item.desc}
							<span class="ep-item-desc">{item.desc}</span>
						{/if}
					</button>
				{/each}
			{/if}
		</div>
	</div>
{/if}

<style>
	/* Trigger button */
	.es-trigger {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		width: 100%;
		padding: 0.5rem 0.75rem;
		border: 1px solid var(--color-border);
		border-radius: 0.375rem;
		font-size: 0.875rem;
		background: var(--color-background);
		color: var(--color-foreground);
		transition: border-color 0.15s;
		text-align: left;
		cursor: pointer;
	}
	.es-trigger:hover {
		border-color: var(--color-primary);
	}
	.es-trigger-icon {
		flex-shrink: 0;
		color: var(--color-primary);
	}
	.es-trigger-label {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.es-trigger-none {
		color: var(--color-muted-foreground);
	}
	.es-trigger-arrow {
		flex-shrink: 0;
		color: var(--color-muted-foreground);
	}

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

	/* Palette container */
	.ep-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;
	}

	/* Search row */
	.ep-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);
	}
	.ep-input {
		flex: 1;
		border: none;
		outline: none;
		background: transparent;
		font-size: 0.9rem;
		color: var(--color-foreground);
		padding: 0;
	}
	.ep-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);
	}

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

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