<template>
    <div class="flex flex-col gap-3 max-w-md w-full">
        <!-- Row 1: postcode + button -->
        <div class="flex flex-col sm:flex-row gap-3">
            <div class="relative flex-1">
                <label for="postcode-input" class="sr-only">Postcode or city</label>
                <button
                    :disabled="locating"
                    aria-label="Use my location"
                    class="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1.5 px-3 py-1.5
                    bg-primary/85
                    text-white rounded-sm  text-sm font-semibold transition-opacity hover:opacity-80"
                    type="button"
                    @click="useMyLocation"
                >
                    <iconify-icon :class="{ 'animate-spin': locating }" :icon="locating ? 'lucide:loader-circle' : 'lucide:map-pin'" style="font-size:1rem"></iconify-icon>
					<span class="hidden md:inline-flex">Near me</span>
                </button>
                <input
                    id="postcode-input"
                    v-model="postcode"
                    type="text"
                    :placeholder="coords ? 'Using your current location' : 'Enter postcode, e.g. SW1A 1AA'"
                    class="w-full h-14 pr-28 pl-4 bg-white border border-zinc-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent shadow-inner text-base"
                    @keyup.enter="onSearch"
                />
            </div>
            <button
                @click="onSearch"
                :disabled="!postcode.trim() && !coords"
                class="h-14 px-8 bg-primary text-white rounded-xl font-bold text-base shadow-xl hover:bg-primary-dark transition-all disabled:cursor-not-allowed"
            >
                Find Prices
            </button>
        </div>

        <!-- Row 2: fuel type + radius + sort -->
        <div class="grid grid-cols-3 gap-2">
            <select
                v-model="fuelType"
                aria-label="Fuel type"
                class="min-w-0 h-10 px-2 bg-white border border-zinc-300 rounded-xl text-sm font-medium text-zinc-700 focus:outline-none focus:ring-2 focus:ring-accent truncate"
            >
                <option v-for="fuel in FUEL_TYPES" :key="fuel.value" :value="fuel.value">
                    {{ fuel.label }}
                </option>
            </select>
            <select
                v-model="radius"
                aria-label="Search radius"
                class="min-w-0 h-10 px-2 bg-white border border-zinc-300 rounded-xl text-sm font-medium text-zinc-700 focus:outline-none focus:ring-2 focus:ring-accent"
            >
                <!-- <option :value="2">2 miles</option> -->

                <option :value="5">5 miles</option>
                <option :value="10">10 miles</option>
                <option :value="20">20 miles</option>
            </select>
            <select
                v-model="sort"
                aria-label="Sort by"
                class="min-w-0 h-10 px-2 bg-white border border-zinc-300 rounded-xl text-sm font-medium text-zinc-700 focus:outline-none focus:ring-2 focus:ring-accent"
            >
                <option value="reliable">Reliable</option>
                <option value="price">Price</option>
                <option value="distance">Distance</option>
                <option value="updated">Updated</option>
                <option value="brand">Brand</option>
            </select>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { FUEL_TYPES } from '../constants/fuelTypes.js'

const props = defineProps({
    initial: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['search'])

const postcode = ref('')
const coords = ref(null)
const fuelType = ref('e10')
const radius = ref(10)
const sort = ref('reliable')
const locating = ref(false)

let hydrating = false

watch(() => props.initial, (v) => {
    if (!v) return
    hydrating = true
    if (typeof v.postcode === 'string') postcode.value = v.postcode
    if (v.lat != null && v.lng != null) coords.value = { lat: v.lat, lng: v.lng }
    if (v.fuelType) fuelType.value = v.fuelType
    if (v.radius != null) radius.value = Number(v.radius)
    if (v.sort) sort.value = v.sort
    nextTick(() => { hydrating = false })
}, { immediate: true, deep: true })

watch(postcode, () => { coords.value = null })

watch([fuelType, radius, sort], () => {
    if (hydrating) return
    if (postcode.value.trim() || coords.value) onSearch()
})

function useMyLocation() {
    if (!navigator.geolocation) return
    locating.value = true
    navigator.geolocation.getCurrentPosition(
        ({ coords: c }) => {
            coords.value = { lat: c.latitude, lng: c.longitude }
            postcode.value = ''
            locating.value = false
            onSearch()
        },
        () => { locating.value = false },
        { timeout: 8000, enableHighAccuracy: false, maximumAge: 30000 },
    )
}

function onSearch() {
    const hasPostcode = postcode.value.trim().length > 0
    const hasCoords = coords.value !== null
    if (!hasPostcode && !hasCoords) return

    emit('search', {
        postcode: hasPostcode ? postcode.value.trim() : null,
        lat: hasCoords ? coords.value.lat : null,
        lng: hasCoords ? coords.value.lng : null,
        fuelType: fuelType.value,
        radius: radius.value,
        sort: sort.value,
    })
}
</script>
