<script lang="ts">
	import { goto } from '$app/navigation';
	import { t } from '$lib/i18n';
	import MdiIcon from './MdiIcon.svelte';
	import { requestHighlight } from '$lib/highlight';
	import { providerDefaultIcon } from '$lib/grid-items';
	import { globalProviderFilter } from '$lib/stores/provider-filter.svelte';
	import {
		fetchAllCaches,
		providersCache,
		targetsCache,
		notificationTrackersCache,
		trackingConfigsCache,
		templateConfigsCache,
		telegramBotsCache,
		emailBotsCache,
		matrixBotsCache,
		commandConfigsCache,
		commandTemplateConfigsCache,
		commandTrackersCache,
	} from '$lib/stores/caches.svelte';

	let { onopen = undefined }: { onopen?: (opener: () => void) => void } = $props();

	let open = $state(false);
	let query = $state('');
	let activeIndex = $state(0);
	let loading = $state(false);
	let inputEl = $state<HTMLInputElement | undefined>();
	const listboxId = 'sp-listbox';
	const optionId = (idx: number) => `sp-option-${idx}`;

	// Expose openPalette to parent via callback
	$effect(() => { onopen?.(openPalette); });

	interface SearchResult {
		id: number;
		name: string;
		icon: string;
		detail: string;
		href: string;
		group: string;
		groupIcon: string;
	}

	/** All searchable entity groups. */
	type CacheEntity = Record<string, unknown> & { id: number; name: string };

	const GROUPS: readonly { key: string; label: string; icon: string; href: string; mapFn: (e: CacheEntity) => { detail: string; icon: string } }[] = [
		{ key: 'providers', label: 'nav.providers', icon: 'mdiServer', href: '/providers',
			mapFn: (e) => ({ detail: String(e.type || ''), icon: providerDefaultIcon(e as any) }) },
		{ key: 'notification_trackers', label: 'nav.notification', icon: 'mdiRadar', href: '/notification-trackers',
			mapFn: (e) => ({ detail: e.enabled ? 'enabled' : 'disabled', icon: String(e.icon || 'mdiRadar') }) },
		{ key: 'tracking_configs', label: 'nav.trackingConfigs', icon: 'mdiCog', href: '/tracking-configs',
			mapFn: (e) => ({ detail: String(e.provider_type || ''), icon: String(e.icon || 'mdiCog') }) },
		{ key: 'template_configs', label: 'nav.templateConfigs', icon: 'mdiFileDocumentEdit', href: '/template-configs',
			mapFn: (e) => ({ detail: String(e.provider_type || ''), icon: String(e.icon || 'mdiFileDocumentEdit') }) },
		{ key: 'targets', label: 'nav.targets', icon: 'mdiTarget', href: '/targets',
			mapFn: (e) => ({ detail: String(e.type || ''), icon: String(e.icon || 'mdiTarget') }) },
		{ key: 'telegram_bots', label: 'nav.telegram', icon: 'mdiSendCircle', href: '/bots?tab=telegram',
			mapFn: (e) => ({ detail: `@${e.bot_username || ''}`, icon: String(e.icon || 'mdiRobot') }) },
		{ key: 'email_bots', label: 'nav.email', icon: 'mdiEmailOutline', href: '/bots?tab=email',
			mapFn: (e) => ({ detail: String(e.email || ''), icon: String(e.icon || 'mdiEmailOutline') }) },
		{ key: 'matrix_bots', label: 'nav.matrix', icon: 'mdiMatrix', href: '/bots?tab=matrix',
			mapFn: (e) => ({ detail: String(e.display_name || ''), icon: String(e.icon || 'mdiMatrix') }) },
		{ key: 'command_trackers', label: 'nav.commandTrackers', icon: 'mdiConsoleLine', href: '/command-trackers',
			mapFn: (e) => ({ detail: e.enabled ? 'enabled' : 'disabled', icon: String(e.icon || 'mdiConsoleLine') }) },
		{ key: 'command_configs', label: 'nav.commandConfigs', icon: 'mdiCog', href: '/command-configs',
			mapFn: (e) => ({ detail: String(e.provider_type || ''), icon: String(e.icon || 'mdiCog') }) },
		{ key: 'command_template_configs', label: 'nav.cmdTemplateConfigs', icon: 'mdiCodeBracesBox', href: '/command-template-configs',
			mapFn: (e) => ({ detail: String(e.provider_type || ''), icon: String(e.icon || 'mdiCodeBracesBox') }) },
	];

	const cacheMap = {
		providers: providersCache,
		notification_trackers: notificationTrackersCache,
		tracking_configs: trackingConfigsCache,
		template_configs: templateConfigsCache,
		targets: targetsCache,
		telegram_bots: telegramBotsCache,
		email_bots: emailBotsCache,
		matrix_bots: matrixBotsCache,
		command_trackers: commandTrackersCache,
		command_configs: commandConfigsCache,
		command_template_configs: commandTemplateConfigsCache,
	} as unknown as Record<string, { items: { id: number; name: string; [k: string]: unknown }[] }>;

	/** Build flat results from all caches, filtered by query. */
	const results = $derived.by(() => {
		if (!open) return [];
		const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
		const all: SearchResult[] = [];

		const gpid = globalProviderFilter.id;
		const gpt = globalProviderFilter.providerType;
		const providerScoped = new Set(['notification_trackers', 'command_trackers', 'actions']);
		const typeScoped = new Set(['tracking_configs', 'template_configs', 'command_configs', 'command_template_configs']);

		for (const group of GROUPS) {
			const cache = cacheMap[group.key];
			if (!cache) continue;
			for (const entity of cache.items) {
				// Apply global provider filter
				if (gpid && group.key === 'providers' && entity.id !== gpid) continue;
				if (gpid && providerScoped.has(group.key) && (entity as any).provider_id !== gpid) continue;
				if (gpt && typeScoped.has(group.key) && (entity as any).provider_type !== gpt) continue;

				const mapped = group.mapFn(entity);
				const name = entity.name || '';
				const searchable = `${name} ${mapped.detail} ${t(group.label)}`.toLowerCase();
				if (terms.length > 0 && !terms.every(term => searchable.includes(term))) continue;
				all.push({
					id: entity.id,
					name,
					icon: mapped.icon,
					detail: mapped.detail,
					href: group.href,
					group: t(group.label),
					groupIcon: group.icon,
				});
			}
		}
		return all;
	});

	/** Group results by entity type for display. */
	const groupedResults = $derived.by(() => {
		const groups: { label: string; icon: string; items: SearchResult[] }[] = [];
		const seen = new Set<string>();
		for (const r of results) {
			if (!seen.has(r.group)) {
				seen.add(r.group);
				groups.push({ label: r.group, icon: r.groupIcon, items: [] });
			}
			groups.find(g => g.label === r.group)!.items.push(r);
		}
		return groups;
	});

	const flatResults = $derived(results);
	const flatIndexMap = $derived(new Map(flatResults.map((item, idx) => [item, idx])));

	async function openPalette() {
		open = true;
		query = '';
		activeIndex = 0;
		loading = true;
		await fetchAllCaches();
		loading = false;
		// Focus input after mount
		requestAnimationFrame(() => inputEl?.focus());
	}

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

	function navigateTo(result: SearchResult) {
		closePalette();
		requestHighlight(result.id);
		goto(result.href);
	}

	function handleKeydown(e: KeyboardEvent) {
		if (!open) {
			// Global shortcut: Ctrl+K / Cmd+K
			if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
				e.preventDefault();
				openPalette();
			}
			return;
		}

		if (e.key === 'Escape') {
			closePalette();
			return;
		}
		if (e.key === 'ArrowDown') {
			e.preventDefault();
			activeIndex = Math.min(activeIndex + 1, flatResults.length - 1);
			scrollToActive();
		} else if (e.key === 'ArrowUp') {
			e.preventDefault();
			activeIndex = Math.max(activeIndex - 1, 0);
			scrollToActive();
		} else if (e.key === 'Enter' && flatResults[activeIndex]) {
			e.preventDefault();
			navigateTo(flatResults[activeIndex]);
		}
	}

	function scrollToActive() {
		requestAnimationFrame(() => {
			const el = document.querySelector('.sp-item.sp-active');
			el?.scrollIntoView({ block: 'nearest' });
		});
	}

	// Reset active index when query changes
	$effect(() => {
		query; // track
		activeIndex = 0;
	});
