<script lang="ts">
	import MdiIcon from './MdiIcon.svelte';
	import { t } from '$lib/i18n';
	import { portal } from '$lib/portal';

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

	let {
		items = [],
		value = $bindable(),
		placeholder = 'Select...',
		columns = 2,
		disabled = false,
		compact = false,
		onChange,
	}: {
		items: GridItem[];
		value: string | number | null;
		placeholder?: string;
		columns?: number;
		disabled?: boolean;
		compact?: boolean;
		/**
		 * Optional one-way change callback. Fired in addition to updating
		 * `value` so callers that own state externally (e.g. a global store)
		 * can avoid the read-modify-write feedback loop that `bind:value` plus
		 * a sync `$effect` produces.
		 */
		onChange?: (value: string | number) => void;
	} = $props();

	let open = $state(false);
	let search = $state('');
	let triggerEl = $state<HTMLButtonElement | undefined>();
	let searchEl = $state<HTMLInputElement | undefined>();
	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 = '';
		onChange?.(item.value);
	}

	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
	aria-expanded={open}
	aria-haspopup="listbox"
	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 + popup are portalled to <body> so they escape any
	     backdrop-filter / transform ancestor that would otherwise act
	     as the containing block for `position: fixed`. -->
	<div use:portal class="icon-grid-portal-root">
		<div class="icon-grid-backdrop"
			role="presentation" onclick={() => open = false}></div>

		<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);" role="listbox">
				{#each filtered as item}
					<button type="button"
						class="icon-grid-cell"
						class:active={String(item.value) === String(value)}
						role="option"
						aria-selected={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">{t('common.noMatches')}</div>
				{/if}
			</div>
		</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.625rem;
		font-size: 0.875rem;
		background: var(--color-input-bg);
		color: var(--color-foreground);
		transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
		text-align: left;
	}
	.icon-grid-trigger:hover:not(.disabled) {
		border-color: var(--color-rule-strong);
		background: var(--color-glass-strong);
	}
	.icon-grid-compact {
		padding: 0.3rem 0.55rem;
		gap: 0.3rem;
		font-size: 0.85rem;
	}
	.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;
	}

	/* Portal root — drains the popup out of any backdrop-filter ancestor.
	   Position: fixed isolates the stacking context at the root level. */
	.icon-grid-portal-root {
		position: fixed;
		inset: 0;
		z-index: 9998;
		pointer-events: none;
	}
	.icon-grid-backdrop {
		position: absolute;
		inset: 0;
		pointer-events: auto;
	}
	.icon-grid-popup {
		pointer-events: auto;
		/* Solid surface — popups need legibility, not glass translucency. */
		--igs-solid-bg: #131520;
		background: var(--igs-solid-bg);
		border: 1px solid var(--color-rule-strong);
		border-radius: 14px;
		box-shadow: var(--shadow-card), 0 24px 48px -16px rgba(0, 0, 0, 0.55);
		padding: 0.5rem;
		max-height: 320px;
		overflow-y: auto;
		overscroll-behavior: contain;
		scrollbar-width: thin;
	}
	:global([data-theme="light"]) .icon-grid-popup { --igs-solid-bg: #fafafe; }
	.icon-grid-popup::after {
		content: '';
		position: absolute;
		inset: 0;
		border-radius: inherit;
		pointer-events: none;
		background: linear-gradient(180deg, var(--color-highlight), transparent 30%);
		opacity: 0.4;
	}
	.icon-grid-search {
		width: 100%;
		padding: 0.45rem 0.6rem;
		margin-bottom: 0.4rem;
		border: 1px solid var(--color-border);
		border-radius: 8px;
		background: var(--color-glass-strong);
		color: var(--color-foreground);
		font-size: 0.8rem;
		outline: none;
		font-family: inherit;
	}
	.icon-grid-search:focus {
		border-color: var(--color-primary);
		box-shadow: 0 0 0 2px var(--color-glow);
	}
	.icon-grid {
		display: grid;
		gap: 0.375rem;
		position: relative;
		z-index: 1;
	}
	.icon-grid-cell {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 0.3rem;
		padding: 0.7rem 0.45rem;
		border-radius: 10px;
		border: 1px solid transparent;
		background: transparent;
		color: var(--color-foreground);
		cursor: pointer;
		transition: all 0.15s;
		text-align: center;
		font-family: inherit;
	}
	.icon-grid-cell:hover {
		background: var(--color-glass-strong);
		border-color: var(--color-border);
	}
	.icon-grid-cell.active {
		background: linear-gradient(135deg, color-mix(in srgb, var(--color-primary) 18%, transparent), color-mix(in srgb, var(--color-orchid) 18%, transparent));
		border-color: var(--color-primary);
		box-shadow: inset 0 1px 0 var(--color-highlight), 0 0 0 1px color-mix(in srgb, var(--color-primary) 40%, transparent);
	}
	.icon-grid-cell-icon {
		color: var(--color-muted-foreground);
	}
	.icon-grid-cell:hover .icon-grid-cell-icon { color: var(--color-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;
	}
	.icon-grid-empty {
		grid-column: 1 / -1;
		text-align: center;
		padding: 0.85rem;
		color: var(--color-muted-foreground);
		font-size: 0.75rem;
	}
</style>
