(function () {
'use strict';

var cfg = window.AdminSettings || {};
var csrfToken = cfg.csrfToken || '';
var messages  = cfg.messages  || {};

/* ── Test de configuration LDAP ──────────────────────────────────────────── */
window.ldapTestConfig = function () {
    var btn  = document.getElementById('ldap_test_btn');
    var out  = document.getElementById('ldap_test_result');
    var data = new FormData();
    data.append('csrf_token', csrfToken);
    data.append('host',       document.querySelector('input[name="ldap_host"]').value);
    data.append('port',       document.querySelector('input[name="ldap_port"]').value);
    data.append('base_dn',    document.querySelector('input[name="ldap_base_dn"]').value);
    data.append('bind_dn',    document.querySelector('input[name="ldap_bind_dn"]').value);
    data.append('bind_pass',       document.querySelector('input[name="ldap_bind_pass"]').value);
    data.append('user_dn_pattern', document.getElementById('ldap_user_dn_pattern').value);
    data.append('tls_insecure',    document.getElementById('ldap_tls_insecure').checked ? '1' : '');
    data.append('test_user',       document.getElementById('ldap_test_user').value);
    data.append('test_pass',       document.getElementById('ldap_test_pass').value);

    btn.disabled = true;
    out.innerHTML = '<div class="alert alert-info" style="margin:0">'
                  + (messages.ldapTestRunning || '')
                  + '</div>';

    fetch('/admin/test_ldap.php', { method: 'POST', body: data, credentials: 'same-origin' })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            btn.disabled = false;
            renderLdapTestResult(data, out);
        })
        .catch(function (e) {
            btn.disabled = false;
            out.innerHTML = '<div class="alert alert-error" style="margin:0">'
                          + 'Erreur réseau : ' + escapeHtml(String(e)) + '</div>';
        });
};

function renderLdapTestResult(data, container) {
    if (data.msg && !data.steps) {
        container.innerHTML = '<div class="alert alert-error" style="margin:0">'
                            + escapeHtml(data.msg) + '</div>';
        return;
    }
    var headerCls = data.ok ? 'alert-success' : 'alert-error';
    var headerLbl = data.ok
        ? (messages.ldapTestOk || '')
        : (messages.ldapTestKo || '');
    var html = '<div class="alert ' + headerCls + '" style="margin:0 0 .5rem 0;font-weight:600">'
             + (data.ok ? '✓ ' : '✕ ') + escapeHtml(headerLbl) + '</div>';

    html += '<ul style="list-style:none;padding:0;margin:0;font-size:.85rem">';
    (data.steps || []).forEach(function (s) {
        var icon  = s.ok ? '✓' : '✕';
        var color = s.ok ? '#27ae60' : '#c0392b';
        html += '<li style="padding:.2rem 0;border-bottom:1px solid var(--color-border-light,rgba(0,0,0,.05))">'
              + '<strong style="color:' + color + '">' + icon + ' [' + escapeHtml(s.name) + ']</strong> '
              + escapeHtml(s.msg);
        if (s.details) {
            html += '<br><code style="font-size:.78rem;color:var(--color-text-muted);white-space:pre-wrap;word-break:break-all">'
                  + escapeHtml(s.details) + '</code>';
        }
        html += '</li>';
    });
    html += '</ul>';
    container.innerHTML = html;
}

function escapeHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

/* ── Test SMTP ─────────────────────────────────────────────────────────── */
window.testSmtp = function () {
    var rcpt = document.getElementById('smtp_test_rcpt').value.trim();
    if (!rcpt) { alert(messages.smtpTestRcptRequired || ''); return; }

    var span = document.getElementById('smtp-test-result');
    span.textContent = '…';
    span.style.display = 'inline';
    span.style.color   = '';

    var fd = new FormData();
    fd.append('csrf_token', csrfToken);
    fd.append('action', 'test_smtp');
    fd.append('test_rcpt', rcpt);

    fetch('/admin/settings.php', { method: 'POST', body: fd })
        .then(function(r) { return r.json(); })
        .then(function(j) {
            span.style.color = j.ok ? '#27ae60' : '#c0392b';
            var txt = (j.ok ? '✓ ' : '✗ ') + j.msg;
            if (j.log && j.log.length) {
                txt += '\n' + j.log.join('\n');
            }
            span.style.whiteSpace = 'pre-wrap';
            span.style.display = 'block';
            span.style.marginTop = '.5rem';
            span.style.fontFamily = 'monospace';
            span.style.fontSize = '.78rem';
            span.textContent = txt;
        })
        .catch(function(e) {
            span.style.color = '#c0392b';
            span.textContent = '✗ ' + e;
        });
};

})();