</script>

<svelte:window onkeydown={handleKeydown} />

{#if open}
	<!-- Backdrop -->
	<div class="sp-backdrop" onclick={closePalette} onkeydown={(e) => { if (e.key === 'Escape') closePalette(); }} role="button" tabindex="-1" aria-label={t('searchPalette.close')}></div>

	<!-- Palette -->
	<div class="sp-container">
		<div class="sp-input-row">
			<MdiIcon name="mdiMagnify" size={20} />
			<input
				bind:this={inputEl}
				bind:value={query}
				placeholder={t('searchPalette.placeholder')}
				class="sp-input"
				type="text"
				role="combobox"
				aria-expanded={flatResults.length > 0}
				aria-controls={listboxId}
				aria-activedescendant={flatResults.length > 0 ? optionId(activeIndex) : undefined}
				aria-autocomplete="list"
			/>
			<kbd class="sp-kbd">ESC</kbd>
		</div>

		<div class="sp-results" id={listboxId} role="listbox">
			{#if loading}
				<div class="sp-empty">
					<div class="w-4 h-4 rounded-full border-2 border-[var(--color-primary)] border-t-transparent animate-spin"></div>
					<span>{t('common.loading')}</span>
				</div>
			{:else if flatResults.length === 0}
				<div class="sp-empty">
					<MdiIcon name="mdiMagnifyClose" size={24} />
					<span>{query ? t('searchPalette.noResults') : t('searchPalette.typeToSearch')}</span>
				</div>
			{:else}
				{#each groupedResults as group}
					<div class="sp-group-header">
						<MdiIcon name={group.icon} size={14} />
						{group.label}
					</div>
					{#each group.items as item}
						{@const flatIdx = flatIndexMap.get(item) ?? -1}
						<button
							id={optionId(flatIdx)}
							role="option"
							aria-selected={flatIdx === activeIndex}
							class="sp-item"
							class:sp-active={flatIdx === activeIndex}
							onclick={() => navigateTo(item)}
							onmouseenter={() => activeIndex = flatIdx}
						>
							<span class="sp-item-icon"><MdiIcon name={item.icon} size={18} /></span>
							<span class="sp-item-name">{item.name}</span>
							{#if item.detail}
								<span class="sp-item-detail">{item.detail}</span>
							{/if}
						</button>
					{/each}
				{/each}
			{/if}
		</div>

		<div class="sp-footer">
			<span><kbd>↑↓</kbd> {t('searchPalette.navigate')}</span>
			<span><kbd>↵</kbd> {t('searchPalette.open')}</span>
			<span><kbd>esc</kbd> {t('searchPalette.close')}</span>
		</div>
	</div>
{/if}

<style>
	.sp-backdrop {
		position: fixed;
		top: 0; left: 0; right: 0; bottom: 0;
		z-index: 9998;
		background: rgba(0, 0, 0, 0.55);
		backdrop-filter: blur(8px) saturate(120%);
		-webkit-backdrop-filter: blur(8px) saturate(120%);
	}
	.sp-container {
		position: fixed;
		top: 18vh;
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
		width: min(640px, 92vw);
		--sp-solid-bg: #131520;
		background: var(--sp-solid-bg);
		border: 1px solid var(--color-rule-strong);
		border-radius: 18px;
		box-shadow: var(--shadow-card), 0 30px 80px -20px rgba(0, 0, 0, 0.6);
		overflow: hidden;
	}
	:global([data-theme="light"]) .sp-container { --sp-solid-bg: #fafafe; }
	.sp-container::after {
		content: '';
		position: absolute;
		inset: 0;
		border-radius: inherit;
		pointer-events: none;
		background: linear-gradient(180deg, var(--color-highlight), transparent 30%);
		opacity: 0.4;
	}
	.sp-input-row {
		display: flex;
		align-items: center;
		gap: 0.65rem;
		padding: 0.95rem 1.15rem;
		border-bottom: 1px solid var(--color-border);
		color: var(--color-muted-foreground);
		position: relative;
		z-index: 1;
	}
	.sp-input {
		flex: 1;
		border: none;
		outline: none;
		background: transparent;
		font-size: 0.95rem;
		color: var(--color-foreground);
		font-family: var(--font-sans);
		letter-spacing: -0.005em;
	}
	.sp-input::placeholder { color: var(--color-muted-foreground); }
	.sp-kbd {
		font-size: 0.62rem;
		font-family: var(--font-mono);
		padding: 0.2rem 0.45rem;
		border-radius: 6px;
		background: var(--color-glass-strong);
		color: var(--color-foreground);
		border: 1px solid var(--color-border);
	}
	.sp-results {
		max-height: 52vh;
		overflow-y: auto;
		scrollbar-width: thin;
		padding: 0.35rem;
		position: relative;
		z-index: 1;
	}
	.sp-empty {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 0.55rem;
		padding: 2.5rem 2rem;
		color: var(--color-muted-foreground);
		font-size: 0.85rem;
	}
	.sp-group-header {
		display: flex;
		align-items: center;
		gap: 0.45rem;
		padding: 0.6rem 0.85rem 0.35rem;
		font-size: 0.6rem;
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.16em;
		color: var(--color-muted-foreground);
		font-family: var(--font-mono);
	}
	.sp-group-header::after {
		content: '';
		flex: 1;
		height: 1px;
		background: var(--color-border);
		margin-left: 0.35rem;
	}
	.sp-item {
		display: flex;
		align-items: center;
		gap: 0.65rem;
		width: 100%;
		padding: 0.55rem 0.85rem;
		border-radius: 10px;
		border: 1px solid transparent;
		background: transparent;
		color: var(--color-foreground);
		font-size: 0.88rem;
		cursor: pointer;
		text-align: left;
		transition: background 0.12s, border-color 0.12s;
		font-family: var(--font-sans);
	}
	.sp-item:hover, .sp-item.sp-active {
		background: var(--color-glass-strong);
		border-color: var(--color-border);
	}
	.sp-item.sp-active {
		background: linear-gradient(135deg,
			color-mix(in srgb, var(--color-primary) 14%, transparent),
			color-mix(in srgb, var(--color-orchid) 14%, transparent));
		border-color: color-mix(in srgb, var(--color-primary) 40%, var(--color-border));
		box-shadow: inset 0 1px 0 var(--color-highlight);
	}
	.sp-item-icon {
		flex-shrink: 0;
		color: var(--color-muted-foreground);
		width: 28px; height: 28px;
		display: grid; place-items: center;
		border-radius: 8px;
		background: var(--color-glass-strong);
		border: 1px solid var(--color-border);
	}
	.sp-item.sp-active .sp-item-icon {
		color: var(--color-primary);
		background: var(--color-glass-elev);
	}
	.sp-item-name {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-weight: 500;
	}
	.sp-item-detail {
		font-size: 0.7rem;
		font-family: var(--font-mono);
		color: var(--color-muted-foreground);
		padding: 0.12rem 0.5rem;
		border-radius: 9999px;
		background: var(--color-glass-strong);
		border: 1px solid var(--color-border);
		white-space: nowrap;
	}
	.sp-footer {
		display: flex;
		gap: 1rem;
		padding: 0.6rem 1.15rem;
		border-top: 1px solid var(--color-border);
		font-size: 0.65rem;
		color: var(--color-muted-foreground);
		position: relative;
		z-index: 1;
		background: var(--color-glass-strong);
	}
	.sp-footer kbd {
		font-family: var(--font-mono);
		padding: 0.1rem 0.35rem;
		border-radius: 5px;
		background: var(--color-glass);
		border: 1px solid var(--color-border);
		font-size: 0.62rem;
		color: var(--color-foreground);
	}
</style>
