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

const emit = defineEmits(['addressSelected'])

const { $t } = useI18n()

const addressInput = ref('')
const searchResults = ref<any[]>([])

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

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

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

<template>
	<div class="relative">
		<Dropdown ref="suggestion" :noAutoFocus="true" placement="bottom-start">
			<template #trigger>
				<TextInput v-model="addressInput" :placeholder="$t('addressSearch.placeholder')" @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>
