{{-- Shared AI lab-interpretation handler. Include INSIDE a <script> block after
     defining: LAB_URL, LAB_TOKEN, LAB_RESULTS (array), LAB_CONTEXT (string).
     Expects a #lab_ai_interpret button and a #lab_ai_panel container. --}}
function labInterpretColor(c) { return { low:'#16a34a', moderate:'#d97706', high:'#dc2626' }[c] || '#64748b'; }
function labRenderInterpret(res) {
    var c = labInterpretColor(res.concern);
    var esc = function (s) { return $('<div>').text(s == null ? '' : s).html(); };
    var h = '<div style="border:1px solid ' + c + ';border-left-width:4px;border-radius:8px;padding:10px 12px;background:#fff;">';
    h += '<div style="font-weight:700;color:' + c + ';"><i class="fa fa-brain"></i> Concern: ' + esc((res.concern || 'unknown').toUpperCase()) + '</div>';
    if (res.summary) h += '<div style="margin:4px 0 6px;">' + esc(res.summary) + '</div>';
    if (res.notes && res.notes.length) {
        h += '<ul style="margin:0;padding-left:18px;">';
        res.notes.forEach(function (n) { h += '<li><strong>' + esc(n.test) + ':</strong> ' + esc(n.note) + '</li>'; });
        h += '</ul>';
    }
    h += '<div class="text-muted" style="font-size:11px;margin-top:6px;">AI decision-support — confirm with a qualified professional.</div></div>';
    return h;
}
$('#lab_ai_interpret').on('click', function () {
    var $btn = $(this);
    if (!window.LAB_RESULTS || !LAB_RESULTS.length) { (window.toastr ? toastr.warning('No results to interpret.') : alert('No results to interpret.')); return; }
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Interpreting…');
    $('#lab_ai_panel').html('');
    $.post(LAB_URL, { _token: LAB_TOKEN, context: (window.LAB_CONTEXT || ''), results: LAB_RESULTS })
        .done(function (res) {
            if (!res.success) { (window.toastr ? toastr.error(res.msg || 'Failed') : alert(res.msg || 'Failed')); return; }
            $('#lab_ai_panel').html(labRenderInterpret(res));
        })
        .fail(function (xhr) {
            var m = (xhr.responseJSON && xhr.responseJSON.msg) || 'Interpretation failed';
            (window.toastr ? toastr.error(m) : alert(m));
        })
        .always(function () { $btn.prop('disabled', false).html('<i class="fa fa-brain"></i> AI interpret results'); });
});