<script setup lang="ts">
import { Dropdown, ListItem, ListView, TextInput } from '@bagelink/vue'

const emit = defineEmits(['addressSelected'])
let addressInput = $ref('')
let searchResults = $ref<any[]>([])

type MapMarker = {
	lat: number
	lon: number
} | [number, number]

const suggestion = $ref<typeof Dropdown>()
function emitAddress(address: MapMarker) {
	emit('addressSelected', address)
	searchResults = []
	addressInput = ''
}

async function searchAddresses() {
	const addressURL = addressInput.replaceAll(/\s+/g, '+')
	const geocodeUrl = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURI(addressURL)}`
	const res = await fetch(geocodeUrl)
	searchResults = await res.json() || []
	suggestion?.show()
}
</script>

<template>
	<div class="relative">
		<Dropdown ref="suggestion" :noAutoFocus="true" placement="bottom-start">
			<template #trigger>
				<TextInput v-model="addressInput" placeholder="Enter address" @debounce="searchAddresses" />
			</template>
			<ListView class="-mt-2 hm-300px">
				<ListItem v-for="(result, index) in searchResults" :key="index" icon="location_on" :title="result.display_name" @click="emitAddress(result)" />
			</listview>
		</Dropdown>
	</div>
</template>
