<template>
<form>
	<div>
	<label>Given name</label><input required type="text" name="gname"/>
	</div>
	
	<div>
	<label>Surname</label><input required type="text" name="sname"/>
	</div>
	
	<div>
	<label>Email</label><input type="email" name="email"/>
	</div>
	
	<div>
	<label>Password</label><input requried type="password" name="pass"/>
	</div>
	
	<div>
	<label>Country</label>
	<select name="country">
  <option value="USA">USA</option>
  <option value="Canada">Canada</option>
  </select>
  </div>
  
  <div class="address-entry">
  <label for="">Address</label>
  <input type="text" @input="searchLocation" :value="address.full">
  <dropdown v-if="addresses && addresses.length"
  :entries="addresses.map(a => ({text: a.full_address, value: a}))"
  @select="setAddress"
  >
  </dropdown>
  </div>

	<div><label>NMLS ID</label><input type="text" name="nmls"/></div>
	
	<div><span class="error">{{error}}</span></div>
	
	<div>
	<button class="btn" @click="submit" type="button">Continue</button>
	</div>
</form>
</template>

<script setup>
import { ref } from "vue"
import Dropdown from "./dropdown.vue"

const error = ref('')
const addresses = ref([])
const user = ref({})
const address = ref({})
const locationsId = ref(null)

function searchLocation(e) {
    address.value.full = e.target.value
    clearTimeout(locationsId.value)
    locationsId.value = setTimeout(getLocations, 1000, e)
}

function getLocations(e) {
    let prefix = "https://api.mapbox.com/search/searchbox/v1/suggest?"
    let search = e.target.value
    let key = encodeURIComponent(process.env.MAPBOX_API_KEY)
    
    if (!search) return
    
    fetch(`${prefix}q=${search}&proximity=ip&access_token=${key}&session_token=1`
    ).then(resp => resp.json()).then(entries => {
        if (!entries?.suggestions) {
            addresses.value = null
            return
        }
        
        addresses.value = entries.suggestions.filter(e => e.full_address)
    })
}

function setAddress(a) {

    address.value = {
        id: address.value.id,
        full: a.full_address,
        street: a.address,
        city: a.context?.place.name ?? '',
        region: a.context?.region?.name ?? '',
        country: a.context?.country?.name ?? '',
        zip: a.context?.postcode?.name ?? '',
    }
    addresses.value = null
}

function submit() {
}
</script>

<style scoped>
form > div {
	display: flex;
	max-width: 350px;
	justify-content: space-between;
	margin: 10px;
	position: relative;
}

button {
  margin: auto;
  min-width: 90px;
  display: block;
}

span.error {
  margin: 10px auto;
  color: darkred;
  
}
</style>
