document.addEventListener('DOMContentLoaded',()=>{
const input=document.querySelector('[data-address-autocomplete]');
const cp=document.querySelector('[data-postcode]');
const city=document.querySelector('[data-city]');
const box=document.getElementById('addressSuggestions');
if(!input||!box)return;

let timer;
let controller;

const hide=()=>{
    box.innerHTML='';
    box.hidden=true;
};

input.addEventListener('input',()=>{
    clearTimeout(timer);
    const q=input.value.trim();

    if(q.length<3){
        hide();
        return;
    }

    timer=setTimeout(async()=>{
        if(controller) controller.abort();
        controller=new AbortController();

        const url=new URL('https://data.geopf.fr/geocodage/completion/');
        url.searchParams.set(
            'text',
            [q,cp?.value,city?.value].filter(Boolean).join(' ')
        );
        url.searchParams.set('type','StreetAddress');
        url.searchParams.set('maximumResponses','6');

        try{
            const response=await fetch(url,{signal:controller.signal});
            const data=await response.json();
            const results=data.results || [];

            box.innerHTML='';

            results.forEach(row=>{
                const full=row.fulltext || row.label || row.name || '';
                const zip=row.zipcode || row.postcode || '';
                const town=row.city || row.cityname || row.locality || '';

                if(!full)return;

                const button=document.createElement('button');
                button.type='button';
                button.className='address-suggestion';
                button.textContent=full;

                button.addEventListener('click',()=>{
                    let address=full;
                    if(zip && full.includes(zip)){
                        address=full.split(zip)[0].replace(/,\s*$/,'').trim();
                    }

                    input.value=address;
                    if(cp && zip) cp.value=zip;
                    if(city && town) city.value=town.toLocaleUpperCase('fr-FR');
                    hide();
                });

                box.appendChild(button);
            });

            box.hidden=!box.children.length;
        }catch(error){
            if(error.name!=='AbortError') hide();
        }
    },350);
});

document.addEventListener('click',event=>{
    if(!box.contains(event.target) && event.target!==input) hide();
});
});
