(() => {
    'use strict';

    const config={
        people:'/public/communications/repertoire/personnes',
        activities:'/public/communications/repertoire/activites'
    };

    const normalize=value => String(value || '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g,'')
        .toLowerCase()
        .trim();

    function findControlByLabel(words){
        const labels=[...document.querySelectorAll('label')];

        for(const label of labels){
            const text=normalize(label.textContent);

            if(words.every(word => text.includes(normalize(word)))){
                const explicit=label.getAttribute('for');

                if(explicit){
                    const control=document.getElementById(explicit);
                    if(control){
                        return {control,label};
                    }
                }

                const nested=label.querySelector('input,select,textarea');
                if(nested){
                    return {control:nested,label};
                }

                const next=label.nextElementSibling;
                if(next?.matches?.('input,select,textarea')){
                    return {control:next,label};
                }
            }
        }

        const all=[...document.querySelectorAll('input,select,textarea')];

        for(const control of all){
            const haystack=normalize([
                control.name,
                control.id,
                control.placeholder,
                control.getAttribute('aria-label')
            ].join(' '));

            if(words.every(word => haystack.includes(normalize(word)))){
                return {control,label:null};
            }
        }

        return null;
    }

    function createAutocomplete(control,kind){
        if(!control || control.dataset.cdaDirectoryReady==='1'){
            return;
        }

        control.dataset.cdaDirectoryReady='1';
        control.autocomplete='off';

        const wrapper=document.createElement('div');
        wrapper.className='cda-directory-autocomplete';

        control.parentNode.insertBefore(wrapper,control);
        wrapper.appendChild(control);

        const results=document.createElement('div');
        results.className='cda-directory-results';
        results.hidden=true;
        wrapper.appendChild(results);

        const hidden=document.createElement('input');
        hidden.type='hidden';
        hidden.name=kind==='people'
            ? 'destinataire_source'
            : 'activite_source';
        wrapper.appendChild(hidden);

        let timer=null;
        let currentItems=[];

        const endpoint=kind==='people'
            ? config.people
            : config.activities;

        control.addEventListener('input',() => {
            clearTimeout(timer);
            hidden.value='';

            const query=control.value.trim();

            if(kind==='people' && query.length<2){
                close();
                return;
            }

            timer=setTimeout(
                () => load(query),
                180
            );
        });

        control.addEventListener('focus',() => {
            if(kind==='activities' && !control.value.trim()){
                load('');
            }
        });

        control.addEventListener('keydown',event => {
            const active=results.querySelector(
                '.cda-directory-result.is-active'
            );
            const buttons=[...results.querySelectorAll(
                '.cda-directory-result'
            )];

            if(event.key==='ArrowDown'){
                event.preventDefault();
                const index=Math.min(
                    buttons.length-1,
                    Math.max(-1,buttons.indexOf(active))+1
                );
                activate(buttons,index);
            }

            if(event.key==='ArrowUp'){
                event.preventDefault();
                const index=Math.max(
                    0,
                    (buttons.indexOf(active)<0 ? buttons.length : buttons.indexOf(active))-1
                );
                activate(buttons,index);
            }

            if(event.key==='Enter' && active){
                event.preventDefault();
                active.click();
            }

            if(event.key==='Escape'){
                close();
            }
        });

        document.addEventListener('click',event => {
            if(!wrapper.contains(event.target)){
                close();
            }
        });

        async function load(query){
            results.hidden=false;
            results.innerHTML='<div class="cda-directory-state">Recherche…</div>';

            try{
                const response=await fetch(
                    `${endpoint}?q=${encodeURIComponent(query)}`,
                    {headers:{Accept:'application/json'}}
                );

                if(!response.ok){
                    throw new Error(`HTTP ${response.status}`);
                }

                const payload=await response.json();
                currentItems=Array.isArray(payload.results)
                    ? payload.results
                    : [];

                render(currentItems);
            }catch(error){
                results.innerHTML=
                    '<div class="cda-directory-state is-error">'
                    +'Recherche indisponible.'
                    +'</div>';
            }
        }

        function render(items){
            results.innerHTML='';

            if(!items.length){
                results.innerHTML=
                    '<div class="cda-directory-state">Aucun résultat.</div>';
                return;
            }

            items.forEach((item,index) => {
                const button=document.createElement('button');
                button.type='button';
                button.className='cda-directory-result';
                button.dataset.index=String(index);

                const icon=document.createElement('span');
                icon.className='cda-directory-icon';
                icon.textContent=item.icon || (kind==='people' ? '👤' : '🎨');

                const content=document.createElement('span');
                content.className='cda-directory-content';

                const title=document.createElement('strong');
                title.textContent=kind==='people'
                    ? item.name
                    : item.label;

                const subtitle=document.createElement('small');
                subtitle.textContent=item.subtitle || item.type_label || '';

                content.append(title,subtitle);
                button.append(icon,content);

                button.addEventListener('click',() => {
                    choose(item);
                });

                results.appendChild(button);
            });
        }

        function choose(item){
            if(kind==='people'){
                control.value=item.name || '';
                hidden.value=[
                    item.source_table,
                    item.source_id
                ].join(':');

                fillEmail(item.email || '');

                control.dispatchEvent(
                    new CustomEvent(
                        'cda:person-selected',
                        {bubbles:true,detail:item}
                    )
                );
            }else{
                control.value=[
                    item.type_label || '',
                    item.code || '',
                    item.label || ''
                ].filter(Boolean).join(' — ');

                hidden.value=item.composite_value
                    || `${item.type}:${item.source_id}`;

                /*
                 * Le champ historique attendait un ID.
                 * On conserve son name mais on stocke la vraie valeur
                 * dans un champ caché dédié, tout en gardant un libellé lisible.
                 */
                control.dataset.selectedId=String(item.source_id || '');
                control.dataset.selectedType=String(item.type || '');

                ensureLegacyActivityFields(control,item);

                control.dispatchEvent(
                    new CustomEvent(
                        'cda:activity-selected',
                        {bubbles:true,detail:item}
                    )
                );
            }

            close();
        }

        function close(){
            results.hidden=true;
            results.innerHTML='';
        }

        function activate(buttons,index){
            buttons.forEach(button =>
                button.classList.remove('is-active')
            );

            if(buttons[index]){
                buttons[index].classList.add('is-active');
                buttons[index].scrollIntoView({block:'nearest'});
            }
        }
    }

    function fillEmail(email){
        const found=findControlByLabel(['e-mail','individuel'])
            || findControlByLabel(['email','individuel'])
            || findControlByLabel(['mail','individuel']);

        if(!found?.control){
            return;
        }

        found.control.value=email;
        found.control.dispatchEvent(
            new Event('input',{bubbles:true})
        );
        found.control.dispatchEvent(
            new Event('change',{bubbles:true})
        );

        found.control.classList.toggle(
            'cda-directory-missing',
            email===''
        );

        let hint=found.control.parentElement?.querySelector(
            '.cda-directory-email-hint'
        );

        if(!hint){
            hint=document.createElement('small');
            hint.className='cda-directory-email-hint';
            found.control.insertAdjacentElement('afterend',hint);
        }

        hint.textContent=email
            ? 'E-mail récupéré automatiquement.'
            : 'Aucun e-mail valide n’est enregistré pour cette personne.';
    }

    function ensureLegacyActivityFields(control,item){
        const form=control.closest('form') || document.body;

        const fields={
            cible_id:String(item.source_id || ''),
            atelier_ou_groupe_id:String(item.source_id || ''),
            cible_type:String(item.type || ''),
            atelier_ou_groupe_type:String(item.type || '')
        };

        Object.entries(fields).forEach(([name,value]) => {
            let field=form.querySelector(
                `input[type="hidden"][name="${name}"]`
            );

            if(!field){
                field=document.createElement('input');
                field.type='hidden';
                field.name=name;
                form.appendChild(field);
            }

            field.value=value;
        });
    }

    function enhance(){
        const person=findControlByLabel(['nom','individuel']);
        const activity=findControlByLabel(['id','atelier','groupe']);

        if(person?.control){
            person.control.placeholder=
                person.control.placeholder
                || 'Saisir au moins 2 lettres du nom';
            createAutocomplete(person.control,'people');

            addHelp(
                person.control,
                'Tapez le nom puis choisissez la personne dans la liste.'
            );
        }

        if(activity?.control){
            activity.control.placeholder=
                'Rechercher un atelier ou un groupe';
            createAutocomplete(activity.control,'activities');

            addHelp(
                activity.control,
                'Cliquez dans le champ ou saisissez le nom/code de l’atelier ou du groupe.'
            );
        }

        bindTargetBehaviour(person?.control,activity?.control);
    }

    function addHelp(control,text){
        const parent=control.parentElement;

        if(!parent || parent.querySelector('.cda-directory-help')){
            return;
        }

        const help=document.createElement('small');
        help.className='cda-directory-help';
        help.textContent=text;
        control.insertAdjacentElement('afterend',help);
    }

    function bindTargetBehaviour(personControl,activityControl){
        const target=findControlByLabel(['cible'])?.control;

        if(!target){
            return;
        }

        const update=() => {
            const value=normalize(
                target.options?.[target.selectedIndex]?.text
                || target.value
            );

            const personMode=[
                'personne',
                'individuel',
                'adherent',
                'membre',
                'professeur'
            ].some(token => value.includes(token));

            const activityMode=[
                'atelier',
                'groupe',
                'cours'
            ].some(token => value.includes(token));

            if(personControl){
                personControl.closest(
                    '.cda-directory-autocomplete'
                )?.classList.toggle(
                    'is-recommended',
                    personMode
                );
            }

            if(activityControl){
                activityControl.closest(
                    '.cda-directory-autocomplete'
                )?.classList.toggle(
                    'is-recommended',
                    activityMode
                );
            }
        };

        target.addEventListener('change',update);
        update();
    }

    if(document.readyState==='loading'){
        document.addEventListener('DOMContentLoaded',enhance);
    }else{
        enhance();
    }
})();
