<script lang="ts">
	import { post } from '$lib/api/client';

	interface Prediction {
		place_id: string;
		name: string;
		address: string;
		description: string;
		types: string[];
	}

	interface PlaceDetails {
		name: string;
		address: string;
		latitude: number | null;
		longitude: number | null;
		types: string[];
		category: string;
	}

	let {
		value = $bindable(''),
		placeholder = 'Search for a place...',
		onSelect
	}: {
		value: string;
		placeholder?: string;
		onSelect: (details: PlaceDetails & { place_id: string }) => void;
	} = $props();

	let predictions = $state<Prediction[]>([]);
	let showDropdown = $state(false);
	let debounceTimer: ReturnType<typeof setTimeout>;

	async function search(query: string) {
		if (query.length < 2) {
			predictions = [];
			showDropdown = false;
			return;
		}
		try {
			const data = await post<{ predictions: Prediction[] }>('/api/places/autocomplete', { query });
			predictions = data.predictions || [];
			showDropdown = predictions.length > 0;
		} catch {
			predictions = [];
		}
	}

	function onInput() {
		clearTimeout(debounceTimer);
		debounceTimer = setTimeout(() => search(value), 250);
	}

	async function selectPlace(pred: Prediction) {
		showDropdown = false;
		value = pred.name;

		// Fetch full details
		try {
			const res = await fetch(`/api/places/details?place_id=${encodeURIComponent(pred.place_id)}`, {
				headers: { 'Authorization': `Bearer ${localStorage.getItem('api_token') || ''}` }
			});
			const details: PlaceDetails = await res.json();
			onSelect({ ...details, place_id: pred.place_id });
		} catch {
			// Fallback with autocomplete data
			onSelect({
				place_id: pred.place_id,
				name: pred.name,
				address: pred.address,
				latitude: null,
				longitude: null,
				types: pred.types,
				category: ''
			});
		}
	}
</script>

<div class="relative">
	<input
		type="text"
		class="input input-bordered w-full"
		{placeholder}
		bind:value
		oninput={onInput}
		onfocus={() => { if (predictions.length > 0) showDropdown = true; }}
		onblur={() => setTimeout(() => showDropdown = false, 200)}
	/>
	{#if showDropdown}
		<div class="absolute top-full left-0 right-0 mt-1 bg-base-200 border border-base-300 rounded-box shadow-xl z-50 max-h-48 overflow-y-auto">
			{#each predictions as pred}
				<button
					class="w-full flex flex-col p-3 hover:bg-base-300 transition-colors text-left"
					onmousedown={() => selectPlace(pred)}
				>
					<span class="font-medium text-sm text-base-content">{pred.name}</span>
					{#if pred.address}
						<span class="text-xs text-base-content/40">{pred.address}</span>
					{/if}
				</button>
			{/each}
		</div>
	{/if}
</div>
