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

	let open = $state(false);
	let query = $state('');
	let activeIndex = $state(0);
	let loading = $state(false);
	let inputEl: HTMLInputElement;

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

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

	const cacheMap: Record<string, { items: any[] }> = {
		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,
	};

	/** 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[] = [];

		for (const group of GROUPS) {
			const cache = cacheMap[group.key];
			if (!cache) continue;
			for (const entity of cache.items) {
				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);

	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();
		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} role="presentation"></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"
			/>
			<kbd class="sp-kbd">ESC</kbd>
		</div>

		<div class="sp-results">
			{#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, i}
						{@const flatIdx = flatResults.indexOf(item)}
						<button
							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.5);
		backdrop-filter: blur(4px);
	}
	.sp-container {
		position: fixed;
		top: 20vh;
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
		width: min(500px, 90vw);
		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);
		overflow: hidden;
	}
	.sp-input-row {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.75rem 1rem;
		border-bottom: 1px solid var(--color-border);
		color: var(--color-muted-foreground);
	}
	.sp-input {
		flex: 1;
		border: none;
		outline: none;
		background: transparent;
		font-size: 0.9rem;
		color: var(--color-foreground);
	}
	.sp-kbd {
		font-size: 0.6rem;
		font-family: var(--font-mono);
		padding: 0.15rem 0.35rem;
		border-radius: 0.25rem;
		background: var(--color-muted);
		color: var(--color-muted-foreground);
		border: 1px solid var(--color-border);
	}
	.sp-results {
		max-height: 50vh;
		overflow-y: auto;
		scrollbar-width: thin;
		padding: 0.25rem;
	}
	.sp-empty {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 0.5rem;
		padding: 2rem;
		color: var(--color-muted-foreground);
		font-size: 0.85rem;
	}
	.sp-group-header {
		display: flex;
		align-items: center;
		gap: 0.375rem;
		padding: 0.375rem 0.75rem;
		font-size: 0.65rem;
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.04em;
		color: var(--color-muted-foreground);
		font-family: var(--font-mono);
		margin-top: 0.25rem;
	}
	.sp-item {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		width: 100%;
		padding: 0.5rem 0.75rem;
		border-radius: 0.375rem;
		border: none;
		background: transparent;
		color: var(--color-foreground);
		font-size: 0.85rem;
		cursor: pointer;
		text-align: left;
		transition: background 0.1s;
	}
	.sp-item:hover, .sp-item.sp-active {
		background: var(--color-muted);
	}
	.sp-item-icon {
		flex-shrink: 0;
		color: var(--color-muted-foreground);
	}
	.sp-item.sp-active .sp-item-icon {
		color: var(--color-primary);
	}
	.sp-item-name {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.sp-item-detail {
		font-size: 0.7rem;
		font-family: var(--font-mono);
		color: var(--color-muted-foreground);
		padding: 0.1rem 0.35rem;
		border-radius: 9999px;
		background: var(--color-muted);
		white-space: nowrap;
	}
	.sp-footer {
		display: flex;
		gap: 1rem;
		padding: 0.5rem 1rem;
		border-top: 1px solid var(--color-border);
		font-size: 0.65rem;
		color: var(--color-muted-foreground);
	}
	.sp-footer kbd {
		font-family: var(--font-mono);
		padding: 0.05rem 0.25rem;
		border-radius: 0.2rem;
		background: var(--color-muted);
		border: 1px solid var(--color-border);
		font-size: 0.6rem;
	}
</style>
