Basculer le menu
Changer de menu des préférences
Basculer le menu personnel
Non connecté(e)
Votre adresse IP sera visible au public si vous faites des modifications.

MediaWiki:Common.js

Page de l’interface de MediaWiki
Version datée du 20 octobre 2026 à 17:25 par Thomas234 (discussion | contributions) (Assistant Microguide : correctif du panneau qui restait ouvert)

Note : après avoir publié vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou appuyez sur Ctrl + F5 ou Ctrl + R (⌘ + R sur un Mac).
  • Google Chrome : appuyez sur Ctrl + Maj + R (⌘ + Shift + R sur un Mac).
  •  Edge : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl + F5.
// Forcer l'ouverture des sections hidden dans citizen qui les cachent par défaut

function ouvrirSections() {
    document.querySelectorAll('.citizen-section').forEach(function (el) {
        el.removeAttribute('hidden');
    });
}

document.addEventListener('DOMContentLoaded', ouvrirSections);

window.addEventListener('pageshow', function (e) {
    if (e.persisted) {
        ouvrirSections();
    }
});

/* Enlever le téléverser sur hamburger et empêcher les menus défilent */

function ouvrirSections() {
    document.querySelectorAll('.citizen-section').forEach(function (el) {
        el.removeAttribute('hidden');
    });
    var upload = document.getElementById('t-upload');
    if (upload) upload.remove();
}




/* Désactive les liens sur toutes les images */
$(document).ready(function() {
    $('.mw-file-description').each(function() {
        $(this).replaceWith($(this).children());
    });
});


