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

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

	let {
		items = [],
		value = $bindable(),
		placeholder = 'Select...',
		columns = 2,
		disabled = false,
		compact = false,
	}: {
		items: GridItem[];
		value: string | number | null;
		placeholder?: string;
		columns?: number;
		disabled?: boolean;
		compact?: boolean;
	} = $props();

	let open = $state(false);
	let search = $state('');
	let triggerEl: HTMLButtonElement;
	let searchEl: HTMLInputElement;
	let popupStyle = $state('');

	const showSearch = $derived(items.length > 4);
	const selected = $derived(items.find(i => String(i.value) === String(value)));
	const filtered = $derived(
		search.trim()
			? items.filter(i => i.label.toLowerCase().includes(search.toLowerCase()))
			: items
	);

	function toggle() {
		if (disabled) return;
		if (!open && triggerEl) {
			const rect = triggerEl.getBoundingClientRect();
			const spaceBelow = window.innerHeight - rect.bottom;
			const popupHeight = Math.min(items.length * 60 + 16 + (showSearch ? 40 : 0), 320);
			const top = spaceBelow > popupHeight + 8
				? rect.bottom + 4
				: rect.top - popupHeight - 4;
			const left = Math.min(rect.left, window.innerWidth - columns * 160 - 24);
			popupStyle = `position:fixed; z-index:9999; top:${top}px; left:${Math.max(4, left)}px;`;
		}
		open = !open;
		search = '';
		if (open && showSearch) {
			requestAnimationFrame(() => searchEl?.focus());
		}
	}

	function select(item: GridItem) {
		value = item.value;
		open = false;
		search = '';
	}

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape' && open) {
			open = false;
			search = '';
		}
	}
</script>

<svelte:window onkeydown={open ? handleKeydown : undefined} />

<button type="button" bind:this={triggerEl} onclick={toggle}
	class="icon-grid-trigger {compact ? 'icon-grid-compact' : ''}"
	class:disabled
	style="opacity: {disabled ? 0.5 : 1}; cursor: {disabled ? 'default' : 'pointer'};">
	{#if selected}
		<span class="icon-grid-trigger-icon"><MdiIcon name={selected.icon} size={compact ? 14 : 18} /></span>
		<span class="icon-grid-trigger-label">{selected.label}</span>
	{:else}
		<span class="icon-grid-trigger-label" style="color: var(--color-muted-foreground);">{placeholder}</span>
	{/if}
	<span class="icon-grid-trigger-arrow"><MdiIcon name="mdiChevronDown" size={compact ? 10 : 14} /></span>
</button>

{#if open}
	<!-- Backdrop -->
	<div style="position:fixed; top:0; left:0; right:0; bottom:0; z-index:9998;"
		role="presentation" onclick={() => open = false}></div>

	<!-- Popup grid -->
	<div style="{popupStyle} width: {columns * 160 + 16}px;"
		class="icon-grid-popup">
		{#if showSearch}
			<input bind:this={searchEl} bind:value={search} placeholder="Filter..."
				class="icon-grid-search" type="text" autocomplete="off"
				onkeydown={handleKeydown} />
		{/if}
		<div class="icon-grid" style="grid-template-columns: repeat({columns}, 1fr);">
			{#each filtered as item}
				<button type="button"
					class="icon-grid-cell"
					class:active={String(item.value) === String(value)}
					onclick={() => select(item)}>
					<span class="icon-grid-cell-icon"><MdiIcon name={item.icon} size={22} /></span>
					<span class="icon-grid-cell-label">{item.label}</span>
					{#if item.desc}
						<span class="icon-grid-cell-desc">{item.desc}</span>
					{/if}
				</button>
			{/each}
			{#if filtered.length === 0}
				<div class="icon-grid-empty" style="grid-column: 1 / -1; text-align: center; padding: 0.75rem; color: var(--color-muted-foreground); font-size: 0.75rem;">No matches</div>
			{/if}
		</div>
	</div>
{/if}

<style>
	.icon-grid-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, box-shadow 0.15s;
		text-align: left;
	}
	.icon-grid-trigger:hover:not(.disabled) {
		border-color: var(--color-primary);
	}
	.icon-grid-compact {
		width: auto;
		padding: 0.3rem 0.5rem;
		gap: 0.3rem;
		font-size: 0.8rem;
	}
	.icon-grid-compact .icon-grid-trigger-label {
		flex: none;
	}
	.icon-grid-trigger-icon {
		flex-shrink: 0;
		color: var(--color-primary);
	}
	.icon-grid-trigger-label {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.icon-grid-trigger-arrow {
		flex-shrink: 0;
		color: var(--color-muted-foreground);
		transition: transform 0.15s;
	}
	.icon-grid-popup {
		background: var(--color-card);
		border: 1px solid var(--color-border);
		border-radius: 0.5rem;
		box-shadow: 0 10px 30px rgba(0,0,0,0.3);
		padding: 0.5rem;
		max-height: 320px;
		overflow-y: auto;
		scrollbar-width: thin;
	}
	.icon-grid-search {
		width: 100%;
		padding: 0.375rem 0.5rem;
		margin-bottom: 0.375rem;
		border: none;
		border-bottom: 1px solid var(--color-border);
		border-radius: 0;
		background: transparent;
		color: var(--color-foreground);
		font-size: 0.8rem;
		outline: none;
	}
	.icon-grid {
		display: grid;
		gap: 0.375rem;
	}
	.icon-grid-cell {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 0.25rem;
		padding: 0.625rem 0.375rem;
		border-radius: 0.375rem;
		border: 2px solid transparent;
		background: transparent;
		color: var(--color-foreground);
		cursor: pointer;
		transition: all 0.15s;
		text-align: center;
	}
	.icon-grid-cell:hover {
		background: var(--color-muted);
		transform: scale(1.03);
	}
	.icon-grid-cell.active {
		border-color: var(--color-primary);
		background: color-mix(in srgb, var(--color-primary) 10%, transparent);
	}
	.icon-grid-cell-icon {
		color: var(--color-muted-foreground);
	}
	.icon-grid-cell.active .icon-grid-cell-icon {
		color: var(--color-primary);
	}
	.icon-grid-cell-label {
		font-size: 0.7rem;
		font-weight: 500;
		line-height: 1.2;
	}
	.icon-grid-cell-desc {
		font-size: 0.6rem;
		color: var(--color-muted-foreground);
		line-height: 1.2;
	}
</style>
