<div class="descrizione-fissa">
    <div class="testo-descrizione">
        {{{descrizione}}}
    </div>
</div>
<!-- Pulsante per aggiungere nuove T -->
<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">
        <table class="generaltable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>{{#str}}contodare, mtcontabilita{{/str}}</th>
                    <th>{{#str}}to, mtcontabilita{{/str}}</th>
                    <th>{{#str}}contoavere, mtcontabilita{{/str}}</th>
                    <th>{{#str}}saldo, mtcontabilita{{/str}} ({{#str}}d, mtcontabilita{{/str}})</th>
                    <th>{{#str}}saldo, mtcontabilita{{/str}} ({{#str}}a, mtcontabilita{{/str}})</th>
                    <th>&nbsp;</th>  <!-- Cestino -->
                </tr>
            </thead>
                <tbody>
                {{#mastrini}}

                {{#righe2}}
                <tr class="{{status}}" data-midx="{{idx}}">
                    <td>{{itemnum}}</td>
                    
                    <td>
                        <input type="text" class="autocomplete"
                            value="{{#mostra_dare}}{{testo}}{{/mostra_dare}}"
                            {{#disable_conto_d}}disabled{{/disable_conto_d}}>
                        {{#show_sugg_dare}}
                        {{#conto_corretto}}
                        <div class="feedback-corretta">Correct: {{conto_corretto}}</div>
                        {{/conto_corretto}}

                        {{#pos_conto_sbagliata}}
                        <div class="feedback-corretta">Correct: {{side_corretto}}</div>
                        {{/pos_conto_sbagliata}}
                        {{/show_sugg_dare}}

                    </td>
                    <td>&nbsp;</td>

                    <td>
                        <input type="text" class="autocomplete"
                            value="{{#mostra_avere}}{{testo}}{{/mostra_avere}}"
                            {{#disable_conto_a}}disabled{{/disable_conto_a}}>

                        {{#show_sugg_avere}}
                        {{#conto_corretto}}
                        <div class="feedback-corretta">Correct: {{conto_corretto}}</div>
                        {{/conto_corretto}}

                        {{#pos_conto_sbagliata}}
                        <div class="feedback-corretta">Correct: {{side_corretto}}</div>
                        {{/pos_conto_sbagliata}}
                        {{/show_sugg_avere}}
                            
                    </td>         
                    <td>
                        <input type="text" class="cifra" value="{{{d}}}" {{#disable_d}}disabled{{/disable_d}}>
                        {{#corretto_d}}
                        <div class="feedback-corretta">Correct: {{{corretto_d}}}</div>
                        {{/corretto_d}}
                    </td>
                    <td>
                        <input type="text" class="cifra" value="{{{a}}}" {{#disable_a}}disabled{{/disable_a}}>
                        {{#corretto_a}}
                        <div class="feedback-corretta">Correct: {{{corretto_a}}}</div>
                        {{/corretto_a}}
                    </td>
                    <!-- Cestino -->
                    <td class="mtc-remove-cell">
                        <button type="button" class="btn btn-link text-danger mtc-remove-row" title="Elimina riga">🗑</button>
                    </td>

                </tr>
                {{/righe2}}
                {{/mastrini}}
                </tbody>
        </table>
    </div>

<!-- <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}}


<!-- Hidden inputs: payload identico a Scrittura1 -->
<div style="display:none" id="mastrini-hidden">
{{#mastrini}}
  <div class="mastrino-hidden" data-midx="{{idx}}">
    <input type="hidden" name="mastrini[{{idx}}][listid]"   value="{{listid}}">
    <input type="hidden" name="mastrini[{{idx}}][parentid]" value="{{parentid}}">
    <input type="hidden" name="mastrini[{{idx}}][testo]"    value="{{testo}}">
    {{#righe}}
      <input type="hidden" name="mastrini[{{idx}}][righe][{{ridx}}][d]" value="{{d_post}}">
      <input type="hidden" name="mastrini[{{idx}}][righe][{{ridx}}][a]" value="{{a_post}}">
    {{/righe}}
  </div>
{{/mastrini}}
</div>


<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
});

/**
 * 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);

document.addEventListener('DOMContentLoaded', function () {
    // Tasto salva.
    const cmtsalva = document.getElementById('mtsalva');
    const cmtcheck = document.getElementById('mtcheck');
    const aggiungiMastrinoButton = document.getElementById('aggiungi-mastrino');
    const elencoSuggerimenti = {{{elencoSuggerimenti}}};

// ======= START: setup contatori/target =======
const mastriniInit = {{{mastriniJSON}}} || [];
let mastrinoCounter = Array.isArray(mastriniInit) ? mastriniInit.length : 0; // parte dopo gli esistenti
const tbody = document.querySelector('.generaltable tbody');

// ======= AUTOCOMPLETE (stile scrittura1, ma minimale) =======
function initAutocomplete(inputEl, hiddenListIdEl, hiddenTestoEl) {
    if (!inputEl) return;

    // evita di inizializzare due volte lo stesso campo
    if (inputEl.dataset.mtcAutoBound === '1') {
        return;
    }
    inputEl.dataset.mtcAutoBound = '1';

    // const suggBox = document.createElement('div');
    // suggBox.className = 'autocomplete-suggestions';
    // inputEl.parentNode.style.position = 'relative';
    // inputEl.parentNode.appendChild(suggBox);

    const suggBox = document.createElement('div');
    suggBox.className = 'autocomplete-suggestions';
    document.body.appendChild(suggBox);

    function placeSuggBox() {
        const r = inputEl.getBoundingClientRect();
        suggBox.style.left = r.left + 'px';
        suggBox.style.top  = (r.bottom + 2) + 'px';
        suggBox.style.width = r.width + 'px';
    }

    placeSuggBox();
    window.addEventListener('scroll', placeSuggBox, true);
    window.addEventListener('resize', placeSuggBox);
    inputEl.addEventListener('focus', placeSuggBox);


    inputEl.addEventListener('input', function () {
        const q = (inputEl.value || '').trim().toLowerCase();
        suggBox.innerHTML = '';
        
        if (!q) {
            suggBox.style.display = 'none';   // ✅ aggiungi anche questo
            return;
        }

        suggBox.style.display = 'block'; 

        const risultati = elencoSuggerimenti.filter(e =>
            (e.nome || '').toLowerCase().startsWith(q)
        );

        risultati.slice(0, 30).forEach(el => {
            const row = document.createElement('div');
            row.className = 'suggestion';
            row.textContent = el.nome;
            row.addEventListener('click', () => {
                inputEl.value = el.nome;
                if (hiddenListIdEl) hiddenListIdEl.value = el.id;
                if (hiddenTestoEl)  hiddenTestoEl.value  = el.nome;

                suggBox.innerHTML = '';
                suggBox.style.display = 'none';

                inputEl.classList.add('vocesel');
            });
            
            suggBox.appendChild(row);
        });
    });

    document.addEventListener('click', (ev) => {
        if (!suggBox.contains(ev.target) && ev.target !== inputEl) {
            suggBox.innerHTML = '';
            suggBox.style.display = 'none';
        }
    });
}

// Autocomplete anche per le righe già presenti a schermo
const form = document.getElementById('frminiziale');
if (form) {
    const rows = form.querySelectorAll('.generaltable tbody tr[data-midx]');
    rows.forEach(tr => {
        const midx = tr.dataset.midx;
        if (midx === undefined || midx === null || midx === '') return;

        const hiddenList = form.querySelector(`input[name="mastrini[${midx}][listid]"]`);
        const hiddenTest = form.querySelector(`input[name="mastrini[${midx}][testo]"]`);

        const autoInputs = tr.querySelectorAll('input.autocomplete');
        autoInputs.forEach(inp => {
            // ✅ bind solo se editabile
            if (inp && !inp.disabled) {
                initAutocomplete(inp, hiddenList, hiddenTest);
            }
        });
    });
}
// Fallback: se qualche campo .autocomplete è rimasto senza autocomplete,
// // lo inizializzo comunque (anche senza hiddenList/hiddenTesto).
// if (form) {
//     const allAuto = form.querySelectorAll('input.autocomplete');
//     allAuto.forEach(inp => {
//         if (inp.dataset.mtcAutoBound !== '1') {
//             initAutocomplete(inp, null, null);
//         }
//     });
// }


// ======= CREA RIGA (due mastrini: D e A) =======
function creaMastrino() {
  // un indice per il conto in DARE, uno per il conto in AVERE (così non collidono con gli esistenti)
  const iD = mastrinoCounter++;
  const iA = mastrinoCounter++;

  const tr = document.createElement('tr');
  tr.className = 'nuovariga';

    tr.innerHTML = `
    <td>+</td>

    <!-- DARE -->
    <td>
      <input type="text" class="autocomplete" placeholder="">
      <!-- hidden che verranno inviati -->
      <input type="hidden" name="mastrini[${iD}][testo]"    value="">
      <input type="hidden" name="mastrini[${iD}][listid]"   value="">
      <input type="hidden" name="mastrini[${iD}][parentid]" value="0">
    </td>

    <td>&nbsp;</td>

    <!-- AVERE -->
    <td>
      <input type="text" class="autocomplete" placeholder="">
      <!-- hidden che verranno inviati -->
      <input type="hidden" name="mastrini[${iA}][testo]"    value="">
      <input type="hidden" name="mastrini[${iA}][listid]"   value="">
      <input type="hidden" name="mastrini[${iA}][parentid]" value="0">
    </td>

    <!-- Importi -->
    <td><input type="text" class="cifra" name="mastrini[${iD}][righe][0][d]" value=""></td>
    <td><input type="text" class="cifra" name="mastrini[${iA}][righe][0][a]" value=""></td>

    <!-- Cestino -->
    <td class="mtc-remove-cell">
      <button type="button" class="btn btn-link text-danger mtc-remove-row" title="Elimina riga">🗑</button>
    </td>
  `;


  tbody.appendChild(tr);

  // bind formattazione numeri
//   tr.querySelectorAll('.cifra').forEach(inp => {
    // inp.addEventListener('input', formattaNumero);
//   });

if (window.mtcNumberFormatter) {
    mtcNumberFormatter.attach(tr);
}

  // init autocomplete per DARE
  const autoD   = tr.querySelectorAll('.autocomplete')[0];
  const hidDLid = tr.querySelector(`input[name="mastrini[${iD}][listid]"]`);
  const hidDTxt = tr.querySelector(`input[name="mastrini[${iD}][testo]"]`);
  initAutocomplete(autoD, hidDLid, hidDTxt);

  // init autocomplete per AVERE
  const autoA   = tr.querySelectorAll('.autocomplete')[1];
  const hidALid = tr.querySelector(`input[name="mastrini[${iA}][listid]"]`);
  const hidATxt = tr.querySelector(`input[name="mastrini[${iA}][testo]"]`);
  initAutocomplete(autoA, hidALid, hidATxt);


}

// ======= COLLEGA IL BOTTONE =======
document.getElementById('aggiungi-mastrino')?.addEventListener('click', (e) => {
  e.preventDefault(); // non inviare il form
  creaMastrino();
});


// ======= ELIMINAZIONE RIGHE (cestino) – versione "toglimi dal POST" =======
document.addEventListener('click', function (ev) {
    const btn = ev.target.closest('.mtc-remove-row');
    if (!btn) {
        return;
    }

    ev.preventDefault();

    const row  = btn.closest('tr');
    const form = document.getElementById('frminiziale');
    if (!row || !form) {
        return;
    }

    const midx = row.getAttribute('data-midx'); // "0", "1", ... oppure null
    console.log('🗑 Clic su cestino, midx =', midx);

    if (midx !== null && midx !== '') {
        // 1) Rimuovo TUTTI gli input relativi a quel mastrino
        //    (sia nel blocco nascosto, sia eventualmente in giro nel form)
        const selectorInputs = 'input[name^="mastrini[' + midx + ']"]';
        const inputs = form.querySelectorAll(selectorInputs);
        console.log('   input da rimuovere per midx', midx, ':', inputs);
        inputs.forEach(el => el.remove());

        // 2) Rimuovo il wrapper nascosto (se presente)
        const hiddenWrapper = form.querySelector(
            '#mastrini-hidden .mastrino-hidden[data-midx="' + midx + '"]'
        );
        console.log('   hiddenWrapper da rimuovere:', hiddenWrapper);
        if (hiddenWrapper) {
            hiddenWrapper.remove();
        }

        // 3) Rimuovo TUTTE le righe della tabella con quel data-midx
        const rowsToRemove = form.querySelectorAll(
            '.generaltable tbody tr[data-midx="' + midx + '"]'
        );
        console.log('   rowsToRemove:', rowsToRemove);
        rowsToRemove.forEach(tr => tr.remove());
    } else {
        // 🔹 Riga NUOVA (creata via JS, senza data-midx → iD/iA locali)
        //    Gli hidden stanno dentro la <tr>, quindi basta rimuoverla.
        console.log('   Riga nuova, rimuovo <tr> e relativi hidden interni');
        row.remove();
    }

    // DEBUG: cosa rimane ancora di "mastrini" nel form
    const rest = Array.from(
        form.querySelectorAll('input[name^="mastrini["]')
    ).map(el => el.name + ' = ' + el.value);
    console.log('📦 Dopo delete, input mastrini rimasti:', rest);
});



// Tasto Salva.
cmtsalva.addEventListener('click', (e) => {
    e.preventDefault();
    $('#itemdate').val($('#datemastrino').val());

    // prima sincronizzo quello che vedi a video nei campi hidden
    syncVisibleToHidden();

    $('#id_action').val('save');
    document.getElementById('frminiziale').submit();
});

// Tasto Check.
if (cmtcheck) {
    cmtcheck.addEventListener('click', (e) => {
        e.preventDefault();
        $('#itemdate').val($('#datemastrino').val());

        syncVisibleToHidden();

        $('#id_action').val('check');
        document.getElementById('frminiziale').submit();
    });
}

    if (window.mtcNumberFormatter) {
    mtcNumberFormatter.attach(document);
}
});


function syncVisibleToHidden() {
    const form = document.getElementById('frminiziale');
    if (!form) return;

    // 1) Raggruppo le righe della tabella per data-midx (solo mastrini ESISTENTI).
    const rows = form.querySelectorAll('.generaltable tbody tr[data-midx]');
    const groups = {}; // midx -> array di TR

    rows.forEach(row => {
        const midx = row.getAttribute('data-midx');
        if (!midx && midx !== '0') {
            return;
        }
        if (!groups[midx]) {
            groups[midx] = [];
        }
        groups[midx].push(row);
    });

    // 2) Per ogni mastrino esistente sincronizzo D/A visibile -> hidden relativi
    Object.keys(groups).forEach(midx => {
        const wrapper = form.querySelector(
            '#mastrini-hidden .mastrino-hidden[data-midx="' + midx + '"]'
        );
        if (!wrapper) {
            // Nessun hidden per questo mastrino → niente da sincronizzare
            return;
        }

        // Hidden D/A SOLO per questo mastrino
        const hiddenDs = Array.from(
            wrapper.querySelectorAll('input[name^="mastrini[' + midx + '][righe]"][name$="[d]"]')
        );
        const hiddenAs = Array.from(
            wrapper.querySelectorAll('input[name^="mastrini[' + midx + '][righe]"][name$="[a]"]')
        );

        let idxD = 0;
        let idxA = 0;

        groups[midx].forEach(row => {
            // colonna 5 = importo Dare, colonna 6 = importo Avere
            const inputD = row.querySelector('td:nth-child(5) input.cifra');
            const inputA = row.querySelector('td:nth-child(6) input.cifra');

            if (inputD) {
                // salto eventuali hidden "x" (righe readonly/situazione iniziale)
                while (idxD < hiddenDs.length && hiddenDs[idxD].value === 'x') {
                    idxD++;
                }
                if (idxD < hiddenDs.length) {
                    hiddenDs[idxD].value = inputD.value;
                    idxD++;
                }
            }

            if (inputA) {
                while (idxA < hiddenAs.length && hiddenAs[idxA].value === 'x') {
                    idxA++;
                }
                if (idxA < hiddenAs.length) {
                    hiddenAs[idxA].value = inputA.value;
                    idxA++;
                }
            }
        });
    });

    // Le righe NUOVE (create via JS) non hanno data-midx,
    // e i loro input hanno già name="mastrini[...][righe][...][d|a]",
    // quindi vanno in POST così come sono e NON richiedono sync.
}


</script>

<style>
    tr.mtc-deleted {
    display: none;
}
/* 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 */



.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;
    margin: 0 auto;       /* centra l’input nella cella */
    display: block;       /* per applicare correttamente margin:auto */
    /* 
        background-color: white;
        border: 1px solid #ccc;
        font-family: monospace; 
    */
    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 */
}

/* Centra i campi cifra dentro le celle della tabella */
.generaltable td {
    text-align: center;
    vertical-align: middle;
}

.generaltable td input.cifra {
    text-align: center;   /* centra il testo dentro l’input */
    margin: 0 auto;       /* centra l’input nella cella */
    display: block;       /* per applicare correttamente margin:auto */
}

/* Centra le intestazioni della tabella */
.generaltable thead th {
    text-align: center !important;
    vertical-align: middle !important;
}

/* (opzionale) evita che le etichette vadano a capo */
.generaltable thead th {
    white-space: nowrap;
}

/*  SUGGERIMENTI */
tr.ok {
    background-color: #d4edda !important;
}
tr.ko {
    background-color: #f8d7da !important;
}
.feedback-corretta {
    color: #dc3545;
    font-size: 0.75rem;
    margin-top: 2px;
}



/* Campi cifra dentro le celle della tabella */
.generaltable td input.cifra {
    text-align: right;   /* vedi punto 3 */
    margin: 0 auto;
    display: block;
    padding: 10px;       /* altezza "alta" */
    box-sizing: border-box;
    width: 100%;
}

/* Campi conto (autocomplete) dentro la tabella: stessa altezza degli importi */
.generaltable td input.autocomplete {
    padding: 10px;
    box-sizing: border-box;
    width: 100%;
    height: auto; /* lascia crescere col padding */
}

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


</style>