<script lang="ts">
	import { currentCollective } from '$lib/stores/collective';
	import { runSearch, type SearchRow, type SearchResultType } from '$lib/stores/search';
	import { Search, FileText, CheckSquare, ShoppingCart } from 'lucide-svelte';
	import * as m from '$lib/paraglide/messages';
	import ScreenMasthead from '$lib/components/ScreenMasthead.svelte';

	let query = $state('');
	let results = $state<SearchRow[]>([]);
	let loading = $state(false);

	// Filter chips — at least one type must be active; if all three are active, no filter is sent.
	let showItems = $state(true);
	let showTasks = $state(true);
	let showNotes = $state(true);

	let debounceTimer: ReturnType<typeof setTimeout> | null = null;
	const DEBOUNCE_MS = 300;

	$effect(() => {
		// Recompute whenever query or filters change; the debounce timer absorbs keystrokes.
		const q = query.trim();
		const activeTypes = [
			showItems ? ('shopping_item' as SearchResultType) : null,
			showTasks ? ('task' as SearchResultType) : null,
			showNotes ? ('note' as SearchResultType) : null
		].filter((t): t is SearchResultType => t !== null);

		if (debounceTimer) clearTimeout(debounceTimer);
		if (q.length < 2 || !$currentCollective) {
			results = [];
			loading = false;
			return;
		}
		loading = true;
		const col = $currentCollective.id;
		debounceTimer = setTimeout(async () => {
			const types = activeTypes.length === 3 ? undefined : activeTypes;
			results = await runSearch(col, q, types ? { types } : {});
			loading = false;
		}, DEBOUNCE_MS);
	});

	const grouped = $derived({
		shopping_item: results.filter((r) => r.result_type === 'shopping_item'),
		task: results.filter((r) => r.result_type === 'task'),
		note: results.filter((r) => r.result_type === 'note')
	});

	function linkFor(r: SearchRow): string {
		switch (r.result_type) {
			case 'shopping_item':
				return r.list_id ? `/lists/${r.list_id}` : '/lists';
			case 'task':
				return r.list_id ? `/tasks/${r.list_id}` : '/tasks';
			case 'note':
				return `/notes/${r.id}`;
		}
	}
</script>

<svelte:head><title>{m.search_title()} — Colectivo</title></svelte:head>

