<div class="descrizione-fissa">
    <div class="testo-descrizione">
        {{{descrizione}}}
    </div>
</div>

<div class="d-flex align-items-center gap-2">
    <button id="aggiungi-mastrino" class="btn btn-primary">{{#str}}addmastrino, mtcontabilita{{/str}}</button>
    <input type="text" 
           class="form-control datapicker datapicker-small {{dateclass}}"
           name="data[]"
           id="datemastrino"
           placeholder="Date"
           autocomplete="off"
           value="{{{itemdate}}}" 
    />
</div>

<form method="post" name="frminiziale" id="frminiziale" action="saveattemptmastrino.php">
    <input type="hidden" name="cmid" id="id_cmid" value="{{{cmid}}}">
    <input type="hidden" name="attemptid" id="id_attemptid" value="{{{attemptid}}}">
    <input type="hidden" name="mtcontabilitaid" id="id_mtcontabilitaid" value="{{{mtcontabilitaid}}}">
    <input type="hidden" name="itemnum" id="id_itemnum" value="{{{itemnum}}}">
    <input type="hidden" name="num" id="id_num" value="{{{num}}}">
    <input type="hidden" name="action" id="id_action" value="{{{action}}}">
    <input type="hidden" name="itemdate" id="itemdate" value="{{{itemdate}}}">
    <input type="hidden" name="tp" id="tp" value="{{{tp}}}">

    <div class="scroll-container"><div id="mastrini-container"></div></div>

    {{#bcheck}}
    <div class="alert alert-{{{clesito}}} mt-2">
        <strong>{{#str}}esito, mtcontabilita{{/str}}:</strong> {{{esito}}} – <strong>{{#str}}score, mtcontabilita{{/str}}:</strong> {{{score}}}
    </div>
    {{/bcheck}}

    <div class="btn-group mt-3">
        <button type="submit" name="action1" value="save" class="btn btn-primary" id="mtsalva">{{#str}}save{{/str}}</button>
    {{#inline}}
        <button type="submit" name="action2" value="check" class="btn btn-success" id="mtcheck">{{#str}}check, mtcontabilita{{/str}}</button>
    {{#showsolution}}
        <button type="button" class="btn btn-success mtc-show-solution">{{#str}}showcorrectsolution, mtcontabilita{{/str}}</button>
    {{/showsolution}}
        
    {{/inline}}
    </div>

    {{#showsolution}}
    <div id="mtc-solution-modal" class="mtc-solution-modal" style="display:none;">
        <div class="mtc-modal-bg mtc-close-solution"></div>
        <div class="mtc-modal-content">
            <h3>{{#str}}correctsolution, mtcontabilita{{/str}}</h3>
            <div id="mtc-solution-body">
                {{{soluzionehtml}}}
            </div>
            <div style="margin-top: 15px; text-align: right;">
                <button type="button" class="btn btn-primary mtc-close-solution">
                    {{#str}}cancel{{/str}}
                </button>
            </div>
        </div>
    </div>
    {{/showsolution}}
</form>
<!-- Flatpickr CSS -->
<link rel="stylesheet" href="/mod/mtcontabilita/js/flatpickr.min.css">
<!-- Flatpickr JS -->
<script src="/mod/mtcontabilita/js/flatpickr.min.js"></script>
<script src="/mod/mtcontabilita/js/l10n/it.js"></script>
<script>

// POPUP INIZIO
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('mtc-show-solution')) {
        var modal = document.getElementById('mtc-solution-modal');
        if (modal) {
            modal.style.display = 'block';
        }
    }

    if (e.target.classList.contains('mtc-close-solution') ||
        e.target.classList.contains('mtc-modal-bg')) {
        var modal = document.getElementById('mtc-solution-modal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
});

const lang = (document.documentElement.getAttribute('lang') || 'en').toLowerCase();
const fpLocale = lang.startsWith('it') && window.flatpickr?.l10ns?.it ? flatpickr.l10ns.it : 'default';

flatpickr('.datapicker', {
  dateFormat: "d/m/Y",
  locale: fpLocale
});

// // POPUP FINE
// flatpickr('.datapicker', {
//     dateFormat: "d/m/Y", // Formato gg/mm/aaaa
//     locale: "it"
// });


/**
 * Formatter numerico centralizzato.
 * - supporta IT (1.234,56) e EN (1,234.56)
 * - on focus: toglie i separatori, tiene solo i decimali
 * - on blur: formatta con migliaia + 2 decimali
 */

(function (win) {
    const mtLang   = '{{lang}}' || 'it';
    const locale   = mtLang.toLowerCase().startsWith('en') ? 'en-US' : 'it-IT';

    // ✅ ndec dal server (obbligatorio)
    const ndecRaw = '{{ndec}}';
    const ndec = Number.isFinite(parseInt(ndecRaw, 10)) ? parseInt(ndecRaw, 10) : 2;

    function normalizza(str) {
        if (!str) return '';
        str = String(str).trim();

        if (locale === 'it-IT') {
            str = str.replace(/\./g, '');
            str = str.replace(',', '.');
            return str;
        } else {
            return str.replace(/,/g, '');
        }
    }

    function formatNumero(value) {
        if (value === '' || value === null || typeof value === 'undefined') return '';

        let num;
        if (typeof value === 'number') {
            num = value;
        } else {
            const norm = normalizza(value);
            num = parseFloat(norm);
        }
        if (isNaN(num)) return '';

        let res = num.toLocaleString(locale, {
            minimumFractionDigits: ndec,
            maximumFractionDigits: ndec
        });

        // Patch 1000 (solo se raggruppamento non viene applicato)
        if (ndec > 0) {
            if (locale === 'it-IT' && new RegExp('^\\d{4},\\d{' + ndec + '}$').test(res)) {
                res = res.replace(new RegExp('^(\\d)(\\d{3},\\d{' + ndec + '})$'), '$1.$2');
            } else if (locale === 'en-US' && new RegExp('^\\d{4}\\.\\d{' + ndec + '}$').test(res)) {
                res = res.replace(new RegExp('^(\\d)(\\d{3}\\.\\d{' + ndec + '})$'), '$1,$2');
            }
        } else {
            // ndec=0: patch "1000" -> "1.000" / "1,000"
            if (locale === 'it-IT' && /^\d{4}$/.test(res)) {
                res = res.replace(/^(\d)(\d{3})$/, '$1.$2');
            } else if (locale === 'en-US' && /^\d{4}$/.test(res)) {
                res = res.replace(/^(\d)(\d{3})$/, '$1,$2');
            }
        }

        return res;
    }

    function attachNumberBehaviour(container) {
        container.querySelectorAll('input.cifra').forEach(input => {
            if (input.dataset.mtcNumBound === '1') return;
            input.dataset.mtcNumBound = '1';

            // readonly: formatto e basta
            if (input.readOnly || input.disabled) {
                input.value = formatNumero(input.value);
                return;
            }

            input.addEventListener('focus', function () {
                if (!this.value) return;
                const norm = normalizza(this.value);
                if (!norm) { this.value = ''; return; }

                if (locale === 'it-IT') {
                    // 1234.56 -> 1234,56 (se ndec>0), oppure 1234 (se ndec=0)
                    if (ndec > 0 && norm.includes('.')) {
                        const parts = norm.split('.');
                        this.value = parts[0] + ',' + (parts[1] || '');
                    } else {
                        this.value = norm.split('.')[0];
                    }
                } else {
                    // en-US: 1234.56 / 1234
                    this.value = (ndec > 0) ? norm : norm.split('.')[0];
                }
            });

            input.addEventListener('blur', function () {
                this.value = formatNumero(this.value);
            });
        });
    }

    win.mtcNumberFormatter = {
        attach: attachNumberBehaviour,
        format: formatNumero,
        ndec: ndec
    };
})(window);








let mastrinoCounter = 0;

document.addEventListener('DOMContentLoaded', function () {
    // Tasto salva.
    const cmtsalva = document.getElementById('mtsalva');
    const cmtcheck = document.getElementById('mtcheck'); // sempre, se esiste

    const mastriniContainer = document.getElementById('mastrini-container');
    const aggiungiMastrinoButton = document.getElementById('aggiungi-mastrino');
    const elencoSuggerimenti = {{{elencoSuggerimenti}}};

    function abilitaInputAutomatico(mastrino) {
    const cifraInputs = mastrino.querySelectorAll('.cifra');
    cifraInputs.forEach(input => {
        input.addEventListener('input', function () {
            const rigaCorrente = this.closest('.mastrino-riga');
            const mastrino = rigaCorrente.closest('.mastrino');
            const mastrinoBody = mastrino.querySelector('.mastrino-body');
            const ultimaRiga = mastrinoBody.querySelector('.mastrino-riga:last-child');

            const dInput = ultimaRiga.querySelector('input[name*="[d]"]');
            const aInput = ultimaRiga.querySelector('input[name*="[a]"]');

            if (
                (dInput && dInput.value.trim() !== '') ||
                (aInput && aInput.value.trim() !== '')
            ) {
                const nextR = parseInt(mastrino.dataset.riga || '1');
                const extraRiga = document.createElement('div');
                extraRiga.classList.add('mastrino-riga', 'riga-aggiunta');
                extraRiga.innerHTML = `
                    <input type="text" class="cifra" name="mastrini[${mastrino.dataset.index}][righe][${nextR}][d]" placeholder="" />
                    <input type="text" class="cifra" name="mastrini[${mastrino.dataset.index}][righe][${nextR}][a]" placeholder="" />
                `;
                mastrinoBody.appendChild(extraRiga);
                mastrino.dataset.riga = nextR + 1;

                abilitaInputAutomatico(mastrino);
            }
        });
    });
}


    function creaMastrino(data = {}) {
        const i = mastrinoCounter++;
        const mastrinoDiv = document.createElement('div');
        mastrinoDiv.classList.add('mastrino');
        mastrinoDiv.dataset.index = i;   // 🔹 per costruire i nomi degli input
        mastrinoDiv.dataset.riga = 1;    // 🔹 inizia da r = 1

        const result = generaHTMLMastrino(i, { listid: '', testo: '', d: 0, a: 0 });
        mastrinoDiv.innerHTML = result.html;

        mastriniContainer.appendChild(mastrinoDiv);
        abilitaInputAutomatico(mastrinoDiv);

        initAutocomplete(mastrinoDiv.querySelector('.autocomplete'));

        mastrinoDiv.querySelector('.btn-remove').addEventListener('click', () => mastrinoDiv.remove());
    }

    function initAutocomplete(inputElement) {
        if (!inputElement) return;

        // Evita doppio bind sullo stesso input.
        if (inputElement.dataset.mtcAutoBound === '1') return;
        inputElement.dataset.mtcAutoBound = '1';

        // Crea dropdown "globale" per questo input (in body).
        const suggerimentiDiv = document.createElement('div');
        suggerimentiDiv.classList.add('autocomplete-suggestions');
        suggerimentiDiv.style.display = 'none';
        document.body.appendChild(suggerimentiDiv);

        function placeSuggBox() {
            // Se l'input non è più nel DOM (es. replaceWith), nascondi e stop.
            if (!document.body.contains(inputElement)) {
                hideSuggestions();
                return;
            }
            const r = inputElement.getBoundingClientRect();
            suggerimentiDiv.style.left = r.left + 'px';
            suggerimentiDiv.style.top = (r.bottom + 2) + 'px';
            suggerimentiDiv.style.width = r.width + 'px';
        }

        function showSuggestions() {
            placeSuggBox();
            suggerimentiDiv.style.display = 'block';
        }

        function hideSuggestions() {
            suggerimentiDiv.style.display = 'none';
            suggerimentiDiv.innerHTML = '';
        }

        // Reposition continuo (cattura true: anche scroll dei contenitori interni)
        const onScrollResize = () => {
            if (suggerimentiDiv.style.display !== 'none') {
                placeSuggBox();
            }
        };
        window.addEventListener('scroll', onScrollResize, true);
        window.addEventListener('resize', onScrollResize);

        inputElement.addEventListener('focus', () => {
            // non apro da solo, ma se era aperto lo riposiziono
            if (suggerimentiDiv.innerHTML.trim() !== '') {
                showSuggestions();
            }
        });

        inputElement.addEventListener('input', function () {
            const q = (inputElement.value || '').trim().toLocaleLowerCase('it');
            hideSuggestions();

            if (!q) return;

            const risultati = elencoSuggerimenti
                .filter(e => (e.nome || '').toLocaleLowerCase('it').startsWith(q))
                .slice(0, 40); // limite (performance)

            if (!risultati.length) return;

            risultati.forEach(elemento => {
                const suggerimento = document.createElement('div');
                suggerimento.classList.add('suggestion');
                suggerimento.textContent = elemento.nome;

                suggerimento.addEventListener('mousedown', function (ev) {
                    // mousedown invece di click: evita che blur chiuda prima della selezione
                    ev.preventDefault();

                    const mastrinoCorrente = inputElement.closest('.mastrino');
                    const listIdInput = mastrinoCorrente
                        ? mastrinoCorrente.querySelector('input[type="hidden"][name$="[listid]"]')
                        : null;

                    if (listIdInput) {
                        listIdInput.value = elemento.id;
                    }
                    inputElement.value = elemento.nome;
                    inputElement.dataset.id = elemento.id;

                    hideSuggestions();

                    const attemptid = document.getElementById('id_attemptid').value;
                    const mtcontabilitaid = document.getElementById('id_mtcontabilitaid').value;
                    const itemnum = document.getElementById('id_itemnum').value;
                    const sort = document.getElementById('id_num').value;

                    $.ajax({
                        url: 'get_mastrini.php',
                        method: 'POST',
                        data: { listid: elemento.id, attemptid, mtcontabilitaid, itemnum, sort },
                        success: function (response) {
                            try {
                                const i = mastrinoCounter++;
                                const nuovoMastrino = document.createElement('div');
                                nuovoMastrino.classList.add('mastrino');

                                const risultato = generaHTMLMastrino(i, {
                                    listid: elemento.id,
                                    testo: elemento.nome,
                                    parentid: response[0]?.aid || 0,
                                    righe: response.map(r => ({
                                        d: r.d === "x" ? "" : r.d,
                                        a: r.a === "x" ? "" : r.a,
                                        dx: r.d === "x" ? "x" : "",
                                        ax: r.a === "x" ? "x" : "",
                                        origine: r.aid == response[0]?.aid ? "(i)" : `(${r.itemnum})`,
                                        readonly: true
                                    }))
                                });

                                nuovoMastrino.innerHTML = risultato.html;
                                nuovoMastrino.dataset.index = i;
                                nuovoMastrino.dataset.riga = risultato.r;

                                const old = inputElement.closest('.mastrino');
                                if (old) old.replaceWith(nuovoMastrino);

                                // ✅ format numeri readonly + bind
                                if (window.mtcNumberFormatter) {
                                    mtcNumberFormatter.attach(nuovoMastrino);
                                }

                                abilitaInputAutomatico(nuovoMastrino);

                                // bind rimozione
                                const btnRemove = nuovoMastrino.querySelector('.btn-remove');
                                if (btnRemove) btnRemove.addEventListener('click', () => nuovoMastrino.remove());

                                // Riga vuota extra (come avevi tu)
                                const mastrinoBody = nuovoMastrino.querySelector('.mastrino-body');
                                const nextR = parseInt(nuovoMastrino.dataset.riga || '1', 10);
                                const nuovaRiga = document.createElement('div');
                                nuovaRiga.classList.add('mastrino-riga', 'riga-aggiunta');
                                nuovaRiga.innerHTML = `
                                    <input type="text" class="cifra" name="mastrini[${i}][righe][${nextR}][d]" placeholder="" />
                                    <input type="text" class="cifra" name="mastrini[${i}][righe][${nextR}][a]" placeholder="" />
                                `;
                                mastrinoBody.appendChild(nuovaRiga);
                                nuovoMastrino.dataset.riga = nextR + 1;

                                abilitaInputAutomatico(nuovoMastrino);
                            } catch (e) {
                                console.error("Errore nel parsing del JSON:", e);
                            }
                        }
                    });
                });

                suggerimentiDiv.appendChild(suggerimento);
            });

            showSuggestions();
        });

        // Chiudi su click esterno
        const onDocClick = (event) => {
            if (event.target === inputElement) return;
            if (suggerimentiDiv.contains(event.target)) return;
            hideSuggestions();
        };
        document.addEventListener('mousedown', onDocClick);

        // Chiudi su ESC
        inputElement.addEventListener('keydown', (ev) => {
            if (ev.key === 'Escape') {
                hideSuggestions();
                inputElement.blur();
            }
        });

        // Chiudi quando perdi il focus (piccolo delay per consentire mousedown su suggestion)
        inputElement.addEventListener('blur', () => {
            setTimeout(() => hideSuggestions(), 120);
        });
    }

    aggiungiMastrinoButton.addEventListener('click', () => creaMastrino());

    // Tasto Salva.
    cmtsalva.addEventListener('click', (e) => {
        e.preventDefault();
        $('#itemdate').val($('#datemastrino').val());
        const dati = $('#frminiziale').serializeArray();
        $('#id_action').val('save')
        document.getElementById('frminiziale').submit();
    });
    // Tasto Check (solo se il bottone esiste, cioè se inline=1).
    if (cmtcheck) {
        cmtcheck.addEventListener('click', (e) => {
            e.preventDefault();
            $('#itemdate').val($('#datemastrino').val());
            const dati = $('#frminiziale').serializeArray();
            $('#id_action').val('check');
            document.getElementById('frminiziale').submit();
        });
    }

    // Inizializza autocomplete su tutti i mastrini iniziali
    document.querySelectorAll('.mastrino .autocomplete').forEach(initAutocomplete);
    // Codice chiamato all'apertura della pagina.
    const mastriniPrecaricati = {{{mastriniJSON}}};

    mastriniPrecaricati.forEach((m) => {
        const i = mastrinoCounter++;
        const mastrinoDiv = document.createElement('div');

        const risultato = generaHTMLMastrino(i, m);
        let html = risultato.html;
       
        mastrinoDiv.classList.add('mastrino');
        mastrinoDiv.dataset.index = i;
        // mastrinoDiv.dataset.riga = (m.righe?.length || 1);
        mastrinoDiv.dataset.riga = risultato.r;
        mastrinoDiv.innerHTML = html;
        mastriniContainer.appendChild(mastrinoDiv);

if (window.mtcNumberFormatter) {
    mtcNumberFormatter.attach(mastrinoDiv);
}        
        // init eventi e autocomplete
        const auto = mastrinoDiv.querySelector('.autocomplete');
        if (auto) initAutocomplete(auto);
        const btnRemove = mastrinoDiv.querySelector('.btn-remove');
        if (btnRemove) btnRemove.addEventListener('click', () => mastrinoDiv.remove());
    });
});

function generaHTMLMastrino(i, data) {
    const d = parseFloat(data.d) || 0;
    const a = parseFloat(data.a) || 0;
    let r = 0;

    let html = `
        <input type="hidden" name="mastrini[${i}][listid]" value="${data.listid}" />
        <input type="hidden" name="mastrini[${i}][parentid]" value="${data.parentid || 0}" />
        <div class="mastrino-header">
            <input name="mastrini[${i}][testo]" type="text" class="autocomplete" value="${data.testo}" ${data.testo ? 'readonly' : ''} />
        </div>
        <div class="mastrino-body">`;

    if (Array.isArray(data.righe)) {
        data.righe.forEach(riga => {
            const dx = riga.dx === 'x';
            const ax = riga.ax === 'x';
            const dareReadonly = dx || (riga.readonly && parseFloat(riga.d) > 0);
            const avereReadonly = ax || (riga.readonly && parseFloat(riga.a) > 0);

            let dare = '', avere = '', flag = '';

            if (dareReadonly) {
                dare = `<input type="text" class="cifra cifra-origin" value="${riga.d}" readonly tabindex="-1" />
                        <input type="hidden" name="mastrini[${i}][righe][${r}][d]" value="x" />`;
                flag = `<div class="origin-flag sinistra">${riga.origine || ''}</div>`;
            } else {
                dare = `<input type="text" class="cifra" name="mastrini[${i}][righe][${r}][d]" value="${riga.d || ''}" />`;
            }

            if (avereReadonly) {
                avere = `<input type="text" class="cifra cifra-origin" value="${riga.a}" readonly tabindex="-1" />
                        <input type="hidden" name="mastrini[${i}][righe][${r}][a]" value="x" />`;
                flag = `<div class="origin-flag destra">${riga.origine || ''}</div>`;
            } else {
                avere = `<input type="text" class="cifra" name="mastrini[${i}][righe][${r}][a]" value="${riga.a || ''}" />`;
            }

            html += `<div class="mastrino-riga">${flag}${dare}${avere}</div>`;
            r++;
        });
    } else if (d > 0) {
        html += `
            <div class="mastrino-riga">
                <div class="origin-flag sinistra">(i)</div>
                <input type="text" class="cifra readonly" value="${d}" readonly tabindex="-1" />
                <input type="text" class="cifra" name="mastrini[${i}][righe][${r}][a]" />
                <input type="hidden" name="mastrini[${i}][righe][${r}][d]" value="x" />
            </div>`;
        r++;
    } else if (a > 0) {
        html += `
            <div class="mastrino-riga">
                <input type="text" class="cifra" name="mastrini[${i}][righe][${r}][d]" />
                <input type="text" class="cifra readonly" value="${a}" readonly tabindex="-1" />
                <div class="origin-flag destra">(i)</div>
                <input type="hidden" name="mastrini[${i}][righe][${r}][a]" value="x" />
            </div>`;
        r++;
    } else {
        html += `
            <div class="mastrino-riga">
                <input type="text" class="cifra" name="mastrini[${i}][righe][${r}][d]" />
                <input type="text" class="cifra" name="mastrini[${i}][righe][${r}][a]" />
            </div>`;
        r++;    
    }
    // Aggiungi sempre una riga finale vuota
    html += `
        <div class="mastrino-riga riga-aggiunta">
            <input type="text" class="cifra" name="mastrini[${i}][righe][${r}][d]" placeholder="" />
            <input type="text" class="cifra" name="mastrini[${i}][righe][${r}][a]" placeholder="" />
        </div>`;
    r++;

    html += `</div>
        <div><button type="button" class="btn btn-danger btn-remove">{{#str}}delmastrino, mtcontabilita{{/str}}</button></div>`;

    return { html, r };
}

</script>

<style>

/* POPUP INIZIO */
.mtc-solution-modal .mtc-modal-bg {
    position: fixed; top:0; left:0; right:0; bottom:0;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
}
.mtc-solution-modal .mtc-modal-content {
    position: fixed;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    max-width: 700px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    z-index: 1001;
}
/* POPUP FINE */


#mastrini-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    align-items: flex-start; /* 🔹 allinea in alto */
}

.cifra-origin {
    font-weight: bold;
    background-color: #e9ecef;
    border: 1px solid #999;
    color: #333;
}

.vocesel {
    color: #4f0303 !important; 
}

input.autocomplete {
    width: 100% !important;
    flex: 1 1 auto !important;
    display: block !important;
    text-align: center; /* 🔹 aggiungi questa riga */
}


.mastrino {
    margin-bottom: 20px;
}

.mastrino-header {
    display: flex;
    flex-direction: column;
    gap: 5px;
    position: relative;
    border-bottom: 2px solid black;
    padding-bottom: 5px;
    margin-bottom: 5px;
}


/* Corpo del mastrino: colonna di righe verticali */
.mastrino-body {
    display: flex;
    flex-direction: column;
    gap: 6px;
    position: relative;
    padding: 5px 0;
}

/* Righe dare/avere */
.mastrino-riga {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
    align-items: center;
    position: relative;
}

/* Linea verticale centrale (la "T") */
.mastrino-body::before {
    content: '';
    position: absolute;
    width: 2px;
    top: 0;
    bottom: 0;
    background-color: black;
    left: 50%;
    transform: translateX(-50%);
    z-index: 0;
}

/* Campi cifra in input e lettura */
.mastrino-body input.cifra,
.mastrino-body span.cifra.readonly {
    padding: 10px;
    text-align: center;
    box-sizing: border-box;
    font-size: 1em;
    width: 100%;
}

/* Versione readonly (non input) */
span.cifra.readonly {
    background-color: #f8f9fa;
}

/* Indicatori (i) sinistra o destra */
.origin-flag {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    font-size: 0.9em;
    color: gray;
    pointer-events: none;
    z-index: 1;
}

.origin-flag.sinistra {
    left: -20px;
}

.origin-flag.destra {
    right: -20px;
}

/* Bottone Elimina */
.btn-remove {
    width: 100%;
    margin-top: 10px;
}

/* Autocomplete dropdown */
.autocomplete {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    font-size: 1em;
}

.autocomplete-suggestions{
    border: 1px solid #ccc;
    max-height: 220px;
    overflow-y: auto;
    position: fixed;      /* ✅ fuori dai problemi di overflow */
    background: #fff;
    z-index: 99999;       /* ✅ sempre davanti */
    box-shadow: 0 6px 16px rgba(0,0,0,.15);
}

.suggestion {
    padding: 8px;
    cursor: pointer;
}
.suggestion:hover {
    background-color: #f0f0f0;
}

/* Contenitore a scorrimento */
.scroll-container {
    max-height: 400px;
    overflow-y: auto;
}

/* Conto statico */
.sautocomplete {
    width: 100%;
    text-align: center;
}

/*  Consente scroll indipendente del testo */
.testo-descrizione {
    max-height: 9em; /* 6 righe circa con line-height 1.5 */
    overflow-y: auto;
    line-height: 1.5;
    padding-right: 10px; /* per evitare che lo scroll copra il testo */
}

.scroll-container{
    max-height: calc(100vh - 340px); /* regola 340 in base a header/descrizione */
    overflow-y: auto;
}

</style>
