(() => {
    const config=window.CDA_SMART_COMMUNICATION;

    if(!config){
        return;
    }

    const search=document.getElementById(
        'smart-recipient-search'
    );
    const results=document.getElementById(
        'smart-recipient-results'
    );
    const selected=document.getElementById(
        'smart-selected-recipient'
    );
    const addressesBox=document.getElementById(
        'smart-addresses'
    );
    const addressList=document.getElementById(
        'smart-address-list'
    );
    const template=document.getElementById(
        'smart-template'
    );
    const object=document.getElementById(
        'smart-object'
    );
    const body=document.getElementById(
        'smart-body'
    );
    const preview=document.getElementById(
        'smart-preview'
    );
    const previewTo=document.getElementById(
        'preview-to'
    );
    const previewObject=document.getElementById(
        'preview-object'
    );
    const unresolved=document.getElementById(
        'smart-unresolved'
    );

    const variables={
        nom_membre:document.getElementById(
            'var-nom-membre'
        ),
        atelier:document.getElementById(
            'var-atelier'
        ),
        creneau:document.getElementById(
            'var-creneau'
        ),
        professeur:document.getElementById(
            'var-professeur'
        ),
        date_limite:document.getElementById(
            'var-date-limite'
        )
    };

    let timer=null;
    let selectedRecipient=null;
    let selectedAddress=null;
    let recipientContext={};

    search?.addEventListener('input',() => {
        clearTimeout(timer);

        const query=search.value.trim();

        if(query.length<2){
            results.innerHTML='';
            return;
        }

        timer=setTimeout(
            () => searchRecipients(query),
            220
        );
    });

    template?.addEventListener(
        'change',
        refreshPreview
    );

    Object.values(variables).forEach(input => {
        input?.addEventListener(
            'input',
            refreshPreview
        );
    });

    object?.addEventListener(
        'input',
        updatePreviewFromEditor
    );

    body?.addEventListener(
        'input',
        updatePreviewFromEditor
    );

    async function searchRecipients(query){
        results.innerHTML=
            '<div class="smart-loading">Recherche…</div>';

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

            const payload=await response.json();

            renderRecipients(payload.results || []);
        }catch(error){
            results.innerHTML=
                '<div class="smart-empty">Recherche indisponible.</div>';
        }
    }

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

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

        for(const item of items){
            const button=document.createElement('button');
            button.type='button';
            button.className='smart-recipient-item';

            const icon=document.createElement('span');
            icon.className='smart-recipient-icon';
            icon.textContent=item.icon || '👤';

            const content=document.createElement('span');

            const title=document.createElement('strong');
            title.textContent=item.name;

            const subtitle=document.createElement('small');
            subtitle.textContent=[
                item.type_label,
                item.subtitle
            ].filter(Boolean).join(' · ');

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

            button.addEventListener(
                'click',
                () => selectRecipient(item)
            );

            results.appendChild(button);
        }
    }

    async function selectRecipient(item){
        selectedRecipient=item;
        selected.hidden=false;
        selected.innerHTML=
            `<strong>${escapeHtml(item.name)}</strong>`
            +`<small>${escapeHtml(item.type_label)}</small>`;

        results.innerHTML='';
        search.value=item.name;

        try{
            const response=await fetch(
                `${config.addressesUrl}?source_type=${encodeURIComponent(item.source_type)}&source_id=${encodeURIComponent(item.source_id)}`,
                {
                    headers:{Accept:'application/json'}
                }
            );

            const payload=await response.json();
            recipientContext=payload.context || {};
            renderAddresses(payload.addresses || []);
            refreshPreview();
        }catch(error){
            addressList.innerHTML=
                '<div class="smart-empty">Adresses indisponibles.</div>';
            addressesBox.hidden=false;
        }
    }

    function renderAddresses(items){
        addressesBox.hidden=false;
        addressList.innerHTML='';
        selectedAddress=null;

        if(!items.length){
            addressList.innerHTML=
                '<div class="smart-empty">Aucune adresse disponible.</div>';
            previewTo.textContent=
                'Aucune adresse disponible';
            updateChecks();
            return;
        }

        items.forEach((item,index) => {
            const label=document.createElement('label');
            label.className='smart-address-item';

            const radio=document.createElement('input');
            radio.type='radio';
            radio.name='smart-address';
            radio.value=item.email;
            radio.checked=index===0;

            const content=document.createElement('span');
            const title=document.createElement('strong');
            title.textContent=item.libelle;
            const email=document.createElement('small');
            email.textContent=item.email;

            content.append(title,email);
            label.append(radio,content);
            addressList.appendChild(label);

            radio.addEventListener('change',() => {
                selectedAddress=item;
                previewTo.textContent=
                    `${selectedRecipient.name} <${item.email}>`;
                updateChecks();
            });

            if(index===0){
                selectedAddress=item;
                previewTo.textContent=
                    `${selectedRecipient.name} <${item.email}>`;
            }
        });

        updateChecks();
    }

    async function refreshPreview(){
        if(!template?.value){
            return;
        }

        const context={
            ...recipientContext,
            nom_membre:variables.nom_membre?.value || '',
            atelier:variables.atelier?.value || '',
            creneau:variables.creneau?.value || '',
            professeur:variables.professeur?.value || '',
            date_limite:variables.date_limite?.value || ''
        };

        const formData=new FormData();
        formData.append(
            'modele_id',
            template.value
        );
        formData.append(
            'context_json',
            JSON.stringify(context)
        );

        try{
            const response=await fetch(
                config.previewUrl,
                {
                    method:'POST',
                    body:formData,
                    headers:{
                        Accept:'application/json'
                    }
                }
            );

            const payload=await response.json();

            object.value=payload.object || '';
            body.value=payload.html || '';
            previewObject.textContent=
                payload.object || '—';
            preview.innerHTML=
                payload.html || '';

            renderUnresolved(
                payload.unresolved || []
            );
            updateChecks();
        }catch(error){
            preview.innerHTML=
                'Aperçu indisponible.';
        }
    }

    function updatePreviewFromEditor(){
        previewObject.textContent=
            object.value || '—';
        preview.innerHTML=
            body.value || '';
        updateChecks();
    }

    function renderUnresolved(items){
        unresolved.hidden=!items.length;

        unresolved.innerHTML=items.length
            ? '<strong>Variables non renseignées :</strong> '
                +items.map(
                    value => `{{${escapeHtml(value)}}}`
                ).join(', ')
            : '';
    }

    function updateChecks(){
        const addressCheck=document.getElementById(
            'check-address'
        );
        const objectCheck=document.getElementById(
            'check-object'
        );
        const variableCheck=document.getElementById(
            'check-variables'
        );

        if(addressCheck){
            addressCheck.textContent=selectedAddress
                ? '✓ Adresse sélectionnée'
                : '⚠ Adresse à sélectionner';
        }

        if(objectCheck){
            objectCheck.textContent=object.value.trim()
                ? '✓ Objet renseigné'
                : '⚠ Objet à préparer';
        }

        const hasUnresolved=
            /\{\{[^}]+\}\}/.test(
                body.value+object.value
            );

        if(variableCheck){
            variableCheck.textContent=hasUnresolved
                ? '⚠ Variables à compléter'
                : '✓ Variables remplacées';
        }
    }

    function escapeHtml(value){
        return String(value)
            .replaceAll('&','&amp;')
            .replaceAll('<','&lt;')
            .replaceAll('>','&gt;')
            .replaceAll('"','&quot;')
            .replaceAll("'",'&#039;');
    }
})();