<div class="flex h-full flex-col overflow-hidden">
	<ScreenMasthead label={m.masthead_search_label()} title={m.masthead_search_title()} />

	<div class="flex flex-col gap-3 px-4 pb-3 md:px-6">
		<div class="relative">
			<Search size={14} strokeWidth={1.5} class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
			<input
				bind:value={query}
				placeholder={m.search_placeholder()}
				class="w-full rounded-md bg-surface-raised pl-9 pr-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-black/20 dark:focus:ring-white/20"
			/>
		</div>

		<!-- Filter chips -->
		<div class="flex gap-2">
			<button
				type="button"
				onclick={() => (showItems = !showItems)}
				aria-pressed={showItems}
				class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors
					{showItems
						? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900'
						: 'bg-surface-raised text-text-secondary hover:bg-black/5 dark:hover:bg-white/5'}"
			>
				<ShoppingCart size={12} strokeWidth={1.5} />
				{m.search_filter_lists()}
			</button>
			<button
				type="button"
				onclick={() => (showTasks = !showTasks)}
				aria-pressed={showTasks}
				class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors
					{showTasks
						? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900'
						: 'bg-surface-raised text-text-secondary hover:bg-black/5 dark:hover:bg-white/5'}"
			>
				<CheckSquare size={12} strokeWidth={1.5} />
				{m.search_filter_tasks()}
			</button>
			<button
				type="button"
				onclick={() => (showNotes = !showNotes)}
				aria-pressed={showNotes}
				class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors
					{showNotes
						? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900'
						: 'bg-surface-raised text-text-secondary hover:bg-black/5 dark:hover:bg-white/5'}"
			>
				<FileText size={12} strokeWidth={1.5} />
				{m.search_filter_notes()}
			</button>
		</div>
	</div>

	<div class="flex-1 overflow-y-auto px-4 py-4 md:px-6">
		{#if query.trim().length < 2}
			<p class="text-sm text-text-secondary">{m.search_hint()}</p>
		{:else if loading}
			<p class="text-sm text-text-secondary">{m.loading()}</p>
		{:else if results.length === 0}
			<p class="text-sm text-text-secondary">{m.search_empty()}</p>
		{:else}
			{#if grouped.shopping_item.length > 0}
				<section data-testid="search-group-shopping_item" class="mb-6">
					<h2 class="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-secondary">
						<ShoppingCart size={12} strokeWidth={1.5} />
						{m.search_group_shopping_items()}
						<span class="ml-auto rounded-full bg-slate-200 px-2 py-0.5 text-[10px] font-semibold text-slate-700 dark:bg-slate-800 dark:text-slate-300">
							{grouped.shopping_item.length} {grouped.shopping_item.length === 1 ? 'MATCH' : 'MATCHES'}
						</span>
					</h2>
					<div class="space-y-1">
						{#each grouped.shopping_item as r (r.id)}
							<a
								href={linkFor(r)}
								data-testid="search-result"
								class="block rounded-md bg-surface-raised px-3 py-2 text-sm text-text-primary hover:bg-black/5 dark:hover:bg-white/5"
							>
								<p class="font-medium">{r.title ?? ''}</p>
								{#if r.snippet && r.snippet !== r.title}
									<p class="truncate text-xs text-text-secondary">{r.snippet}</p>
								{/if}
							</a>
						{/each}
					</div>
				</section>
			{/if}

			{#if grouped.task.length > 0}
				<section data-testid="search-group-task" class="mb-6">
					<h2 class="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-secondary">
						<CheckSquare size={12} strokeWidth={1.5} />
						{m.search_group_tasks()}
						<span class="ml-auto rounded-full bg-slate-200 px-2 py-0.5 text-[10px] font-semibold text-slate-700 dark:bg-slate-800 dark:text-slate-300">
							{grouped.task.length} {grouped.task.length === 1 ? 'MATCH' : 'MATCHES'}
						</span>
					</h2>
					<div class="space-y-1">
						{#each grouped.task as r (r.id)}
							<a
								href={linkFor(r)}
								data-testid="search-result"
								class="block rounded-md bg-surface-raised px-3 py-2 text-sm text-text-primary hover:bg-black/5 dark:hover:bg-white/5"
							>
								<p class="font-medium">{r.title ?? ''}</p>
							</a>
						{/each}
					</div>
				</section>
			{/if}

			{#if grouped.note.length > 0}
				<section data-testid="search-group-note" class="mb-6">
					<h2 class="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-secondary">
						<FileText size={12} strokeWidth={1.5} />
						{m.search_group_notes()}
						<span class="ml-auto rounded-full bg-slate-200 px-2 py-0.5 text-[10px] font-semibold text-slate-700 dark:bg-slate-800 dark:text-slate-300">
							{grouped.note.length} {grouped.note.length === 1 ? 'MATCH' : 'MATCHES'}
						</span>
					</h2>
					<div class="space-y-1">
						{#each grouped.note as r (r.id)}
							<a
								href={linkFor(r)}
								data-testid="search-result"
								class="block rounded-md bg-surface-raised px-3 py-2 text-sm text-text-primary hover:bg-black/5 dark:hover:bg-white/5"
							>
								{#if r.title}
									<p class="font-medium">{r.title}</p>
								{/if}
								<p class="truncate text-xs text-text-secondary">{r.snippet}</p>
							</a>
						{/each}
					</div>
				</section>
			{/if}
		{/if}
	</div>
</div>
