/* Exclusions scanner + situational-clause and scope-component checkbox
 * wiring for the quote builder (includes/estimates.php). Reads page
 * config attached via wp_add_inline_script: paintopsScopeTerms, an
 * array of {term, disclaimer} objects. */
(function() {
    var scopeTerms = window.paintopsScopeTerms || [];
    var scopeNotesField = document.getElementById('scopeNotes');
    var suggestBox = document.getElementById('scopeSuggestions');
    var quoteEditorEl = document.getElementById('quoteEditor');

    function renderSuggestions() {
        if (!suggestBox || !scopeNotesField || !quoteEditorEl) return;
        var text = quoteEditorEl.innerText.toLowerCase();
        var notes = scopeNotesField.value;
        var matches = scopeTerms.filter(function(t) {
            return t.term && text.indexOf(t.term.toLowerCase()) !== -1 && notes.indexOf(t.disclaimer) === -1;
        });

        if (!matches.length) {
            suggestBox.innerHTML = '';
            suggestBox.style.display = 'none';
            return;
        }

        suggestBox.style.display = 'block';
        var html = '<div style="background:var(--po-tile-bg,#fff8e5);color:var(--po-text,#111);border:1px solid var(--po-card-border,#f0d99b);border-radius:6px;padding:10px 14px;margin:6px 0;">';
        html += '<strong>Possible scope wording to clarify:</strong>';
        matches.forEach(function(t, i) {
            html += '<div style="margin-top:6px;"><em>&ldquo;' + t.term + '&rdquo;</em> - <button type="button" class="button button-small scope-add-btn" data-index="' + i + '">+ Add disclaimer</button></div>';
        });
        html += '</div>';
        suggestBox.innerHTML = html;

        suggestBox.querySelectorAll('.scope-add-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var match = matches[parseInt(btn.getAttribute('data-index'), 10)];
                if (!match) return;
                scopeNotesField.value = scopeNotesField.value.trim() === '' ? match.disclaimer : (scopeNotesField.value + "\n\n" + match.disclaimer);
                renderSuggestions();
            });
        });
    }

    if (quoteEditorEl) {
        quoteEditorEl.addEventListener('input', renderSuggestions);
        renderSuggestions();
    }

    document.querySelectorAll('.scope-situational-check').forEach(function(cb) {
        cb.addEventListener('change', function() {
            if (!scopeNotesField) return;
            var disclaimer = cb.getAttribute('data-disclaimer');
            if (!disclaimer) return;
            if (cb.checked) {
                if (scopeNotesField.value.indexOf(disclaimer) === -1) {
                    scopeNotesField.value = scopeNotesField.value.trim() === '' ? disclaimer : (scopeNotesField.value + "\n\n" + disclaimer);
                }
            } else {
                scopeNotesField.value = scopeNotesField.value.split(disclaimer).join('').replace(/\n{3,}/g, "\n\n").trim();
            }
            renderSuggestions();
        });
    });

    // Scope wording helper drawer, same checkbox interaction as the Situational
    // Clauses above, but it inserts into the Description of Work editor
    // (quoteEditorEl's HTML) instead of the Exclusions textarea, since
    // this checklist is about what IS included, not what isn't.
    document.querySelectorAll('.scope-component-check').forEach(function(cb) {
        cb.addEventListener('change', function() {
            if (!quoteEditorEl) return;
            var scopeText = cb.getAttribute('data-scope-text');
            if (!scopeText) return;
            // Compare/insert the HTML-ENCODED form (2026-07-22 audit): the
            // editor's innerHTML reads "&" back as "&amp;", so raw-text
            // matching failed to untick/remove any component containing
            // &, <, or > and duplicated it on re-tick.
            var scopeEncDiv = document.createElement('div');
            scopeEncDiv.textContent = scopeText;
            var scopeHtml = scopeEncDiv.innerHTML;
            if (cb.checked) {
                if (quoteEditorEl.innerHTML.indexOf(scopeHtml) === -1 && quoteEditorEl.innerHTML.indexOf(scopeText) === -1) {
                    quoteEditorEl.innerHTML = quoteEditorEl.innerHTML.trim() === '' ? scopeHtml : (quoteEditorEl.innerHTML + '<br><br>' + scopeHtml);
                }
            } else {
                quoteEditorEl.innerHTML = quoteEditorEl.innerHTML.split(scopeHtml).join('').split(scopeText).join('').replace(/(<br>\s*){3,}/g, '<br><br>').trim();
            }
            cb.closest('.paintops-situational-chip').classList.toggle('checked', cb.checked);
            renderSuggestions();
        });
    });
})();
