/**
 * Admin Audits Page JS — NoonElite Audit Engine
 *
 * Handles: shortcode copy, toast, slug auto-generation, question/answer builder.
 * Localized data available via noonAuditAudits object.
 */
(function() {
    'use strict';

    // ── Toast Utility ────────────────────────────────────────────────────────
    function noonToast(msg) {
        var t = document.getElementById('noon-toast');
        if (!t) return;
        t.innerHTML = '<span class="dashicons dashicons-yes" style="color:#10b981;"></span>' + msg;
        t.classList.add('show');
        clearTimeout(t._tid);
        t._tid = setTimeout(function() { t.classList.remove('show'); }, 2000);
    }

    // ── Copy Utility ─────────────────────────────────────────────────────────
    function noonCopy(text) {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text);
        } else {
            var ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            document.execCommand('copy');
            document.body.removeChild(ta);
        }
        noonToast(noonAuditAudits.i18n.shortcodeCopied);
    }

    // ── HTML Escape ──────────────────────────────────────────────────────────
    function noonEscapeHtml(unsafe) {
        return String(unsafe)
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    // ── List View: Shortcode Copy Buttons ────────────────────────────────────
    document.querySelectorAll('.noon-copy-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            noonCopy(this.getAttribute('data-shortcode'));
        });
    });
    document.querySelectorAll('.noon-shortcode-copy').forEach(function(code) {
        code.addEventListener('click', function() {
            noonCopy(this.textContent);
        });
    });

    // ── Editor: Slug Auto-generation ─────────────────────────────────────────
    var titleField = document.getElementById('title');
    var slugField = document.getElementById('slug');
    if (titleField && slugField) {
        titleField.addEventListener('input', function() {
            if (!slugField.dataset.manual) {
                var slug = this.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
                slugField.value = slug;
                var preview = document.getElementById('slug-preview');
                if (preview) preview.textContent = slug;
            }
        });
        slugField.addEventListener('input', function() {
            this.dataset.manual = '1';
            var preview = document.getElementById('slug-preview');
            if (preview) preview.textContent = this.value;
        });
    }

    // ── Editor: Add Category ─────────────────────────────────────────────────
    window.noonAddCategory = function() {
        var list = document.getElementById('noon-categories-list');
        if (!list) return;
        var html = '<div class="noon-cat-row">' +
            '<input type="hidden" name="cat_id[]" value="">' +
            '<input type="color" name="cat_color[]" value="#6366f1" title="' + noonEscapeHtml(noonAuditAudits.i18n.colour) + '">' +
            '<input type="text" name="cat_name[]" value="" placeholder="' + noonEscapeHtml(noonAuditAudits.i18n.categoryName) + '">' +
            '<button type="button" class="noon-remove-btn" onclick="this.parentElement.remove()" title="' + noonEscapeHtml(noonAuditAudits.i18n.remove) + '">×</button>' +
            '</div>';
        list.insertAdjacentHTML('beforeend', html);
    };

    // ── Editor: Add Question ─────────────────────────────────────────────────
    window.noonQCount = noonAuditAudits.questionCount || 0;

    window.noonAddQuestion = function() {
        var qi = window.noonQCount++;
        var list = document.getElementById('noon-questions-list');
        if (!list) return;

        var catSelects = document.querySelectorAll('#noon-categories-list .noon-cat-row');
        var options = '';
        catSelects.forEach(function(row) {
            var name = row.querySelector('input[name="cat_name[]"]').value;
            var id = row.querySelector('input[name="cat_id[]"]').value || name.toLowerCase().replace(/[^a-z0-9]+/g, '-');
            if (name) options += '<option value="' + noonEscapeHtml(id) + '">' + noonEscapeHtml(name) + '</option>';
        });

        var html = '<div class="noon-question-block">' +
            '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">' +
            '<strong>' + noonEscapeHtml(noonAuditAudits.i18n.question) + ' ' + (qi + 1) + '</strong>' +
            '<button type="button" class="noon-remove-btn" onclick="this.closest(\'.noon-question-block\').remove();noonReindex()" title="' + noonEscapeHtml(noonAuditAudits.i18n.remove) + '">×</button>' +
            '</div>' +
            '<input type="hidden" name="q_id[]" value="q-' + noonEscapeHtml(String(qi + 1)) + '">' +
            '<p><label>' + noonEscapeHtml(noonAuditAudits.i18n.category) + '</label> <select name="q_cat[]" class="noon-q-cat-select">' + options + '</select></p>' +
            '<p><input type="text" name="q_text[]" value="" class="large-text" placeholder="' + noonEscapeHtml(noonAuditAudits.i18n.questionText) + '"></p>' +
            '<div class="noon-answers-list">' +
            noonAnswerRow(qi, 'A', '', 0) +
            noonAnswerRow(qi, 'B', '', 3) +
            noonAnswerRow(qi, 'C', '', 7) +
            noonAnswerRow(qi, 'D', '', 10) +
            '</div>' +
            '<button type="button" class="button button-small" onclick="noonAddAnswer(this)" style="margin-top:5px;">' + noonEscapeHtml(noonAuditAudits.i18n.addAnswer) + '</button>' +
            '</div>';
        list.insertAdjacentHTML('beforeend', html);
    };

    window.noonAnswerRow = function(qi, letter, text, pts) {
        return '<div class="noon-answer-row">' +
            '<span style="font-weight:600;min-width:20px;">' + noonEscapeHtml(letter) + '</span>' +
            '<input type="text" name="q_answers[' + qi + '][text][]" value="' + noonEscapeHtml(text) + '" placeholder="' + noonEscapeHtml(noonAuditAudits.i18n.answerText) + '">' +
            '<input type="number" name="q_answers[' + qi + '][points][]" value="' + pts + '" placeholder="' + noonEscapeHtml(noonAuditAudits.i18n.pts) + '" min="0" max="10">' +
            '<button type="button" class="noon-remove-btn" onclick="this.parentElement.remove()" title="' + noonEscapeHtml(noonAuditAudits.i18n.remove) + '">×</button>' +
            '</div>';
    };

    window.noonAddAnswer = function(btn) {
        var block = btn.closest('.noon-question-block');
        var list = block.querySelector('.noon-answers-list');
        var qi = Array.from(document.querySelectorAll('.noon-question-block')).indexOf(block);
        var count = list.querySelectorAll('.noon-answer-row').length;
        var letter = String.fromCharCode(65 + count);
        list.insertAdjacentHTML('beforeend', noonAnswerRow(qi, letter, '', 0));
    };

    window.noonReindex = function() {
        document.querySelectorAll('.noon-question-block').forEach(function(block, i) {
            block.querySelector('strong').textContent = noonAuditAudits.i18n.question + ' ' + (i + 1);
        });
    };
})();
