document.addEventListener('DOMContentLoaded', () => {
    const addressInput = document.getElementById('address');
    const cityInput = document.getElementById('city');
    const stateInput = document.getElementById('state');
    const postalInput = document.getElementById('postal');
    const countrySelect = document.getElementById('country');

    if (!addressInput) return;

    let suggestionsBox = document.getElementById('address-suggestions');
    if (!suggestionsBox) {
        suggestionsBox = document.createElement('div');
        suggestionsBox.id = 'address-suggestions';
        suggestionsBox.className = 'absolute w-full mt-1 rounded shadow-lg border border-gray-700 bg-gray-900 text-white max-h-64 overflow-auto';
        suggestionsBox.style.display = 'none';
        suggestionsBox.style.zIndex = '1000';
        // Ensure the parent is positioned
        const parent = addressInput.parentElement;
        if (parent && getComputedStyle(parent).position === 'static') {
            parent.style.position = 'relative';
        }
        parent.appendChild(suggestionsBox);
    }

    let debounceTimer;
    const debounce = (fn, delay = 300) => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(fn, delay);
    };

    function clearSuggestions() {
        suggestionsBox.innerHTML = '';
        suggestionsBox.style.display = 'none';
    }

    function showSuggestions(items) {
        suggestionsBox.innerHTML = '';
        items.forEach(item => {
            const option = document.createElement('div');
            option.className = 'px-3 py-2 cursor-pointer border-b border-gray-800 hover:bg-gray-700';
            option.textContent = item.display_name;
            option.addEventListener('click', () => {
                fillFromSuggestion(item);
                clearSuggestions();
            });
            suggestionsBox.appendChild(option);
        });
        suggestionsBox.style.display = items.length ? 'block' : 'none';
    }

    function fillFromSuggestion(item) {
        if (addressInput) {
            const houseNumber = item.address && item.address.house_number ? item.address.house_number + ' ' : '';
            const road = item.address && item.address.road ? item.address.road : '';
            const addrLine1 = (houseNumber + road).trim();
            addressInput.value = addrLine1 || item.display_name;
        }
        if (cityInput) {
            cityInput.value = item.address.city || item.address.town || item.address.village || item.address.hamlet || '';
        }
        if (stateInput) {
            stateInput.value = item.address.state || item.address.region || '';
        }
        if (postalInput) {
            postalInput.value = item.address.postcode || '';
        }
        if (countrySelect && item.address.country_code) {
            const countryCode = item.address.country_code.toUpperCase();
            const found = Array.from(countrySelect.options).some(opt => {
                if (opt.value.toUpperCase() === countryCode) {
                    countrySelect.value = opt.value;
                    return true;
                }
                return false;
            });
            if (!found && item.address.country) {
                // If the exact code is not present, leave current selection as-is
            }
        }
    }

    async function searchAddresses(query) {
        // Free, no-key geocoding API
        const url = `https://nominatim.openstreetmap.org/search?format=json&addressdetails=1&limit=5&q=${encodeURIComponent(query)}`;
        try {
            const res = await fetch(url, {
                headers: { 'Accept': 'application/json' }
            });
            if (!res.ok) throw new Error('Network error');
            const data = await res.json();
            return data;
        } catch (e) {
            console.warn('Address lookup failed:', e);
            return [];
        }
    }

    addressInput.addEventListener('input', () => {
        const q = addressInput.value.trim();
        if (q.length < 3) {
            clearSuggestions();
            return;
        }
        debounce(async () => {
            const results = await searchAddresses(q);
            showSuggestions(results);
        }, 350);
    });

    // Hide suggestions when clicking outside
    document.addEventListener('click', (e) => {
        if (!suggestionsBox.contains(e.target) && e.target !== addressInput) {
            clearSuggestions();
        }
    });

    // Basic keyboard navigation (optional)
    addressInput.addEventListener('keydown', (e) => {
        if (suggestionsBox.style.display === 'none') return;
        const options = Array.from(suggestionsBox.children);
        if (!options.length) return;
        const active = suggestionsBox.querySelector('.bg-gray-700');
        let idx = active ? options.indexOf(active) : -1;
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (idx < options.length - 1) idx++;
            options.forEach(o => o.classList.remove('bg-gray-700'));
            options[idx].classList.add('bg-gray-700');
            options[idx].scrollIntoView({ block: 'nearest' });
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (idx > 0) idx--;
            options.forEach(o => o.classList.remove('bg-gray-700'));
            options[idx].classList.add('bg-gray-700');
            options[idx].scrollIntoView({ block: 'nearest' });
        } else if (e.key === 'Enter') {
            if (idx >= 0) {
                e.preventDefault();
                options[idx].click();
            }
        } else if (e.key === 'Escape') {
            clearSuggestions();
        }
    });
});
