<script lang="ts">
	interface Prediction {
		place_id: string;
		name: string;
		address: string;
		types: string[];
	}

	let {
		value = $bindable(''),
		placeholder = 'Search for a place...',
		onSelect
	}: {
		value: string;
		placeholder?: string;
		onSelect: (details: { place_id: string; name: string; address: string; latitude: number | null; longitude: number | null; category: 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 res = await fetch('/api/trips/places/autocomplete', {
				method: 'POST', credentials: 'include',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ query })
			});
			if (res.ok) {
				const data = await res.json();
				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;
		try {
			const res = await fetch(`/api/trips/places/details?place_id=${encodeURIComponent(pred.place_id)}`, { credentials: 'include' });
			const details = await res.json();
			onSelect({ ...details, place_id: pred.place_id });
		} catch {
			onSelect({ place_id: pred.place_id, name: pred.name, address: pred.address, latitude: null, longitude: null, category: '' });
		}
	}
</script>

<div class="places-wrap">
	<input type="text" class="places-input" {placeholder} bind:value oninput={onInput}
		onfocus={() => { if (predictions.length > 0) showDropdown = true; }}
		onblur={() => setTimeout(() => showDropdown = false, 200)} />
	{#if showDropdown}
		<div class="places-dropdown">
			{#each predictions as pred}
				<button class="places-option" onmousedown={() => selectPlace(pred)}>
					<span class="places-name">{pred.name}</span>
					{#if pred.address}<span class="places-addr">{pred.address}</span>{/if}
				</button>
			{/each}
		</div>
	{/if}
</div>

<style>
	.places-wrap { position: relative; }
	.places-input {
		width: 100%; padding: 10px 12px; border-radius: var(--radius-md);
		border: 1px solid var(--border); background: var(--surface-secondary);
		color: var(--text-1); font-size: var(--text-base); font-family: var(--font);
	}
	.places-input:focus { outline: none; border-color: var(--accent); }
	.places-dropdown {
		position: absolute; top: 100%; left: 0; right: 0; margin-top: var(--sp-1);
		background: var(--card); border: 1px solid var(--border); border-radius: 10px;
		box-shadow: var(--card-shadow); z-index: 50; max-height: 200px; overflow-y: auto;
	}
	.places-option {
		display: flex; flex-direction: column; width: 100%; padding: 10px 14px;
		background: none; border: none; border-bottom: 1px solid var(--border);
		text-align: left; cursor: pointer; transition: background var(--transition); font-family: var(--font);
	}
	.places-option:last-child { border-bottom: none; }
	.places-option:hover { background: var(--card-hover); }
	.places-name { font-size: var(--text-sm); font-weight: 500; color: var(--text-1); }
	.places-addr { font-size: var(--text-xs); color: var(--text-3); margin-top: 1px; }
</style>