// ============================================
// CALCULATEUR IRC — Microguide
// ============================================
if (mw.config.get('wgPageName') === 'Calculateur') {

    var style = document.createElement('style');
    style.textContent = `
        #calc-app * { box-sizing: border-box; font-family: 'Segoe UI', system-ui, sans-serif; }
        #calc-app { background: #f0f4f8; padding: 16px; border-radius: 12px; }
        .calc-header { background: linear-gradient(135deg, #1a5fa8 0%, #2980d4 100%); padding: 18px 22px; border-radius: 12px; color: white; margin-bottom: 16px; }
        .calc-header h1 { margin: 0; font-size: 20px; font-weight: 700; }
        .calc-header p { margin: 4px 0 0; font-size: 12px; opacity: 0.75; }
        .calc-card { background: white; border-radius: 12px; padding: 20px 22px; margin-bottom: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border: 1px solid #e2e8f0; }
        .calc-card h2 { margin: 0 0 14px; font-size: 15px; font-weight: 700; color: #0f2d5e; }
        .calc-grid { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 10px; margin-bottom: 12px; }
        .calc-grid label { font-size: 11px; color: #64748b; font-weight: 600; display: block; margin-bottom: 4px; }
        .calc-grid input { width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid #e2e8f0; font-size: 14px; color: #0f2d5e; font-weight: 600; outline: none; }
        .calc-sexe-btn { padding: 6px 18px; border-radius: 8px; border: 1.5px solid #e2e8f0; background: white; color: #64748b; font-weight: 600; cursor: pointer; font-size: 13px; margin-right: 8px; }
        .calc-sexe-btn.active { border-color: #0f2d5e; background: #0f2d5e; color: white; }
        .calc-result-box { background: #f8fafc; border-radius: 10px; padding: 14px 18px; display: flex; align-items: center; gap: 20px; flex-wrap: wrap; margin-top: 10px; }
        .calc-clcr-val { font-size: 32px; font-weight: 800; line-height: 1; }
        .calc-clcr-label { font-size: 12px; font-weight: 600; margin-top: 2px; }
        .calc-search { width: 100%; padding: 10px 14px; border-radius: 10px; border: 1.5px solid #e2e8f0; font-size: 14px; margin-bottom: 10px; outline: none; }
        .calc-cats { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
        .calc-cat-btn { padding: 6px 14px; border-radius: 20px; border: 1.5px solid #e2e8f0; background: white; color: #475569; font-weight: 600; cursor: pointer; font-size: 12px; }
        .calc-cat-btn.active { border-color: #0f2d5e; background: #0f2d5e; color: white; }
        .calc-drugs { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
        .calc-drug-btn { padding: 6px 12px; border-radius: 8px; border: 1.5px solid #e2e8f0; background: white; color: #475569; font-weight: 500; cursor: pointer; font-size: 12px; }
        .calc-drug-btn.active { border-color: #1a9d8f; background: #e8f6f4; color: #0f7a6e; font-weight: 700; }
        .calc-table { width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 10px; }
        .calc-table th { background: #f1f5f9; padding: 8px 12px; text-align: left; font-weight: 700; color: #0f2d5e; }
        .calc-table td { padding: 10px 12px; border-bottom: 1px solid #f1f5f9; }
        .calc-table tr.active-row { background: #e8f4f0 !important; outline: 2px solid #1a9d8f; }
        .calc-table tr.active-row td { color: #0a5a52; font-weight: 700; }
        .calc-badge { background: #1a9d8f; color: white; font-size: 10px; padding: 2px 6px; border-radius: 4px; margin-left: 8px; font-weight: 700; }
        .calc-note { background: #fefce8; border: 1px solid #fde68a; border-radius: 8px; padding: 10px 14px; font-size: 12px; color: #92400e; margin-bottom: 12px; }
        .calc-warning { background: #fef2f2; border: 1px solid #fecaca; border-radius: 10px; padding: 12px 16px; font-size: 11px; color: #991b1b; margin-top: 14px; }
        .calc-search-results button { display: block; width: 100%; text-align: left; padding: 8px 12px; margin-bottom: 4px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; font-size: 13px; color: #0f2d5e; }
        .calc-hint { margin-top: 12px; padding: 10px 14px; background: #f0f9ff; border-radius: 8px; font-size: 12px; color: #0369a1; }
        .calc-imc-info { border-left: 1px solid #e2e8f0; padding-left: 16px; font-size: 11px; color: #d97706; }
        @media (max-width: 600px) { .calc-grid { grid-template-columns: 1fr 1fr; } }
        .vanco-header { background: linear-gradient(135deg, #7c3aed 0%, #9f67f5 100%); padding: 18px 22px; border-radius: 12px; color: white; margin-bottom: 16px; }
        .vanco-header h1 { margin: 0; font-size: 20px; font-weight: 700; }
        .vanco-header p { margin: 4px 0 0; font-size: 12px; opacity: 0.75; }
        .vanco-card { background: white; border-radius: 12px; padding: 20px 22px; margin-bottom: 14px; box-shadow: 0 2px 8px rgba(124,58,237,0.08); border: 1px solid #ede9fe; }
        .vanco-card h2 { margin: 0 0 14px; font-size: 15px; font-weight: 700; color: #5b21b6; }
        .vanco-section-title { font-size: 13px; font-weight: 700; color: #5b21b6; margin: 14px 0 8px; padding-bottom: 4px; border-bottom: 2px solid #ede9fe; }
        .vanco-table { width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 8px; }
        .vanco-table th { background: #ede9fe; padding: 8px 12px; text-align: left; font-weight: 700; color: #5b21b6; }
        .vanco-table td { padding: 9px 12px; border-bottom: 1px solid #f5f3ff; }
        .vanco-table tr.vanco-active { background: #f3e8ff !important; }
        .vanco-table tr.vanco-active td { color: #6d28d9; font-weight: 700; }
        .vanco-badge { background: #7c3aed; color: white; font-size: 10px; padding: 2px 6px; border-radius: 4px; margin-left: 6px; font-weight: 700; }
        .vanco-input-row { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
        .vanco-input-group { flex: 1; min-width: 120px; }
        .vanco-input-group label { font-size: 11px; color: #7c3aed; font-weight: 600; display: block; margin-bottom: 4px; }
        .vanco-input-group input { width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid #ede9fe; font-size: 14px; color: #4c1d95; font-weight: 600; outline: none; }
        .vanco-result-box { background: #f3e8ff; border: 2px solid #c4b5fd; border-radius: 10px; padding: 14px 18px; margin-top: 12px; display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
        .vanco-result-val { font-size: 26px; font-weight: 800; color: #6d28d9; line-height: 1; }
        .vanco-warning { background: #fef2f2; border: 1px solid #fecaca; border-radius: 10px; padding: 12px 16px; font-size: 11px; color: #991b1b; margin-top: 14px; }
        .vanco-note { background: #fefce8; border: 1px solid #fde68a; border-radius: 8px; padding: 10px 14px; font-size: 12px; color: #92400e; margin-bottom: 12px; }
        .vanco-tab-btns { display: flex; gap: 8px; margin-bottom: 16px; }
        .vanco-tab-btn { padding: 7px 18px; border-radius: 8px; border: 1.5px solid #ede9fe; background: white; color: #7c3aed; font-weight: 600; cursor: pointer; font-size: 13px; }
        .vanco-tab-btn.active { background: #7c3aed; border-color: #7c3aed; color: white; }
        .vanco-prelevement { background: #f5f3ff; border-radius: 10px; padding: 14px 18px; margin-top: 12px; font-size: 13px; }
        @media (max-width: 600px) { .vanco-input-row { flex-direction: column; } }
    `;
    document.head.appendChild(style);

    var ANTIBIOS = {
        "Céphalosporines": {
            "Céfadroxil (PO)": { notes: "", doses: [
                { min: 30, max: 999, label: "500 mg PO q12h ou 1g PO q12-24h" },
                { min: 20, max: 29, label: "1g PO x1 dose puis 500 mg PO q12h" },
                { min: 10, max: 19, label: "1g PO x1 dose puis 500 mg PO q24h" },
                { min: 0, max: 9, label: "1g PO x1 dose puis 500 mg PO q24-36h" },
            ]},
            "Céfazoline (IV)": { notes: "", doses: [
                { min: 35, max: 999, label: "1-2g IV q8h (fréq. max. q6h)" },
                { min: 11, max: 34, label: "1-2g IV q12h" },
                { min: 0, max: 10, label: "1g IV q24h" },
            ]},
            "Céfépime (IV) — IIA/IU": { notes: "Infections intra-abdominales et urinaires", doses: [
                { min: 30, max: 999, label: "1-2g IV q12h" },
                { min: 11, max: 29, label: "1-2g IV q24h" },
                { min: 6, max: 10, label: "1g IV q24h" },
                { min: 0, max: 5, label: "500 mg IV q24h" },
            ]},
            "Céfépime (IV) — NF": { notes: "Neutropénie fébrile", doses: [
                { min: 30, max: 999, label: "2g IV q8h" },
                { min: 11, max: 29, label: "2g IV q12h" },
                { min: 6, max: 10, label: "2g IV q24h" },
                { min: 0, max: 5, label: "1g IV q24h" },
            ]},
            "Céfixime (PO)": { notes: "", doses: [
                { min: 21, max: 999, label: "400 mg PO q24h" },
                { min: 11, max: 20, label: "300 mg (¾ co.) PO q24h" },
                { min: 0, max: 10, label: "200 mg PO q24h" },
            ]},
            "Céfotaxime (IV)": { notes: "", doses: [
                { min: 21, max: 999, label: "1-2g IV q6-8h (jusqu'à 2g IV q4h si SNC)" },
                { min: 0, max: 20, label: "Diminuer la dose de 50%. Certains: 2g IV q12-24h" },
            ]},
            "Céfoxitine (IV)": { notes: "Dose max: 12g/jour", doses: [
                { min: 30, max: 999, label: "1-2g IV q6-8h" },
                { min: 11, max: 29, label: "1-2g IV q8-12h" },
                { min: 5, max: 10, label: "1-2g IV q12-24h" },
                { min: 1, max: 4, label: "50% de la dose IV q12-24h" },
                { min: 0, max: 0, label: "50% de la dose IV q24-48h" },
            ]},
            "Cefprozil (PO)": { notes: "", doses: [
                { min: 31, max: 999, label: "250-500 mg PO q12h" },
                { min: 0, max: 30, label: "250 mg PO q12h" },
            ]},
            "Ceftazidime (IV)": { notes: "", doses: [
                { min: 31, max: 999, label: "1-2g IV q8h" },
                { min: 16, max: 30, label: "1-2g IV q12h" },
                { min: 6, max: 15, label: "1-2g IV q24h" },
                { min: 1, max: 5, label: "500mg-1g IV q24h" },
                { min: 0, max: 0, label: "500mg-1g IV q48h" },
            ]},
            "Ceftobiprole (IV)": { notes: "Perfusion sur 4h si Clcr > 150 mL/min", doses: [
                { min: 31, max: 999, label: "500 mg IV q8h perf. sur 2h" },
                { min: 16, max: 30, label: "500 mg IV q12h perf. sur 2h" },
                { min: 6, max: 15, label: "250 mg IV q12h perf. sur 2h" },
                { min: 0, max: 5, label: "250 mg IV q24h perf. sur 2h" },
            ]},
            "Ceftriaxone (IV)": { notes: "Aucun ajustement requis sauf IR + IH (dose max: 2g/jour)", doses: [
                { min: 0, max: 999, label: "1-2g IV q24h (max: 2g IV q12h pour SNC)" },
            ]},
            "Céfuroxime axétil (PO)": { notes: "", doses: [
                { min: 11, max: 999, label: "250-500 mg PO q12h" },
                { min: 0, max: 10, label: "250 mg PO q24h" },
            ]},
            "Céfuroxime (IV)": { notes: "", doses: [
                { min: 21, max: 999, label: "750mg-1,5g IV q8h" },
                { min: 11, max: 20, label: "750 mg IV q12h" },
                { min: 0, max: 10, label: "750 mg IV q24h" },
            ]},
            "Céphalexine (PO)": { notes: "", doses: [
                { min: 41, max: 999, label: "250mg-1g PO q6h" },
                { min: 11, max: 40, label: "250-500 mg PO q8-12h" },
                { min: 0, max: 10, label: "250-500 mg PO q12-24h" },
            ]},
        },
        "Carbapénèmes": {
            "Ertapénem (IV)": { notes: "", doses: [
                { min: 31, max: 999, label: "1g IV q24h" },
                { min: 0, max: 30, label: "500 mg IV q24h" },
            ]},
            "Imipénem-Cilastatine (IV)": { notes: "PR ≥ 70 kg: 500 mg IV q6h (max 4g/jour). PR < 70 kg: voir monographie.", doses: [
                { min: 71, max: 999, label: "500 mg IV q6h (max: 4g/jour)" },
                { min: 41, max: 70, label: "500 mg IV q6-8h" },
                { min: 21, max: 40, label: "500 mg IV q8-12h" },
                { min: 6, max: 20, label: "250 mg IV q12h" },
                { min: 0, max: 5, label: "⚠️ Non recommandé" },
            ]},
            "Méropénem (IV) — usuel": { notes: "Posologie usuelle", doses: [
                { min: 26, max: 999, label: "1g IV q8h" },
                { min: 11, max: 25, label: "1g IV q12h" },
                { min: 6, max: 10, label: "500 mg IV q12h" },
                { min: 0, max: 5, label: "500 mg IV q24h" },
            ]},
            "Méropénem (IV) — SNC": { notes: "Infections du SNC", doses: [
                { min: 26, max: 999, label: "2g IV q8h" },
                { min: 11, max: 25, label: "2g IV q12h" },
                { min: 6, max: 10, label: "1g IV q12h" },
                { min: 0, max: 5, label: "1g IV q24h" },
            ]},
        },
        "Macrolides": {
            "Azithromycine (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "250-500 mg PO q24h" }]},
            "Azithromycine (IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "500 mg IV q24h" }]},
            "Clarithromycine (PO)": { notes: "", doses: [
                { min: 31, max: 999, label: "250-500 mg PO q12h" },
                { min: 0, max: 30, label: "250 mg PO q24h (ou q12h si infection sévère)" },
            ]},
            "Érythromycine (PO/IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "Posologie selon indication et formulation" }]},
        },
        "Pénicillines": {
            "Amoxicilline (PO)": { notes: "", doses: [
                { min: 31, max: 999, label: "250mg-1g PO q8h" },
                { min: 11, max: 30, label: "250-500 mg PO q12h" },
                { min: 0, max: 10, label: "250-500 mg PO q24h" },
            ]},
            "Amoxicilline-Clavulanate (PO)": { notes: "", doses: [
                { min: 31, max: 999, label: "500/125 mg PO q8h ou 875/125 mg PO q12h" },
                { min: 11, max: 30, label: "500/125 mg PO q12h" },
                { min: 0, max: 10, label: "500/125 mg PO q24h" },
            ]},
            "Ampicilline (IV)": { notes: "Posologie usuelle: 1-2g IV q4-6h", doses: [
                { min: 41, max: 999, label: "1-2g IV q6h" },
                { min: 31, max: 40, label: "1-2g IV q6-8h" },
                { min: 16, max: 30, label: "1-2g IV q8-12h" },
                { min: 0, max: 15, label: "1-2g IV q12-24h" },
            ]},
            "Cloxacilline (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "250-500 mg PO q6h (jusqu'à 4g/jour)" }]},
            "Cloxacilline (IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "1-2g IV q4-6h" }]},
            "Pénicilline G sodique (IV)": { notes: "DC = dose de charge", doses: [
                { min: 21, max: 999, label: "1-4 mU IV q4-6h" },
                { min: 11, max: 20, label: "DC suivie de 50% de la dose IV q4-6h" },
                { min: 0, max: 10, label: "DC suivie de 50% de la dose IV q8-12h" },
            ]},
            "Pipéracilline-Tazobactam (IV) — usuel": { notes: "Posologie usuelle", doses: [
                { min: 41, max: 999, label: "3,375g [3g/0,375g] IV q6h ou 4,5g [4g/0,5g] IV q8h" },
                { min: 21, max: 40, label: "2,25g [2g/0,25g] IV q6h" },
                { min: 0, max: 20, label: "2,25g [2g/0,25g] IV q8h" },
            ]},
            "Pipéracilline-Tazobactam (IV) — PAH/NF": { notes: "Pneumonie hospitalière ou neutropénie fébrile", doses: [
                { min: 41, max: 999, label: "4,5g [4g/0,5g] IV q6h" },
                { min: 21, max: 40, label: "3,375g [3g/0,375g] IV q6h" },
                { min: 0, max: 20, label: "2,25g [2g/0,25g] IV q6h" },
            ]},
        },
        "Fluoroquinolones": {
            "Ciprofloxacine (PO)": { notes: "", doses: [
                { min: 31, max: 999, label: "500-750 mg PO q12h" },
                { min: 16, max: 30, label: "500 mg PO q12h" },
                { min: 0, max: 15, label: "500 mg PO q24h ou 250 mg PO q12h" },
            ]},
            "Ciprofloxacine (IV)": { notes: "", doses: [
                { min: 31, max: 999, label: "400 mg IV q8-12h" },
                { min: 16, max: 30, label: "400 mg IV q12h" },
                { min: 0, max: 15, label: "400 mg IV q24h ou 200 mg IV q12h" },
            ]},
            "Lévofloxacine — légère/prostatite": { notes: "Ex: prostatite chronique", doses: [
                { min: 51, max: 999, label: "500 mg PO/IV q24h" },
                { min: 21, max: 50, label: "500 mg PO/IV x1 dose, puis 250 mg PO/IV q24h" },
                { min: 0, max: 20, label: "500 mg PO/IV x1 dose, puis 250 mg PO/IV q48h" },
            ]},
            "Lévofloxacine — PAH": { notes: "Pneumonie hospitalière", doses: [
                { min: 51, max: 999, label: "750 mg PO/IV q24h" },
                { min: 21, max: 50, label: "750 mg PO/IV q48h" },
                { min: 0, max: 20, label: "750 mg PO/IV x1 dose, puis 500 mg PO/IV q48h" },
            ]},
            "Moxifloxacine (PO/IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "400 mg PO/IV q24h" }]},
            "Norfloxacine (PO) — IU": { notes: "Infection urinaire", doses: [
                { min: 31, max: 999, label: "400 mg PO q12-24h" },
                { min: 0, max: 30, label: "400 mg PO q24h" },
            ]},
        },
        "Autres antibactériens": {
            "Clindamycine (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "150-450 mg PO q6h" }]},
            "Clindamycine (IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "600-900 mg IV q8h (fréq. max.: q6h)" }]},
            "Daptomycine (IV) — usuelle": { notes: "Pour dose 6 mg/kg: utiliser PD si PR > 140 kg", doses: [
                { min: 31, max: 999, label: "4-6 mg/kg PR IV q24h" },
                { min: 0, max: 30, label: "Même dose IV q48h" },
            ]},
            "Doxycycline (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "100 mg PO q12h" }]},
            "Linézolide (PO/IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "600 mg PO/IV q12h" }]},
            "Métronidazole (PO)": { notes: "", doses: [
                { min: 11, max: 999, label: "250-500 mg PO q8h ou 500 mg PO q12h" },
                { min: 0, max: 10, label: "500 mg PO q12h" },
            ]},
            "Métronidazole (IV)": { notes: "", doses: [
                { min: 11, max: 999, label: "500 mg IV q8h (fréq. max.: q6h)" },
                { min: 0, max: 10, label: "500 mg IV q12h" },
            ]},
            "Nitrofurantoïne (PO)": { notes: "Cystite non compliquée uniquement", doses: [
                { min: 46, max: 999, label: "50-100 mg PO QID ou 100 mg PO q12h (monohydrate)" },
                { min: 31, max: 45, label: "Données limitées. Possiblement efficace à court terme." },
                { min: 0, max: 30, label: "⚠️ Contre-indiqué — risque de toxicité accru" },
            ]},
            "Tétracycline (PO)": { notes: "", doses: [
                { min: 51, max: 999, label: "250-500 mg PO q6h" },
                { min: 11, max: 50, label: "250-500 mg PO q12h" },
                { min: 0, max: 10, label: "250-500 mg PO q24h" },
            ]},
            "Tigécycline (IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "100 mg IV x1 dose puis 50 mg IV q12h" }]},
            "Triméthoprime (PO)": { notes: "", doses: [
                { min: 16, max: 999, label: "100 mg PO q12h" },
                { min: 6, max: 15, label: "50 mg PO q12h" },
                { min: 0, max: 5, label: "⚠️ Non recommandé" },
            ]},
            "TMP-SMX — usuel": { notes: "80 mg TMP = 1 co SS; 160 mg TMP = 1 co DS", doses: [
                { min: 31, max: 999, label: "160-320 mg TMP PO/IV q12h" },
                { min: 16, max: 30, label: "80 mg TMP PO/IV q12h ou 160 mg TMP PO/IV q24h" },
                { min: 0, max: 15, label: "⚠️ Non recommandé" },
            ]},
            "Vancomycine (IV)": { notes: "⚠️ Amorcer empiriquement selon âge, fonction rénale et poids puis ajuster selon dosages sériques. DC = 25 mg/kg PR. DM: 15-20 mg/kg PD/dose q8-12h (max 2g/dose). Consulter pharmacien.", doses: [
                { min: 71, max: 999, label: "DM IV q12h — surveiller dosages sériques" },
                { min: 41, max: 70, label: "DM IV q24h — surveiller dosages sériques" },
                { min: 21, max: 40, label: "DM IV q36-48h — dosages sériques quotidiens" },
                { min: 11, max: 20, label: "DM IV q72-96h" },
                { min: 0, max: 10, label: "DM IV q5-7 jours — consulter pharmacien" },
            ]},
            "Vancomycine (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "125 mg PO QID (max 500 mg PO QID si infection compliquée)" }]},
        },
        "Antifongiques": {
            "Anidulafungine (IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "200 mg IV x1 dose puis 100 mg IV q24h" }]},
            "Caspofungine (IV)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "70 mg IV x1 dose puis 50 mg IV q24h" }]},
            "Fluconazole (PO/IV)": { notes: "DC = 100% de la dose. Écart: 100-800 mg PO/IV q24h", doses: [
                { min: 51, max: 999, label: "DC puis 100% dose PO/IV q24h" },
                { min: 11, max: 50, label: "DC puis 50% de la dose PO/IV q24h" },
                { min: 0, max: 10, label: "DC puis 25-50% de la dose PO/IV q24h" },
            ]},
            "Isavuconazole (PO/IV)": { notes: "Aucun ajustement requis. 372 mg sulfate = 200 mg isavuconazole.", doses: [{ min: 0, max: 999, label: "DC: 200 mg PO/IV q8h x6 doses, puis 200 mg PO/IV q24h" }]},
            "Kétoconazole (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "200-400 mg PO q24h" }]},
            "Micafungine — prophylaxie": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "50-100 mg IV q24h" }]},
            "Micafungine — traitement": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "100-150 mg IV q24h" }]},
            "Terbinafine (PO)": { notes: "", doses: [
                { min: 51, max: 999, label: "250 mg PO q24h" },
                { min: 0, max: 50, label: "⚠️ Non recommandé — données limitées" },
            ]},
        },
        "Antimycobactériens": {
            "Ethambutol (PO)": { notes: "Si PR > 120% PI, baser dose sur PI.", doses: [
                { min: 31, max: 999, label: "15-25 mg/kg PO q24h" },
                { min: 0, max: 30, label: "15-25 mg/kg/dose PO DIE 3 jours/semaine" },
            ]},
            "Isoniazide (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "5 mg/kg PO q24h (max: 300 mg)" }]},
            "Pyrazinamide (PO)": { notes: "Si PR > 120% PI, baser dose sur PI.", doses: [
                { min: 31, max: 999, label: "20-25 mg/kg PO q24h (max: 2g)" },
                { min: 0, max: 30, label: "25-35 mg/kg/dose PO DIE 3 jours/semaine" },
            ]},
            "Rifabutine (PO)": { notes: "", doses: [
                { min: 16, max: 999, label: "300 mg PO q24h" },
                { min: 0, max: 15, label: "150 mg PO q24h" },
            ]},
            "Rifampicine (PO)": { notes: "Aucun ajustement requis", doses: [{ min: 0, max: 999, label: "10 mg/kg PO q24h (max: 600 mg)" }]},
        },
        "Antiviraux": {
            "Acyclovir (IV)": { notes: "Posologie usuelle: 5-15 mg/kg/dose IV q8h", doses: [
                { min: 26, max: 999, label: "100% de la dose IV q8h" },
                { min: 11, max: 25, label: "100% de la dose IV q12h" },
                { min: 6, max: 10, label: "100% de la dose IV q24h" },
                { min: 0, max: 5, label: "50% de la dose IV q24h" },
            ]},
            "Acyclovir (PO) — zona": { notes: "", doses: [
                { min: 26, max: 999, label: "800 mg PO q4h (5 fois/jour)" },
                { min: 11, max: 25, label: "800 mg PO q8h" },
                { min: 0, max: 10, label: "800 mg PO q12h" },
            ]},
            "Famciclovir (PO) — zona": { notes: "", doses: [
                { min: 41, max: 999, label: "500 mg PO q8h" },
                { min: 21, max: 40, label: "500 mg PO q12h" },
                { min: 6, max: 20, label: "500 mg PO q24h" },
                { min: 0, max: 5, label: "250 mg PO q24h" },
            ]},
            "Oseltamivir (PO) — traitement": { notes: "Influenza A et B", doses: [
                { min: 31, max: 999, label: "75 mg PO q12h" },
                { min: 11, max: 30, label: "30 mg PO q12h" },
                { min: 6, max: 10, label: "30 mg PO q24h" },
                { min: 0, max: 5, label: "75 mg PO x1 dose" },
            ]},
            "Oseltamivir (PO) — prophylaxie": { notes: "Prophylaxie Influenza A et B", doses: [
                { min: 31, max: 999, label: "75 mg PO q24h" },
                { min: 11, max: 30, label: "30 mg PO q24h" },
                { min: 6, max: 10, label: "30 mg PO q48h" },
                { min: 0, max: 5, label: "Privilégier zanamivir inhalation" },
            ]},
            "Valacyclovir (PO) — zona": { notes: "", doses: [
                { min: 31, max: 999, label: "1g PO q8h" },
                { min: 16, max: 30, label: "1g PO q12h" },
                { min: 6, max: 15, label: "1g PO q24h" },
                { min: 0, max: 5, label: "500 mg PO q24h" },
            ]},
            "Valacyclovir (PO) — herpès génital": { notes: "", doses: [
                { min: 31, max: 999, label: "1g PO q12h" },
                { min: 16, max: 30, label: "1g PO q24h" },
                { min: 0, max: 15, label: "500 mg PO q24h" },
            ]},
        },
    };

    function calcClcr(age, poids, creat, sexe) {
        var k = sexe === 'F' ? 0.85 : 1.0;
        return ((140 - age) * poids / (49 * creat)) * 60 * k;
    }
    function calcPI(taille, sexe) {
        return sexe === 'F' ? 45.5 + 0.91 * (taille - 152) : 50 + 0.91 * (taille - 152);
    }
    function calcIMC(poids, taille) {
        return poids / Math.pow(taille / 100, 2);
    }

    var state = {
        age: '', poids: '', taille: '', creat: '', sexe: 'H',
        selectedCat: '', selectedDrug: '', search: '',
        mode: 'cg', dfgDirect: ''
    };

    function getDrugData(cat, drug) {
        return ANTIBIOS[cat] && ANTIBIOS[cat][drug] ? ANTIBIOS[cat][drug] : null;
    }

    function getActiveDose(doses, clcr) {
        var clcrRounded = Math.round(clcr * 10) / 10;
        for (var i = 0; i < doses.length; i++) {
            if (clcrRounded >= doses[i].min && clcrRounded <= doses[i].max) return i;
        }
        for (var i = doses.length - 1; i >= 0; i--) {
            if (clcrRounded >= doses[i].min) return i;
        }
        return doses.length - 1;
    }

    function calcClcrFromState() {
        if (state.mode === 'direct') {
            var dfg = parseFloat(state.dfgDirect);
            return { clcr: isNaN(dfg) ? null : dfg, imc: null, pi: null, poidsCalc: null };
        }
        var age = parseFloat(state.age);
        var poids = parseFloat(state.poids);
        var taille = parseFloat(state.taille);
        var creat = parseFloat(state.creat);
        var imc = (!isNaN(poids) && !isNaN(taille)) ? calcIMC(poids, taille) : null;
        var pi = (!isNaN(taille)) ? calcPI(taille, state.sexe) : null;
        var poidsCalc = null;
        if (!isNaN(poids) && !isNaN(taille)) {
            poidsCalc = imc < 30 ? poids : pi + 0.4 * (poids - pi);
        }
        var clcr = (!isNaN(age) && poidsCalc !== null && !isNaN(creat)) ? calcClcr(age, poidsCalc, creat, state.sexe) : null;
        return { clcr: clcr, imc: imc, pi: pi, poidsCalc: poidsCalc };
    }

    function renderResult() {
        var res = calcClcrFromState();
        var clcr = res.clcr; var imc = res.imc; var pi = res.pi; var poidsCalc = res.poidsCalc;
        var clcrColor = '#64748b'; var clcrLabel = '';
        if (clcr !== null) {
            if (clcr >= 60) { clcrColor = '#16a34a'; clcrLabel = 'Normale / légèrement réduite'; }
            else if (clcr >= 30) { clcrColor = '#d97706'; clcrLabel = 'IRC modérée'; }
            else if (clcr >= 15) { clcrColor = '#ea580c'; clcrLabel = 'IRC sévère'; }
            else { clcrColor = '#dc2626'; clcrLabel = 'IRC très sévère / terminale'; }
        }
        var box = document.getElementById('calc-result-box');
        if (box) {
            if (clcr !== null) {
                var html = '<div>';
                html += '<div style="font-size:11px;color:#64748b;font-weight:600">' + (state.mode === 'direct' ? 'DFG (LABORATOIRE)' : 'CLAIRANCE CRÉATININE') + '</div>';
                html += '<div class="calc-clcr-val" style="color:' + clcrColor + '">' + clcr.toFixed(1) + ' <span style="font-size:14px;font-weight:500">mL/min</span></div>';
                html += '<div class="calc-clcr-label" style="color:' + clcrColor + '">' + clcrLabel + '</div>';
                html += '</div>';
                if (imc !== null) {
                    html += '<div class="calc-imc-info">';
                    html += '<div style="font-size:11px;color:#64748b;font-weight:600">IMC</div>';
                    html += '<div style="font-size:20px;font-weight:700;color:#0f2d5e">' + imc.toFixed(1) + ' <span style="font-size:11px">kg/m\u00b2</span></div>';
                    if (imc >= 30 && pi) {
                        html += '<div>IMC \u2265 30 \u2014 Poids de dosage : <b>' + poidsCalc.toFixed(1) + ' kg</b><br>Poids id\u00e9al : ' + pi.toFixed(1) + ' kg</div>';
                    }
                    html += '</div>';
                }
                box.innerHTML = html;
                box.style.display = 'flex';
                box.style.border = '2px solid ' + clcrColor + '33';
            } else {
                box.innerHTML = '';
                box.style.display = 'none';
            }
        }
        var btnH = document.getElementById('calc-btn-h');
        var btnF = document.getElementById('calc-btn-f');
        if (btnH) btnH.className = 'calc-sexe-btn' + (state.sexe === 'H' ? ' active' : '');
        if (btnF) btnF.className = 'calc-sexe-btn' + (state.sexe === 'F' ? ' active' : '');
        renderDrugResult(clcr);
    }

    function renderDrugResult(clcr) {
        var drugData = getDrugData(state.selectedCat, state.selectedDrug);
        var section = document.getElementById('calc-drug-result');
        if (!section) return;
        if (!state.selectedDrug || !drugData) { section.innerHTML = ''; return; }
        var html = '<div class="calc-card">';
        html += '<h2>3. Posologie recommand\u00e9e</h2>';
        html += '<div style="font-size:13px;color:#64748b;margin-bottom:14px">' + state.selectedDrug + '</div>';
        if (drugData.notes) html += '<div class="calc-note">\u26a0\ufe0f ' + drugData.notes + '</div>';
        html += '<table class="calc-table"><thead><tr><th>ClCr (mL/min)</th><th>Posologie</th></tr></thead><tbody>';
        var activeIdx = clcr !== null ? getActiveDose(drugData.doses, clcr) : -1;
        drugData.doses.forEach(function(d, i) {
            var isActive = clcr !== null && i === activeIdx;
            var rangeLabel = d.max >= 999 ? '\u2265 ' + d.min : d.min === 0 ? '< ' + (drugData.doses.filter(function(x){return x.min>0;}).map(function(x){return x.min;}).sort(function(a,b){return a-b;})[0]||5) : d.min + ' \u2013 ' + d.max;
            html += '<tr' + (isActive ? ' class="active-row"' : ' style="background:' + (i%2===0?'white':'#f8fafc') + '"') + '>';
            html += '<td style="font-weight:600;white-space:nowrap">' + (isActive ? '\u25b6 ' : '') + rangeLabel + '</td>';
            html += '<td>' + d.label + (isActive ? '<span class="calc-badge">VOTRE PATIENT</span>' : '') + '</td>';
            html += '</tr>';
        });
        html += '</tbody></table>';
        if (clcr === null) html += '<div class="calc-hint">\ud83d\udca1 Entrez les donn\u00e9es du patient (\u00e9tape 1) pour mettre en \u00e9vidence la posologie appropri\u00e9e.</div>';
        html += '</div>';
        section.innerHTML = html;
    }

    function renderDrugSelector() {
        var searchResults = [];
        if (state.search && state.search.length >= 2) {
            var q = state.search.toLowerCase();
            Object.keys(ANTIBIOS).forEach(function(cat) {
                Object.keys(ANTIBIOS[cat]).forEach(function(drug) {
                    if (drug.toLowerCase().indexOf(q) !== -1) searchResults.push({ cat: cat, drug: drug });
                });
            });
        }
        var sr = document.getElementById('calc-search-results');
        if (sr) {
            var html = '';
            searchResults.forEach(function(r) {
                html += '<button onclick="calcSelectDrug(\'' + r.cat.replace(/'/g, "\\'") + '\',\'' + r.drug.replace(/'/g, "\\'") + '\')">';
                html += '<span style="color:#64748b;font-size:11px">' + r.cat + ' / </span>' + r.drug + '</button>';
            });
            sr.innerHTML = html;
        }
        var cats = document.getElementById('calc-cats');
        if (cats) {
            var html = '';
            Object.keys(ANTIBIOS).forEach(function(cat) {
                html += '<button class="calc-cat-btn ' + (state.selectedCat === cat ? 'active' : '') + '" onclick="calcSetCat(\'' + cat.replace(/'/g, "\\'") + '\')">' + cat + '</button>';
            });
            cats.innerHTML = html;
        }
        var drugs = document.getElementById('calc-drugs');
        if (drugs) {
            var html = '';
            if (state.selectedCat && ANTIBIOS[state.selectedCat]) {
                Object.keys(ANTIBIOS[state.selectedCat]).forEach(function(drug) {
                    html += '<button class="calc-drug-btn ' + (state.selectedDrug === drug ? 'active' : '') + '" onclick="calcSetDrug(\'' + drug.replace(/'/g, "\\'") + '\')">' + drug + '</button>';
                });
            }
            drugs.innerHTML = html;
        }
    }

    function renderVanco() {
        var app = document.getElementById('vanco-app');
        if (!app) return;
        var html = '';

        // Header violet
        html += '<div class="vanco-header">';
        html += '<h1>Vancomycine IV \u2014 Tableaux posologiques</h1>';
        html += '<p>Bas\u00e9 sur les lignes directrices APES \u2022 Adultes seulement</p>';
        html += '</div>';

        // Explication
        html += '<div class="vanco-card">';
        html += '<h2>\ud83d\udcd6 Comment utiliser ces tableaux</h2>';
        html += '<ol style="font-size:13px;color:#374151;line-height:1.8;margin:0;padding-left:20px;">';
        html += '<li><b>Dose de charge (optionnelle) :</b> Trouver le poids du patient dans le tableau 1 \u2192 administrer la dose correspondante en IV \u00d7 1 seule fois. Recommand\u00e9e chez les patients gravement malades.</li>';
        html += '<li><b>Dose d\u2019entretien :</b> Trouver le poids dans le tableau 2 \u2192 c\u2019est la dose par administration.</li>';
        html += '<li><b>Fr\u00e9quence :</b> Utiliser le DFGe fourni par le laboratoire (mL/min/1,73m\u00b2) dans le tableau 2 \u2192 d\u00e9termine l\u2019intervalle entre les doses (q8h, q12h, q24h).</li>';
        html += '<li><b>Pr\u00e9l\u00e8vements :</b> Consulter le tableau 3 selon la fr\u00e9quence choisie pour planifier le moment des pr\u00e9l\u00e8vements PIC et creux.</li>';
        html += '<li><b>Ajustement :</b> Toujours ajuster selon les dosages s\u00e9riques obtenus. Consulter un pharmacien pour les cas complexes (IMC \u2265 30, insuffisance r\u00e9nale s\u00e9v\u00e8re, soins intensifs).</li>';
        html += '</ol>';
        html += '<div style="margin-top:12px;padding:10px 14px;background:#f0fdf4;border-radius:8px;font-size:12px;color:#166534;">';
        html += '\ud83d\udca1 <b>Astuce :</b> Pour un calcul plus pr\u00e9cis de la dose d\u2019entretien (particulièrement si IMC \u2265 30), utiliser <b>vancopk.com</b>.';
        html += '</div>';
        html += '</div>';

        // Tableau 1 — Dose de charge
        html += '<div class="vanco-card">';
        html += '<h2>Tableau 1 \u2014 Dose de charge \u00d7 1 dose</h2>';
        html += '<div style="font-size:12px;color:#64748b;margin-bottom:12px;">Calcul\u00e9e \u00e0 25 mg/kg de poids r\u00e9el. Non applicable aux usagers sous th\u00e9rapie de remplacement r\u00e9nal.</div>';
        html += '<div style="overflow-x:auto;">';
        html += '<table class="vanco-table"><thead><tr><th>Poids (kg)</th><th>Dose (mg)</th><th>Poids (kg)</th><th>Dose (mg)</th><th>Poids (kg)</th><th>Dose (mg)</th></tr></thead><tbody>';
        html += '<tr><td>35 \u2013 39,9</td><td><b>750</b></td><td>60 \u2013 69,9</td><td><b>1500</b></td><td>90 \u2013 99,9</td><td><b>2250</b></td></tr>';
        html += '<tr><td>40 \u2013 49,9</td><td><b>1000</b></td><td>70 \u2013 79,9</td><td><b>1750</b></td><td>100 \u2013 129,9</td><td><b>2500</b></td></tr>';
        html += '<tr><td>50 \u2013 59,9</td><td><b>1250</b></td><td>80 \u2013 89,9</td><td><b>2000</b></td><td>130 et plus</td><td><b>3000</b></td></tr>';
        html += '</tbody></table>';
        html += '</div></div>';

        // Tableau 2 — Entretien
        html += '<div class="vanco-card">';
        html += '<h2>Tableau 2 \u2014 Traitement d\u2019entretien</h2>';
        html += '<div style="font-size:12px;color:#64748b;margin-bottom:12px;">Croiser la dose selon le poids <b>ET</b> la fr\u00e9quence selon le DFGe du laboratoire.</div>';
        html += '<div style="display:flex;gap:16px;flex-wrap:wrap;">';

        html += '<div style="flex:1;min-width:180px;">';
        html += '<div class="vanco-section-title">Dose selon le poids</div>';
        html += '<table class="vanco-table"><thead><tr><th>Poids (kg)</th><th>Dose / administration</th></tr></thead><tbody>';
        html += '<tr><td>35 \u2013 39,9</td><td><b>500 mg</b></td></tr>';
        html += '<tr><td>40 \u2013 59,9</td><td><b>750 mg</b></td></tr>';
        html += '<tr><td>60 \u2013 79,9</td><td><b>1000 mg</b></td></tr>';
        html += '<tr><td>80 \u2013 99,9</td><td><b>1250 mg</b></td></tr>';
        html += '<tr><td>100 et plus</td><td><b>1500 mg</b></td></tr>';
        html += '</tbody></table></div>';

        html += '<div style="flex:1;min-width:220px;">';
        html += '<div class="vanco-section-title">Fr\u00e9quence selon le DFGe (mL/min/1,73m\u00b2)</div>';
        html += '<table class="vanco-table"><thead><tr><th>DFGe</th><th>Fr\u00e9quence</th></tr></thead><tbody>';
        html += '<tr><td>Plus de 90</td><td><b>q 8h</b></td></tr>';
        html += '<tr><td>50 \u2013 90</td><td><b>q 12h</b></td></tr>';
        html += '<tr><td>15 \u2013 49</td><td><b>q 24h</b></td></tr>';
        html += '<tr><td>Moins de 15</td><td><b>Dose unique puis selon dosage</b></td></tr>';
        html += '</tbody></table></div>';
        html += '</div></div>';

        // Tableau 3 — Prélèvements
        html += '<div class="vanco-card">';
        html += '<h2>Tableau 3 \u2014 Moment des pr\u00e9l\u00e8vements recommand\u00e9s</h2>';
        html += '<div style="font-size:12px;color:#64748b;margin-bottom:12px;">Incluant la dose de charge s\u2019il y a lieu.</div>';
        html += '<div style="overflow-x:auto;">';
        html += '<table class="vanco-table"><thead><tr><th>Intervalle posologique</th><th>PIC</th><th>CREUX</th></tr></thead><tbody>';
        html += '<tr><td style="font-weight:700;">q8h ou q12h</td><td>60 \u00e0 120 min post fin de perfusion de la <b>4\u1d49 dose</b></td><td>Juste avant la <b>4\u1d49 dose</b></td></tr>';
        html += '<tr><td style="font-weight:700;">q24h</td><td>60 \u00e0 120 min post fin de perfusion de la <b>3\u1d49 dose</b></td><td>Juste avant la <b>3\u1d49 dose</b></td></tr>';
        html += '</tbody></table>';
        html += '</div>';
        html += '<div style="font-size:12px;color:#64748b;margin-top:10px;">Des pr\u00e9l\u00e8vements par <b>creux seulement</b> doivent \u00eatre effectu\u00e9s pour les patients dont l\u2019\u00e9tat d\u2019\u00e9quilibre n\u2019est pas atteint.</div>';
        html += '</div>';

        // Avertissement
        html += '<div class="vanco-warning">\u26a0\ufe0f <b>Avertissement clinique :</b> Ces tableaux sont fournis \u00e0 titre de r\u00e9f\u00e9rence. Toujours ajuster selon les dosages s\u00e9riques. Consulter un pharmacien pour tout ajustement posologique de la vancomycine et se r\u00e9f\u00e9rer au guide APES (bulletin N\u00b0 40).</div>';

        app.innerHTML = html;
    }

    function render() {
        var app = document.getElementById('calc-app');
        if (!app) return;
        var html = '';
        html += '<div class="calc-header">';
        html += '<h1>Calculateur posologique \u2014 Insuffisance r\u00e9nale</h1>';
        html += '<p>Bas\u00e9 sur le guide APES (RPEI) \u2014 Octobre 2019 \u2022 Adultes seulement \u2022 Le jugement clinique doit pr\u00e9valoir</p>';
        html += '</div>';

        html += '<div class="calc-card">';
        html += '<h2>1. Fonction r\u00e9nale</h2>';
        html += '<div style="display:flex;gap:8px;margin-bottom:16px;">';
        html += '<button id="calc-btn-cg" class="calc-sexe-btn ' + (state.mode === 'cg' ? 'active' : '') + '" onclick="calcSetMode(\'cg\')">Calculer (Cockcroft-Gault)</button>';
        html += '<button id="calc-btn-direct" class="calc-sexe-btn ' + (state.mode === 'direct' ? 'active' : '') + '" onclick="calcSetMode(\'direct\')">DFG d\u00e9j\u00e0 connu</button>';
        html += '</div>';
        if (state.mode === 'cg') {
            html += '<div style="margin-bottom:12px;display:flex;align-items:center;gap:8px;">';
            html += '<span style="font-size:13px;color:#64748b;width:50px">Sexe</span>';
            html += '<button id="calc-btn-h" class="calc-sexe-btn ' + (state.sexe === 'H' ? 'active' : '') + '" onclick="calcSetSexe(\'H\')">Homme</button>';
            html += '<button id="calc-btn-f" class="calc-sexe-btn ' + (state.sexe === 'F' ? 'active' : '') + '" onclick="calcSetSexe(\'F\')">Femme</button>';
            html += '</div>';
            html += '<div class="calc-grid">';
            html += '<div><label>\u00c2ge (ans)</label><input id="calc-age" type="number" placeholder="ex: 65" oninput="calcSetField(\'age\',this.value)"></div>';
            html += '<div><label>Poids r\u00e9el (kg)</label><input id="calc-poids" type="number" placeholder="ex: 70" oninput="calcSetField(\'poids\',this.value)"></div>';
            html += '<div><label>Taille (cm)</label><input id="calc-taille" type="number" placeholder="ex: 170" oninput="calcSetField(\'taille\',this.value)"></div>';
            html += '<div><label>Cr\u00e9atinine (\u03bcmol/L)</label><input id="calc-creat" type="number" placeholder="ex: 120" oninput="calcSetField(\'creat\',this.value)"></div>';
            html += '</div>';
        } else {
            html += '<div style="max-width:250px;">';
            html += '<label style="font-size:11px;color:#64748b;font-weight:600;display:block;margin-bottom:4px;">DFG / ClCr (mL/min)</label>';
            html += '<input id="calc-dfg-direct" type="number" placeholder="ex: 45" style="width:100%;padding:10px 14px;border-radius:8px;border:1.5px solid #e2e8f0;font-size:18px;font-weight:700;color:#0f2d5e;outline:none;" oninput="calcSetField(\'dfgDirect\',this.value)">';
            html += '<div style="font-size:11px;color:#64748b;margin-top:6px;">Valeur fournie par le laboratoire</div>';
            html += '</div>';
        }
        html += '<div id="calc-result-box" class="calc-result-box" style="display:none"></div>';
        html += '</div>';

        html += '<div class="calc-card">';
        html += '<h2>2. S\u00e9lection de l\'antimicrobien</h2>';
        html += '<input id="calc-search-input" class="calc-search" type="text" placeholder="\ud83d\udd0d Rechercher un antimicrobien..." oninput="calcSetSearch(this.value)">';
        html += '<div id="calc-search-results" class="calc-search-results"></div>';
        html += '<div id="calc-cats" class="calc-cats"></div>';
        html += '<div id="calc-drugs" class="calc-drugs"></div>';
        html += '</div>';

        html += '<div id="calc-drug-result"></div>';
        html += '<div class="calc-warning">\u26a0\ufe0f <b>Avertissement clinique :</b> Cet outil est bas\u00e9 sur le guide APES (RPEI, octobre 2019). Les ajustements servent uniquement \u00e0 guider la d\u00e9cision clinique \u2014 le jugement clinique doit pr\u00e9valoir. Consulter un pharmacien pour les cas complexes.</div>';
        html += '<div id="vanco-app" style="margin-top:24px;"></div>';

        app.innerHTML = html;
        renderResult();
        renderDrugSelector();
        renderVanco();
    }

    window.calcSetMode = function(mode) { state.mode = mode; render(); };
    window.calcSetField = function(field, val) { state[field] = val; renderResult(); };
    window.calcSetSexe = function(sexe) { state.sexe = sexe; renderResult(); };
    window.calcSetSearch = function(val) { state.search = val; state.selectedCat = ''; state.selectedDrug = ''; renderDrugSelector(); renderDrugResult(calcClcrFromState().clcr); };
    window.calcSetCat = function(cat) { state.selectedCat = cat; state.selectedDrug = ''; renderDrugSelector(); renderDrugResult(calcClcrFromState().clcr); };
    window.calcSetDrug = function(drug) { state.selectedDrug = drug; renderDrugSelector(); renderDrugResult(calcClcrFromState().clcr); };
    window.calcSelectDrug = function(cat, drug) { state.selectedCat = cat; state.selectedDrug = drug; state.search = ''; var si = document.getElementById('calc-search-input'); if(si) si.value=''; renderDrugSelector(); renderDrugResult(calcClcrFromState().clcr); };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', render);
    } else {
        render();
    }
}

/* ====== DEBUT Assistant Microguide (essai) ======
   Ajoute une bulle de recherche-reponse en bas a droite.
   ESSAI : actif uniquement pour le compte Thomas234 (voir le if ci-dessous).
   Pour l'ouvrir a tout le monde : enlever la ligne 'if (...) {' et son '}' final.
   Pour le retirer : supprimer tout ce bloc, de DEBUT a FIN.
   Installe le 2026-10-20. Ne touche a rien d'autre sur le wiki.
   ================================================ */
if (mw.config.get('wgUserName') === 'Thomas234') {

/* =====================================================================
   Assistant Microguide — recherche-réponse pour microguide.ca
   =====================================================================
   Fonctionne ENTIÈREMENT dans le navigateur du visiteur :
     - il lit le wiki par son API publique (api.php) ;
     - il bâtit son index tout seul, puis le garde en cache 24 h ;
     - il répond en recopiant mot pour mot le texte et les tableaux du wiki,
       avec le lien de la page.
   Aucun serveur à louer, aucune clé d'API, aucun service externe, aucune
   dépendance. Rien ne sort du wiki.

   INSTALLATION : coller ce fichier au complet dans MediaWiki:Common.js.

   POUR L'ENLEVER : vider MediaWiki:Common.js de ce bloc. Rien d'autre
   n'a été modifié sur le wiki.

   Réglage facultatif, avant ce bloc :
     window.MICROGUIDE_BASE = "https://microguide.ca";  // sinon : site courant
   ===================================================================== */

/* ---------- 1/4 vocabulaire ---------- */
// Vocabulaire de l'assistant microguide.
//
// GLOSSAIRE : français québécois, abréviations cliniques et noms de rue ->
// mots réellement écrits dans le wiki. Appliqué sans IA, donc sans erreur
// possible (principe repris du glossaire du bibliothécaire).
//
// INTENTIONS : quelle SORTE de renseignement la question demande, pour
// privilégier la bonne section (« quoi donner » -> section Traitements).

window.MICROGUIDE_GLOSSAIRE = {
  "atb": [
    "antibiotique",
    "antibiotiques"
  ],
  "abx": [
    "antibiotique",
    "antibiotiques"
  ],
  "anti biotique": [
    "antibiotique"
  ],
  "traiter": [
    "traitement",
    "traitements"
  ],
  "traite": [
    "traitement"
  ],
  "soigner": [
    "traitement"
  ],
  "donner": [
    "traitement"
  ],
  "prescrire": [
    "traitement"
  ],
  "couvrir": [
    "couverture",
    "traitement"
  ],
  "couvre": [
    "couverture"
  ],
  "tuer": [
    "traitement",
    "sensibilite"
  ],
  "marche": [
    "efficace",
    "traitement"
  ],
  "fonctionne": [
    "efficace",
    "traitement"
  ],
  "pogner": [
    "infection",
    "acquisition"
  ],
  "attraper": [
    "infection",
    "acquisition"
  ],
  "poumon": [
    "pulmonaire",
    "pneumonie"
  ],
  "poumons": [
    "pulmonaire",
    "pneumonie"
  ],
  "pipi": [
    "urinaire"
  ],
  "urine": [
    "urinaire"
  ],
  "vessie": [
    "cystite",
    "urinaire"
  ],
  "rein": [
    "pyelonephrite",
    "urinaire"
  ],
  "reins": [
    "pyelonephrite",
    "urinaire"
  ],
  "sang": [
    "bacteriemie",
    "sepsis",
    "hemoculture"
  ],
  "coeur": [
    "endocardite"
  ],
  "peau": [
    "cutanee",
    "tissus mous",
    "cellulite"
  ],
  "os": [
    "osteomyelite",
    "osteoarticulaire"
  ],
  "cerveau": [
    "meningite"
  ],
  "ventre": [
    "intra abdominale",
    "digestif"
  ],
  "diarrhee": [
    "digestif",
    "colite"
  ],
  "oreille": [
    "otite"
  ],
  "gorge": [
    "pharyngite",
    "orl"
  ],
  "yeux": [
    "keratite",
    "ophtalmologique"
  ],
  "oeil": [
    "keratite",
    "ophtalmologique"
  ],
  "bibitte": [
    "bacterie"
  ],
  "germe": [
    "bacterie"
  ],
  "microbe": [
    "bacterie"
  ],
  "resistant": [
    "resistance",
    "resistances"
  ],
  "resiste": [
    "resistance"
  ],
  "dose": [
    "posologie",
    "dose"
  ],
  "poso": [
    "posologie"
  ],
  "grossesse": [
    "grossesse",
    "enceinte"
  ],
  "enceinte": [
    "grossesse"
  ],
  "allergie": [
    "allergie",
    "allergique"
  ],
  "penicilline": [
    "penicilline",
    "penicillines"
  ],
  "pseudo": [
    "pseudomonas"
  ],
  "staph": [
    "staphylococcus",
    "staphyloccocus"
  ],
  "strep": [
    "streptococcus",
    "streptocoque"
  ],
  "pneumo": [
    "pneumoniae",
    "pneumocoque"
  ],
  "sarm": [
    "sarm",
    "meticilline",
    "resistant"
  ],
  "e coli": [
    "escherichia",
    "coli"
  ],
  "ecoli": [
    "escherichia",
    "coli"
  ],
  "c diff": [
    "clostridioides",
    "difficile"
  ],
  "cdiff": [
    "clostridioides",
    "difficile"
  ],
  "klebs": [
    "klebsiella"
  ],
  "entero": [
    "enterocoque",
    "enterococcus",
    "enterobacter"
  ],
  "bgn": [
    "gram negatif"
  ],
  "bgp": [
    "gram positif"
  ],
  "cocci": [
    "cocci",
    "coque"
  ],
  "labo": [
    "laboratoire"
  ],
  "gram": [
    "gram"
  ],
  "vanco": [
    "vancomycine"
  ],
  "cipro": [
    "ciprofloxacine"
  ],
  "levo": [
    "levofloxacine"
  ],
  "moxi": [
    "moxifloxacine"
  ],
  "ceftri": [
    "ceftriaxone"
  ],
  "cefta": [
    "ceftazidime"
  ],
  "pip tazo": [
    "piperacilline",
    "tazobactam"
  ],
  "piptazo": [
    "piperacilline",
    "tazobactam"
  ],
  "tazo": [
    "tazobactam",
    "piperacilline"
  ],
  "mero": [
    "meropeneme",
    "meropenem"
  ],
  "erta": [
    "ertapenem"
  ],
  "clinda": [
    "clindamycine"
  ],
  "flagyl": [
    "metronidazole"
  ],
  "metro": [
    "metronidazole"
  ],
  "doxy": [
    "doxycycline"
  ],
  "azithro": [
    "azithromycine"
  ],
  "clav": [
    "clavulanate",
    "amoxicilline"
  ],
  "amox": [
    "amoxicilline"
  ],
  "cloxa": [
    "cloxacilline"
  ],
  "cefaz": [
    "cefazoline",
    "cefazolin"
  ],
  "keflex": [
    "cephalexine"
  ],
  "genta": [
    "gentamicine"
  ],
  "tobra": [
    "tobramycine"
  ],
  "septra": [
    "triclotrimoxazole",
    "tmp",
    "smx"
  ],
  "tmp smx": [
    "triclotrimoxazole"
  ],
  "fkp": [
    "fibrose kystique",
    "fkp"
  ],
  "mpoc": [
    "mpoc"
  ],
  "si": [
    "soins intensifs"
  ],
  "usi": [
    "soins intensifs"
  ]
};

window.MICROGUIDE_INTENTIONS = {
  "traitement": {
    "declencheurs": [
      "traiter",
      "traite",
      "traitement",
      "atb",
      "abx",
      "antibiotique",
      "antibiotiques",
      "soigner",
      "donner",
      "prescrire",
      "couvrir",
      "couverture",
      "efficace",
      "quoi donner",
      "tuer",
      "marche",
      "fonctionne",
      "choix",
      "empirique",
      "per os",
      "po",
      "iv"
    ],
    "titres": [
      "traitement",
      "traitements",
      "efficace",
      "efficaces",
      "spectre",
      "couverture",
      "sensibilite",
      "posologie"
    ]
  },
  "resistance": {
    "declencheurs": [
      "resistance",
      "resistances",
      "resistant",
      "resiste",
      "mecanisme",
      "mecanismes",
      "blse",
      "carbapenemase",
      "sarm",
      "ervr"
    ],
    "titres": [
      "resistance",
      "resistances",
      "mecanisme",
      "mecanismes"
    ]
  },
  "clinique": {
    "declencheurs": [
      "infection",
      "infections",
      "cause",
      "causes",
      "clinique",
      "maladie",
      "symptome",
      "symptomes",
      "manifestation",
      "manifestations",
      "tableau",
      "pneumonie",
      "cellulite",
      "endocardite",
      "meningite",
      "urinaire",
      "osteomyelite",
      "abces",
      "bacteriemie",
      "sepsis",
      "otite",
      "keratite"
    ],
    "titres": [
      "infection",
      "infections",
      "clinique",
      "manifestations",
      "principales"
    ]
  },
  "epidemiologie": {
    "declencheurs": [
      "epidemiologie",
      "reservoir",
      "ou vit",
      "transmission",
      "attraper",
      "pogner",
      "acquisition",
      "colonisation",
      "colonisant",
      "risque",
      "nosocomial",
      "nosocomiale",
      "communautaire",
      "porteur"
    ],
    "titres": [
      "epidemiologie",
      "reservoir",
      "transmission",
      "acquisition",
      "specificite"
    ]
  },
  "laboratoire": {
    "declencheurs": [
      "laboratoire",
      "labo",
      "identification",
      "identifier",
      "culture",
      "gram",
      "microscope",
      "coloration",
      "catalase",
      "coagulase",
      "oxydase",
      "lactose",
      "milieu",
      "gelose",
      "hemoculture",
      "tsi"
    ],
    "titres": [
      "laboratoire",
      "laboratoires",
      "microscope",
      "identification",
      "culture",
      "caracteristiques",
      "tests"
    ]
  }
};

/* ---------- 2/4 construction de l'index ---------- */
// Construit l'index de microguide.ca DANS LE NAVIGATEUR, à partir de l'API
// du wiki. Aucun fichier à maintenir : l'index se refait tout seul, donc il
// est toujours à jour avec le wiki.
//
// Deux appels suffisent : le contenu de toutes les pages, puis l'URL des
// images. Environ 130 Ko, gardés en cache local pour 24 h.

(function (root) {
  "use strict";

  var MOTS_VIDES = ("a au aux avec ce ces dans de des du elle en et eux il ils je la le les leur lui ma mais " +
    "me meme mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton " +
    "tu un une vos votre vous y est sont etre ete suis es sommes etes ont ai as avons avez avait etait sera " +
    "seront c d j l m n s t quel quelle quels quelles quoi comment pourquoi quand combien cet cette plus " +
    "moins tres bien aussi alors donc car si comme tout tous toute toutes autre autres faire fait fais peut " +
    "peux peuvent doit dois doivent").split(" ");

  function normalise(s) {
    return (s || "").toLowerCase().normalize("NFD")
      .replace(/[̀-ͯ]/g, "")
      .replace(/[-'’/]/g, " ");
  }

  var VIDES = new Set(MOTS_VIDES);

  function mots(s) {
    return (normalise(s).match(/[a-z0-9]+/g) || []).filter(function (w) {
      return w.length > 1 && !VIDES.has(w);
    });
  }

  // ------------------------------------------------ nettoyage du wikitext

  function cellules(bloc) {
    var out = [];
    bloc.split("\n").forEach(function (l) {
      l = l.trim();
      if (l[0] === "!" || l[0] === "|") {
        l = l.replace(/^[!|]+/, "");
        if (l.indexOf("|") >= 0 && l.indexOf("||") < 0) l = l.replace(/^[^|]*\|(?!\|)/, "");
        l.split("||").forEach(function (c) {
          c = c.replace(/^[a-z\-]+\s*=\s*"[^"]*"\s*\|/, "").trim();
          if (c && !/^[-\s|]*$/.test(c)) out.push(c);
        });
      }
    });
    return out.join("\n");
  }

  function nettoyer(t) {
    t = t.replace(/<!--[\s\S]*?-->/g, "");
    t = t.replace(/<ref[^>]*\/>/g, "").replace(/<ref[\s\S]*?<\/ref>/g, "");
    for (var i = 0; i < 5; i++) {
      var t2 = t.replace(/\{\{[^{}]*\}\}/g, "");
      if (t2 === t) break;
      t = t2;
    }
    t = t.replace(/\{\|[\s\S]*?\|\}/g, function (m) { return cellules(m); });
    t = t.replace(/\[\[(?:Fichier|File|Image)\s*:[^\]]*\]\]/gi, "");
    t = t.replace(/\[\[([^\]|]*)\|([^\]]*)\]\]/g, "$2").replace(/\[\[([^\]]*)\]\]/g, "$1");
    t = t.replace(/\[https?:\/\/\S+\s+([^\]]*)\]/g, "$1").replace(/\[https?:\/\/\S+\]/g, "");
    t = t.replace(/<br\s*\/?>/gi, "\n");
    t = t.replace(/<\/?(div|span|p|big|small|center|u|b|i|sub|sup|font|blockquote)[^>]*>/gi, "");
    t = t.replace(/<[^>]+>/g, " ");
    t = t.replace(/'''/g, "").replace(/''/g, "");
    t = t.replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
    t = t.replace(/[ \t]+/g, " ").replace(/\n\s*\n\s*\n+/g, "\n\n");
    return t.trim();
  }

  // ------------------------------------------------ découpage en sections

  function decouper(wikitext) {
    var lignes = wikitext.split("\n");
    var sections = [], cur = { titre: "", lignes: [] };
    lignes.forEach(function (ligne) {
      var m = ligne.match(/^\s*(={2,6})\s*(.+?)\s*\1\s*$/);
      if (m) {
        if (cur.lignes.length) sections.push(cur);
        var brut = m[2];
        // un titre qui n'est qu'une image n'est pas un titre
        if (/^\s*\[\[(?:Fichier|File|Image)\s*:/i.test(brut)) brut = "";
        cur = { titre: nettoyer(brut) || brut.replace(/^['= ]+|['= ]+$/g, ""), lignes: [] };
      } else {
        cur.lignes.push(ligne);
      }
    });
    if (cur.lignes.length) sections.push(cur);

    return sections.map(function (s) {
      var brut = s.lignes.join("\n");
      var imgs = [];
      var re = /\[\[(?:Fichier|File|Image)\s*:\s*([^|\]]+)/gi, m;
      while ((m = re.exec(brut))) imgs.push(m[1].trim().replace(/_/g, " "));
      var texte = nettoyer(brut);
      var puces = [], prose = [];
      texte.split("\n").forEach(function (l) {
        l = l.trim();
        if (!l) return;
        if (/^[\*\#•·–-]\s*/.test(l)) puces.push(l.replace(/^[\*\#•·–-]+\s*/, "").trim());
        else prose.push(l);
      });
      return { titre: s.titre, puces: puces, prose: prose, images: imgs };
    }).filter(function (s) {
      return s.puces.length || s.prose.length || s.images.length;
    });
  }

  // ------------------------------------------------ appels à l'API

  function api(params, base) {
    var u = (base || "") + "/api.php?origin=*&format=json&formatversion=2&" +
      Object.keys(params).map(function (k) {
        return encodeURIComponent(k) + "=" + encodeURIComponent(params[k]);
      }).join("&");
    return fetch(u, { credentials: "omit" }).then(function (r) {
      if (!r.ok) throw new Error("API " + r.status);
      return r.json();
    });
  }

  function toutesLesPages(base) {
    var pages = [];
    function tour(cont) {
      var p = {
        action: "query", generator: "allpages", gapnamespace: 0, gaplimit: "max",
        prop: "revisions", rvprop: "content|timestamp", rvslots: "main"
      };
      if (cont) for (var k in cont) p[k] = cont[k];
      return api(p, base).then(function (d) {
        ((d.query && d.query.pages) || []).forEach(function (pg) {
          var rev = pg.revisions && pg.revisions[0];
          var txt = rev && rev.slots && rev.slots.main && rev.slots.main.content;
          if (txt) pages.push({ titre: pg.title, wikitext: txt });
        });
        if (d.continue) return tour(d.continue);
        return pages;
      });
    }
    return tour(null);
  }

  function toutesLesImages(base) {
    var map = {};
    function tour(cont) {
      var p = { action: "query", list: "allimages", ailimit: "max" };
      if (cont) for (var k in cont) p[k] = cont[k];
      return api(p, base).then(function (d) {
        ((d.query && d.query.allimages) || []).forEach(function (im) {
          map[im.name.replace(/_/g, " ")] = im.url;
        });
        if (d.continue) return tour(d.continue);
        return map;
      });
    }
    return tour(null);
  }

  // ------------------------------------------------ assemblage de l'index

  function assembler(pagesBrutes, imgMap, base) {
    var pages = [], sections = [], vus = {};

    // Le wiki contient des redirections et des pages-coquilles (titres mal
    // orthographiés, pages vides) qui, sans ça, passent devant les vraies.
    pagesBrutes = pagesBrutes.filter(function (p) {
      if (/^\s*#\s*REDIRECT/i.test(p.wikitext)) return false;
      return nettoyer(p.wikitext).replace(/\s/g, "").length >= 80;
    });
    // à titre égal, on garde la page la plus fournie
    pagesBrutes.sort(function (a, b) { return b.wikitext.length - a.wikitext.length; });

    pagesBrutes.forEach(function (p) {
      if (vus[p.titre]) return;            // redirections vers le même titre
      var secs = decouper(p.wikitext);
      if (!secs.length) return;
      vus[p.titre] = 1;

      var pid = pages.length;
      var imgsPage = [];
      secs.forEach(function (sec, k) {
        sec.images.forEach(function (n) {
          if (imgMap[n]) {
            imgsPage.push({
              nom: n, url: imgMap[n],
              section: sec.titre || p.titre,
              entete: k === 0 && !sec.titre
            });
          }
        });
      });

      pages.push({
        id: pid, titre: p.titre,
        url: base + "/index.php/" + encodeURI(p.titre.replace(/ /g, "_")),
        images: imgsPage
      });

      secs.forEach(function (s) {
        var plat = s.prose.concat(s.puces).join(" ");
        var images = s.images.filter(function (n) { return imgMap[n]; })
          .map(function (n) { return { nom: n, url: imgMap[n] }; });
        if (plat.length < 15 && !images.length) return;
        sections.push({
          page: pid, titre: s.titre || p.titre,
          puces: s.puces, prose: s.prose, images: images,
          // le titre compte double : une section « Couverture » doit se
          // trouver même si son contenu n'est qu'un tableau en image
          mots: mots((s.titre || "") + " " + (s.titre || "") + " " + plat)
        });
      });
    });

    var df = {};
    sections.forEach(function (s) {
      new Set(s.mots).forEach(function (w) { df[w] = (df[w] || 0) + 1; });
    });
    sections.forEach(function (s) {
      var tf = {};
      s.mots.forEach(function (w) { tf[w] = (tf[w] || 0) + 1; });
      s.tf = tf; s.len = s.mots.length; delete s.mots;
    });

    return {
      pages: pages, sections: sections, df: df, N: sections.length,
      wiki: base, mots_vides: MOTS_VIDES,
      glossaire: root.MICROGUIDE_GLOSSAIRE || {},
      intentions: root.MICROGUIDE_INTENTIONS || {},
      bati: Date.now()
    };
  }

  // ------------------------------------------------ cache local 24 h

  var CLE = "microguide-index-v1";

  function duCache() {
    try {
      var b = localStorage.getItem(CLE);
      if (!b) return null;
      var d = JSON.parse(b);
      if (!d.bati || Date.now() - d.bati > 864e5) return null;
      d.glossaire = root.MICROGUIDE_GLOSSAIRE || {};
      d.intentions = root.MICROGUIDE_INTENTIONS || {};
      return d;
    } catch (e) { return null; }
  }

  function auCache(d) {
    try { localStorage.setItem(CLE, JSON.stringify(d)); } catch (e) { /* quota : tant pis */ }
  }

  // Construit (ou relit) l'index. Renvoie une promesse.
  function charger(base) {
    base = base || "";
    var c = duCache();
    if (c) return Promise.resolve(c);
    return Promise.all([toutesLesPages(base), toutesLesImages(base)])
      .then(function (r) {
        var ix = assembler(r[0], r[1], base);
        auCache(ix);
        return ix;
      });
  }

  root.MicroguideIndexeur = {
    charger: charger, assembler: assembler, decouper: decouper,
    nettoyer: nettoyer, mots: mots, viderCache: function () {
      try { localStorage.removeItem(CLE); } catch (e) {}
    }
  };
})(typeof module !== "undefined" ? module.exports : window);

/* ---------- 3/4 moteur de réponse ---------- */
// Moteur de réponse de l'assistant microguide — AUCUNE INVENTION POSSIBLE.
//
// La réponse est composée uniquement de phrases et de puces recopiées
// telles quelles depuis les pages du wiki, avec le titre de la section et
// le lien. Il n'y a pas de modèle de langue qui réécrit : le texte affiché
// existe mot pour mot sur microguide.ca.
//
// Principe repris du bibliothécaire de Thomas : les passages sources SONT
// la réponse.

(function (root) {
  "use strict";

  function normalise(s) {
    return (s || "")
      .toLowerCase()
      .normalize("NFD")
      .replace(/[̀-ͯ]/g, "");
  }

  function Moteur(index) {
    this.ix = index;
    this.vides = new Set(index.mots_vides || []);
    this.gloss = index.glossaire || {};
    // longueur moyenne des sections, pour BM25
    var t = 0;
    for (var i = 0; i < index.sections.length; i++) t += index.sections[i].len;
    this.avgdl = t / Math.max(1, index.sections.length);
  }

  Moteur.prototype.mots = function (s) {
    var self = this;
    return (normalise(s).match(/[a-z0-9]+/g) || []).filter(function (w) {
      return w.length > 1 && !self.vides.has(w);
    });
  };

  // Ajoute le vocabulaire québécois / les abréviations cliniques
  Moteur.prototype.etendre = function (q) {
    var n = normalise(q);
    var base = this.mots(q);
    var ajouts = [];
    for (var cle in this.gloss) {
      var re = new RegExp("\\b" + cle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
      if (re.test(n)) {
        var vals = this.gloss[cle];
        for (var i = 0; i < vals.length; i++) {
          ajouts = ajouts.concat(this.mots(vals[i]));
        }
      }
    }
    // les mots de la question pèsent plus que les ajouts du glossaire
    var poids = {};
    base.forEach(function (w) { poids[w] = Math.max(poids[w] || 0, 1); });
    ajouts.forEach(function (w) { poids[w] = Math.max(poids[w] || 0, 0.6); });
    return poids;
  };

  // Quelle sorte de renseignement la question demande-t-elle ?
  // « quoi donner pour un pseudomonas » -> traitement, donc on privilégie
  // les sections « Traitements » plutôt qu'une autre qui parle aussi d'ATB.
  Moteur.prototype.intentions = function (question) {
    var n = normalise(question), out = [];
    var defs = this.ix.intentions || {};
    for (var nom in defs) {
      var d = defs[nom], touche = false;
      for (var i = 0; i < d.declencheurs.length; i++) {
        var t = d.declencheurs[i];
        var re = new RegExp("\\b" + t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
        if (re.test(n)) { touche = true; break; }
      }
      if (touche) out.push({ nom: nom, titres: d.titres });
    }
    return out;
  };

  // BM25 sur les sections
  Moteur.prototype.chercher = function (question, nb) {
    var ix = this.ix, self = this;
    var poids = this.etendre(question);
    var inten = this.intentions(question);
    var k1 = 1.4, b = 0.72, N = ix.N;
    var res = [];

    // Quelle page la question NOMME-t-elle ? « le SARM ça se traite comment »
    // doit répondre avec la page du SARM, pas avec une autre page qui parle
    // aussi de traitement. On mesure la correspondance avec le titre de page,
    // pondérée par la rareté des mots (un mot rare identifie mieux).
    var entite = [];
    for (var pi = 0; pi < ix.pages.length; pi++) {
      var mt = self.mots(ix.pages[pi].titre), e = 0;
      var vusMot = {};
      for (var mi = 0; mi < mt.length; mi++) {
        var mw = mt[mi];
        if (vusMot[mw]) continue;
        vusMot[mw] = 1;
        if (poids[mw] >= 0.6) {
          var dfp = ix.df[mw] || 1;
          e += Math.log(1 + (N - dfp + 0.5) / (dfp + 0.5));
        }
      }
      entite[pi] = e;
    }
    var entiteMax = Math.max.apply(null, entite.concat([0]));

    for (var i = 0; i < ix.sections.length; i++) {
      var s = ix.sections[i], score = 0, touches = 0;
      for (var w in poids) {
        var f = s.tf[w];
        if (!f) continue;
        var df = ix.df[w] || 1;
        var idf = Math.log(1 + (N - df + 0.5) / (df + 0.5));
        score += poids[w] * idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * s.len / self.avgdl));
        touches++;
      }
      if (!score) continue;
      // bonus quand le titre de la page ou de la section correspond
      var tp = normalise(ix.pages[s.page].titre);
      var ts = normalise(s.titre);
      for (var w2 in poids) {
        if (poids[w2] < 1) continue;
        if (tp.indexOf(w2) >= 0) score += 2.2 * poids[w2];
        if (ts.indexOf(w2) >= 0) score += 1.5 * poids[w2];
      }
      // la section répond-elle à la sorte de question posée ?
      var bonusIntention = 0;
      for (var a = 0; a < inten.length; a++) {
        var titres = inten[a].titres;
        for (var c = 0; c < titres.length; c++) {
          if (ts.indexOf(titres[c]) >= 0) {
            bonusIntention = Math.max(bonusIntention, 1);
            break;
          }
        }
      }
      if (inten.length) {
        // multiplicatif : une section hors sujet garde son score, la bonne
        // section passe devant sans écraser la pertinence des mots.
        score *= bonusIntention ? 1.9 : 0.85;
      }
      // la page nommée par la question passe devant les autres
      if (entiteMax > 0 && entite[s.page] > 0) {
        score *= 1 + 1.6 * (entite[s.page] / entiteMax);
      }
      res.push({ i: i, score: score, touches: touches });
    }
    res.sort(function (a, b) { return b.score - a.score; });
    return res.slice(0, nb || 8);
  };

  // Compose la réponse : toujours un texte, toujours du verbatim + source.
  Moteur.prototype.repondre = function (question) {
    var ix = this.ix;
    var hits = this.chercher(question, 10);
    var inten = this.intentions(question);

    if (!hits.length) {
      return {
        etat: "rien",
        intro: "Je n'ai rien trouvé sur microguide.ca pour cette question. " +
               "Le wiki ne semble pas couvrir ce sujet — il n'y a donc rien que je puisse te citer.",
        blocs: [],
        suggestions: ix.pages.slice(0, 0)
      };
    }

    // on regroupe par page, en gardant l'ordre de pertinence
    var parPage = {}, ordre = [];
    hits.forEach(function (h) {
      var s = ix.sections[h.i];
      if (!parPage[s.page]) { parPage[s.page] = []; ordre.push(s.page); }
      parPage[s.page].push({ s: s, score: h.score });
    });

    var meilleur = hits[0].score;
    var blocs = [];
    // page principale : jusqu'à 3 sections ; puis 2 pages d'appoint, 1 section
    ordre.slice(0, 3).forEach(function (pid, rang) {
      var page = ix.pages[pid];
      var secs = parPage[pid]
        .filter(function (x) { return x.score >= meilleur * (rang === 0 ? 0.28 : 0.45); })
        .slice(0, rang === 0 ? 3 : 1);
      if (!secs.length) return;
      // Images à afficher : celles dont la section correspond à la sorte de
      // question posée (un tableau de couverture pour une question de
      // traitement), plus la fiche d'en-tête de la page quand c'est la page
      // principale. Les images résument souvent mieux que le texte.
      var titresRetenus = {};
      secs.forEach(function (x) { titresRetenus[normalise(x.s.titre)] = 1; });
      var images = (page.images || []).filter(function (im) {
        var ns = normalise(im.section);
        if (titresRetenus[ns]) return true;
        for (var a = 0; a < inten.length; a++) {
          var titres = inten[a].titres;
          for (var c = 0; c < titres.length; c++) {
            if (ns.indexOf(titres[c]) >= 0) return true;
          }
        }
        return rang === 0 && im.entete;
      }).slice(0, 3);

      blocs.push({
        page: page.titre,
        url: page.url,
        images: images,
        sections: secs.map(function (x) {
          return { titre: x.s.titre, prose: x.s.prose, puces: x.s.puces };
        })
      });
    });

    var faible = meilleur < 6;
    var p0 = blocs.length ? blocs[0].page : null;
    var intro;
    if (faible) {
      intro = "Je ne trouve pas de passage qui répond clairement à cette question sur microguide.ca. " +
              "Voici ce qui s'en rapproche le plus, recopié tel quel — à vérifier, ça ne répond " +
              "peut-être pas à ce que tu cherches.";
    } else {
      intro = "D'après " + (blocs.length > 1 ? "les pages du wiki" : "la page « " + p0 + " »") +
              ", voici ce qui est écrit sur microguide.ca, recopié mot pour mot :";
    }

    return { etat: faible ? "faible" : "ok", intro: intro, blocs: blocs };
  };

  // Rendu texte (pour les essais en ligne de commande)
  Moteur.prototype.texte = function (question) {
    var r = this.repondre(question);
    var out = ["Q: " + question, "", r.intro, ""];
    r.blocs.forEach(function (b) {
      out.push("── " + b.page + "  <" + b.url + ">");
      (b.images || []).forEach(function (im) {
        out.push("   [IMAGE] " + im.nom + "  (§ " + im.section + ")");
      });
      b.sections.forEach(function (s) {
        out.push("   § " + s.titre);
        s.prose.forEach(function (p) { out.push("     " + p); });
        s.puces.forEach(function (p) { out.push("     • " + p); });
      });
      out.push("");
    });
    return out.join("\n");
  };

  root.MicroguideMoteur = Moteur;
})(typeof module !== "undefined" ? module.exports : window);

/* ---------- 4/4 bulle ---------- */
// Bulle de l'assistant microguide : lanceur en bas à droite, visible sur
// toutes les pages du wiki. Tout tourne dans le navigateur du visiteur, à
// partir de l'API du wiki : aucun serveur, aucune clé, aucun service externe.

(function () {
  "use strict";

  if (window.__microguideAssistant) return;   // déjà chargé
  window.__microguideAssistant = true;

  var BASE = (window.MICROGUIDE_BASE !== undefined)
    ? window.MICROGUIDE_BASE
    : (location.origin || "");

  var CSS = [
    '.mga-launch{position:fixed;z-index:9000;right:calc(18px + env(safe-area-inset-right,0px));',
    'bottom:calc(18px + env(safe-area-inset-bottom,0px));display:flex;align-items:center;gap:9px;',
    'background:#3f7490;color:#fff;border:none;font:600 14.5px/1 inherit;padding:13px 19px;',
    'border-radius:30px;cursor:pointer;box-shadow:0 6px 22px -6px rgba(20,40,55,.5)}',
    '.mga-launch:hover{filter:brightness(1.08)}',
    '.mga-launch svg{width:18px;height:18px;flex:0 0 auto}',
    '.mga-panel{position:fixed;z-index:9001;right:calc(18px + env(safe-area-inset-right,0px));',
    'bottom:calc(18px + env(safe-area-inset-bottom,0px));',
    'width:min(440px,calc(100vw - 32px));max-height:min(680px,calc(100vh - 36px));',
    'background:#fff;color:#1c2228;border:1px solid #dcd8d0;border-radius:12px;',
    'box-shadow:0 18px 50px -14px rgba(15,30,42,.45);display:flex;flex-direction:column;',
    'overflow:hidden;font:400 15px/1.6 "IBM Plex Sans",system-ui,sans-serif}',
    '.mga-head{display:flex;align-items:center;gap:10px;padding:13px 15px;border-bottom:1px solid #dcd8d0}',
    '.mga-head .t{font-weight:600;font-size:14.5px;flex:1;min-width:0}',
    '.mga-head .t em{display:block;font-style:normal;font-size:11px;color:#8995a0;font-weight:400}',
    '.mga-ico{background:none;border:none;color:#8995a0;cursor:pointer;font-size:19px;line-height:1;padding:4px 6px;border-radius:5px}',
    '.mga-ico:hover{color:#1c2228;background:#f4f1ea}',
    '.mga-log{flex:1;overflow-y:auto;padding:15px;display:flex;flex-direction:column;gap:17px;min-height:0}',
    '.mga-intro{font-size:13.5px;color:#55616b}',
    '.mga-intro p{margin:0 0 9px}',
    '.mga-rule{border-left:3px solid #3f7490;background:#e4eff6;padding:9px 12px;color:#1c2228}',
    '.mga-samples{display:flex;flex-direction:column;gap:6px;margin-top:11px}',
    '.mga-samples button{text-align:left;background:none;border:1px solid #dcd8d0;color:#1c2228;',
    'font:400 13px/1.5 inherit;padding:8px 11px;border-radius:6px;cursor:pointer}',
    '.mga-samples button:hover{border-color:#3f7490;background:#e4eff6}',
    '.mga-q{align-self:flex-end;max-width:88%;background:#3f7490;color:#fff;padding:9px 13px;',
    'border-radius:12px 12px 3px 12px;font-size:14px}',
    '.mga-a{font-size:14px}',
    '.mga-lead{color:#55616b;margin:0 0 12px}',
    '.mga-lead.weak{background:#faf0dd;border-left:3px solid #8a5a1c;padding:9px 12px;color:#1c2228}',
    '.mga-src{border-top:1px solid #dcd8d0;padding-top:11px;margin-top:13px}',
    '.mga-src:first-of-type{border-top:none;padding-top:0;margin-top:0}',
    '.mga-srch{display:flex;align-items:baseline;gap:7px;flex-wrap:wrap;margin-bottom:8px}',
    '.mga-srch .lbl{font-family:"IBM Plex Mono",monospace;font-size:10px;letter-spacing:.1em;',
    'text-transform:uppercase;color:#8995a0}',
    '.mga-srch a{color:#3f7490;font-weight:600;font-size:14px;text-decoration:none;border-bottom:1px solid transparent}',
    '.mga-srch a:hover{border-bottom-color:#3f7490}',
    '.mga-sec{margin:0 0 11px}',
    '.mga-sect{font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.07em;',
    'text-transform:uppercase;color:#3f7490;margin-bottom:5px}',
    '.mga-quote{font-family:"IBM Plex Serif",Georgia,serif;font-size:14px;background:#f4f1ea;',
    'border-left:2px solid #dcd8d0;padding:9px 12px;color:#1c2228}',
    '.mga-quote p{margin:0 0 6px}.mga-quote p:last-child{margin-bottom:0}',
    '.mga-quote ul{margin:5px 0 0;padding-left:19px}.mga-quote li{margin:2px 0}',
    '.mga-fig{margin:0 0 11px}',
    '.mga-fig img{display:block;width:100%;height:auto;border:1px solid #dcd8d0;border-radius:4px;background:#fff}',
    '.mga-fig figcaption{font-family:"IBM Plex Mono",monospace;font-size:10.5px;color:#8995a0;margin-top:4px}',
    '.mga-none{background:#faf0dd;border-left:3px solid #8a5a1c;padding:11px 13px;font-size:13.5px}',
    '.mga-ask{border-top:1px solid #dcd8d0;padding:11px;display:flex;gap:8px}',
    '.mga-ask input{flex:1;min-width:0;background:#fbfaf7;color:#1c2228;border:1px solid #dcd8d0;',
    'border-radius:7px;padding:10px 12px;font:400 14px/1.4 inherit}',
    '.mga-ask input:focus{outline:2px solid #3f7490;outline-offset:-1px;border-color:#3f7490}',
    '.mga-ask button{background:#3f7490;color:#fff;border:none;border-radius:7px;padding:0 15px;',
    'font:600 14px/1 inherit;cursor:pointer}',
    '.mga-foot{padding:0 13px 11px;font-family:"IBM Plex Mono",monospace;font-size:11px;color:#8995a0}',
    '@media (max-width:460px){.mga-panel{right:8px;left:8px;width:auto}}',
    // Nos règles .mga-panel/.mga-launch ont une spécificité plus forte que la
    // règle [hidden] du navigateur : sans ceci, le panneau reste affiché même
    // quand il est marqué caché.
    '.mga-panel[hidden],.mga-launch[hidden]{display:none!important}'
  ].join("");

  var SAMPLES = [
    "quels antibiotiques pour traiter un pseudomonas ?",
    "la couverture de la ceftriaxone",
    "comment on traite un c diff",
    "le SARM ça se traite comment",
    "c'est quoi la posologie de la gentamicine"
  ];

  function el(tag, cls, txt) {
    var n = document.createElement(tag);
    if (cls) n.className = cls;
    if (txt != null) n.textContent = txt;
    return n;
  }

  var moteur = null, chargement = null, log, intro, champ, panel, launch;

  function construire() {
    var style = el("style");
    style.textContent = CSS;
    document.head.appendChild(style);

    launch = el("button", "mga-launch");
    launch.setAttribute("aria-label", "Ouvrir l'assistant");
    launch.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
      'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 11.5a8.4 8.4 0 0 1-.9 ' +
      '3.8A8.5 8.5 0 0 1 12.5 20a8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7A8.4 8.4 0 0 1 4 11.5a8.5 8.5 0 0 1 ' +
      '4.7-7.6A8.4 8.4 0 0 1 12.5 3h.5a8.5 8.5 0 0 1 8 8z"/></svg>';
    launch.appendChild(document.createTextNode("Demander au guide"));
    document.body.appendChild(launch);

    panel = el("section", "mga-panel");
    panel.hidden = true;
    panel.setAttribute("aria-label", "Assistant Microguide");

    var head = el("div", "mga-head");
    var t = el("div", "t", "Assistant Microguide");
    t.appendChild(el("em", null, "répond uniquement avec le contenu du wiki"));
    head.appendChild(t);
    var bReset = el("button", "mga-ico", "⟲");
    bReset.title = "Effacer";
    var bClose = el("button", "mga-ico", "✕");
    bClose.title = "Fermer";
    head.appendChild(bReset);
    head.appendChild(bClose);
    panel.appendChild(head);

    log = el("div", "mga-log");
    intro = el("div", "mga-intro");
    intro.appendChild(el("p", null, "Pose ta question en français, comme tu la dirais à l'oral."));
    intro.appendChild(el("div", "mga-rule",
      "Je ne rédige rien de moi-même. Je recopie les passages du wiki mot pour mot, avec le " +
      "lien de la page et le tableau quand il y en a un. Si le wiki ne le dit pas, je ne l'invente pas."));
    var samples = el("div", "mga-samples");
    SAMPLES.forEach(function (q) {
      var b = el("button", null, q);
      b.addEventListener("click", function () { demander(q); });
      samples.appendChild(b);
    });
    intro.appendChild(samples);
    log.appendChild(intro);
    panel.appendChild(log);

    var form = el("form", "mga-ask");
    champ = el("input");
    champ.type = "text";
    champ.placeholder = "Ta question…";
    champ.autocomplete = "off";
    champ.setAttribute("aria-label", "Ta question");
    var env = el("button", null, "Chercher");
    env.type = "submit";
    form.appendChild(champ);
    form.appendChild(env);
    form.addEventListener("submit", function (e) {
      e.preventDefault();
      demander(champ.value);
    });
    panel.appendChild(form);

    var foot = el("div", "mga-foot", "index rebâti depuis le wiki");
    panel.appendChild(foot);
    document.body.appendChild(panel);

    launch.addEventListener("click", ouvrir);
    bClose.addEventListener("click", fermer);
    bReset.addEventListener("click", function () {
      Array.prototype.slice.call(log.children).forEach(function (n) {
        if (n !== intro) n.remove();
      });
      intro.hidden = false;
      champ.value = "";
      champ.focus();
    });
    document.addEventListener("keydown", function (e) {
      if (e.key === "Escape" && !panel.hidden) fermer();
    });
    panel.__foot = foot;
  }

  function ouvrir() {
    panel.hidden = false;
    launch.hidden = true;
    precharger();
    setTimeout(function () { champ.focus(); }, 30);
  }
  function fermer() {
    panel.hidden = true;
    launch.hidden = false;
  }

  // L'index se bâtit au premier usage, pas au chargement de la page : la
  // navigation normale du wiki n'est donc jamais ralentie.
  function precharger() {
    if (moteur || chargement) return chargement;
    chargement = window.MicroguideIndexeur.charger(BASE).then(function (ix) {
      ix.glossaire = window.MICROGUIDE_GLOSSAIRE || {};
      ix.intentions = window.MICROGUIDE_INTENTIONS || {};
      moteur = new window.MicroguideMoteur(ix);
      if (panel.__foot) {
        panel.__foot.textContent = ix.pages.length + " pages · " + ix.sections.length + " sections";
      }
      return moteur;
    });
    return chargement;
  }

  function rendreSection(s) {
    var wrap = el("div", "mga-sec");
    wrap.appendChild(el("div", "mga-sect", s.titre));
    var box = el("div", "mga-quote");
    s.prose.forEach(function (p) { box.appendChild(el("p", null, p)); });
    if (s.puces.length) {
      var ul = el("ul");
      s.puces.forEach(function (p) { ul.appendChild(el("li", null, p)); });
      box.appendChild(ul);
    }
    wrap.appendChild(box);
    return wrap;
  }

  function rendreReponse(r) {
    var box = el("div", "mga-a");
    box.appendChild(el("p", "mga-lead" + (r.etat === "faible" ? " weak" : ""), r.intro));
    if (!r.blocs.length) {
      box.appendChild(el("div", "mga-none",
        "Aucune page du wiki ne traite de ça. Je préfère te le dire plutôt que de te donner " +
        "une réponse que je n'ai pas lue quelque part."));
      return box;
    }
    r.blocs.forEach(function (b) {
      var src = el("div", "mga-src");
      var h = el("div", "mga-srch");
      h.appendChild(el("span", "lbl", "Page"));
      var a = el("a", null, b.page);
      a.href = b.url;
      h.appendChild(a);
      src.appendChild(h);
      (b.images || []).forEach(function (im) {
        var fig = el("figure", "mga-fig");
        var img = document.createElement("img");
        img.src = im.url;
        img.alt = im.section + " — " + b.page;
        img.loading = "lazy";
        fig.appendChild(img);
        fig.appendChild(el("figcaption", null, "Tableau du wiki — " + im.section));
        src.appendChild(fig);
      });
      b.sections.forEach(function (s) { src.appendChild(rendreSection(s)); });
      box.appendChild(src);
    });
    return box;
  }

  function demander(q) {
    q = (q || "").trim();
    if (!q) return;
    intro.hidden = true;
    log.appendChild(el("div", "mga-q", q));
    var attente = el("p", "mga-lead", "Je cherche dans le wiki…");
    log.appendChild(attente);
    log.scrollTop = log.scrollHeight;
    champ.value = "";

    precharger().then(function (m) {
      attente.remove();
      log.appendChild(rendreReponse(m.repondre(q)));
      log.scrollTop = log.scrollHeight;
    })["catch"](function (e) {
      attente.remove();
      log.appendChild(el("div", "mga-none",
        "Je n'ai pas pu lire le wiki (" + (e && e.message ? e.message : "erreur") +
        "). Réessaie dans un moment."));
    });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", construire);
  } else {
    construire();
  }
})();

}
/* ====== FIN Assistant Microguide (essai) ====== */