// ============================================================
// bedside/sepsis.js
// SEPSIS — Phoenix criteria, febrile-infant rules, first-hour bundle.
// ============================================================

import { S } from './shared.js';

function showSepsis() {
  var wt = parseFloat(document.getElementById('sepsis-weight').value);
  var age = document.getElementById('sepsis-age').value;
  var el = document.getElementById('sepsis-result');
  var html = '';

  var ageLbl = { neonate: 'Neonate (0-28 d)', infant: 'Young infant (29 d - 3 mo)', child: 'Older child / adolescent' }[age];
  html += '<div style="padding:10px 14px;border-radius:8px;background:#fee2e2;border:1.5px solid #ef4444;margin-bottom:12px;"><strong style="color:#dc2626;">Sepsis approach — ' + ageLbl + (wt ? ', ' + wt + ' kg' : '') + '</strong></div>';

  // Definition (Phoenix 2024)
  html += '<h5 style="font-size:13px;font-weight:700;color:var(--g700);margin:0 0 6px;">Definition — Phoenix Sepsis Criteria (JAMA 2024)</h5>';
  html += '<div style="padding:10px;background:var(--g50);border-radius:6px;font-size:12px;line-height:1.55;margin-bottom:12px;">';
  html += '<strong>Sepsis</strong> = suspected or confirmed infection + Phoenix Score ≥2 (organ dysfunction across respiratory, cardiovascular, coagulation, neurological).<br>';
  html += '<strong>Septic shock</strong> = sepsis + cardiovascular dysfunction (vasoactive support, or ↑lactate ≥5, or ↓MAP for age).<br>';
  html += '<em style="color:var(--g500);">Previous SIRS-based criteria (Goldstein 2005) are now superseded. Still useful for quick clinical screening.</em>';
  html += '</div>';

  // Quick red flags
  html += '<h5 style="font-size:13px;font-weight:700;color:var(--g700);margin:10px 0 6px;">Red flags (recognize early)</h5>';
  html += '<div style="padding:10px;background:#fef2f2;border-radius:6px;font-size:12px;color:#991b1b;">Abnormal behavior / mentation • Fever + ill-appearance • Tachycardia out of proportion to fever • Prolonged cap refill (&gt;3 s) • Cold/mottled extremities • Weak pulses or wide pulse pressure (&quot;warm shock&quot;) • Hypotension is a <strong>LATE</strong> sign in children • Any immune compromise / indwelling line.</div>';

  // Age-specific approach
  html += '<h5 style="font-size:13px;font-weight:700;color:var(--g700);margin:14px 0 6px;">Evaluation &amp; empiric therapy — ' + ageLbl + '</h5>';
  if (age === 'neonate') {
    html += '<div style="padding:10px;background:var(--g50);border-radius:6px;font-size:12px;margin-bottom:10px;">';
    html += '<strong>Workup (full sepsis eval):</strong> CBC + diff, CRP, blood culture, UA + urine culture (cath), <strong>lumbar puncture</strong> (CSF + HSV PCR), CXR if respiratory sx. Consider procalcitonin. Rapid viral panel if available.<br>';
    html += '<strong>Early-onset (&lt;72 h):</strong> GBS, E. coli, Listeria. <strong>Late-onset (&gt;72 h):</strong> coag-neg staph, S. aureus, gram-negs, Candida.</div>';
    html += S.drugTable(
      S.drugRow('Ampicillin', wt ? S.dStr(wt, 100, 2000) : '50-100 mg/kg/dose', 'IV', 'q8-12h depending on age/weight. Covers GBS, Listeria, Enterococcus.') +
      S.drugRow('Gentamicin', wt ? S.dStr(wt, 4, 120) : '4-5 mg/kg/dose', 'IV', 'q24-48h. Monitor levels. Peak 5-12, trough &lt;1.') +
      S.drugRow('Cefotaxime (add)', wt ? S.dStr(wt, 50, 2000) : '50 mg/kg/dose', 'IV', 'If meningitis suspected or gram-neg concern. Ceftriaxone avoided in hyperbilirubinemia.') +
      S.drugRow('Acyclovir', wt ? S.dStr(wt, 20, 1200) : '20 mg/kg/dose', 'IV q8h', 'If HSV risk: maternal genital lesions, vesicles, seizures, CSF pleocytosis, hypothermia, hepatitis.')
    );
  } else if (age === 'infant') {
    html += '<div style="padding:10px;background:var(--g50);border-radius:6px;font-size:12px;margin-bottom:10px;">';
    html += '<strong>Workup:</strong> Use validated rules — PECARN, Aronson, Rochester, Step-by-Step (see below). Most warrant CBC + ANC, procalcitonin and/or CRP, blood culture, UA + urine culture. Many warrant LP + admission + empiric abx.<br>';
    html += '<strong>Coverage:</strong> GBS, E. coli, Listeria (up to ~6 wk), S. pneumoniae, N. meningitidis, H. influenzae, Salmonella.</div>';

    // Febrile-infant rules — collapsible details
    html += '<details style="margin-bottom:10px;border:1px solid var(--g200);border-radius:8px;padding:8px 10px;background:white;"><summary style="cursor:pointer;font-weight:600;font-size:13px;color:var(--blue-dark);"><i class="fas fa-list-check"></i> Validated febrile-infant rules (click to expand)</summary>';
    html += '<div style="margin-top:10px;font-size:12px;line-height:1.55;">';

    // PECARN 2019
    html += '<div style="padding:10px 12px;background:#eff6ff;border-radius:6px;margin-bottom:8px;border-left:4px solid #3b82f6;">';
    html += '<div style="font-weight:700;color:#1e40af;margin-bottom:4px;">PECARN febrile infant rule (Kuppermann et al., JAMA Pediatrics 2019)</div>';
    html += '<strong>Age:</strong> 29-60 days, well-appearing, febrile. <strong>Low-risk if ALL:</strong><br>';
    html += '&nbsp;&bull; Normal UA (no LE, no nitrite, &lt;5 WBC/hpf)<br>';
    html += '&nbsp;&bull; ANC ≤4,090 /&mu;L<br>';
    html += '&nbsp;&bull; Procalcitonin ≤0.5 ng/mL (if procal unavailable: use CRP &le;20 mg/L as proxy)<br>';
    html += '<strong>Low-risk</strong> → may defer LP/abx, observe, close follow-up. <strong>Not low-risk</strong> → full workup + empiric abx.';
    html += '</div>';

    // Aronson 2019
    html += '<div style="padding:10px 12px;background:#f0fdf4;border-radius:6px;margin-bottom:8px;border-left:4px solid #16a34a;">';
    html += '<div style="font-weight:700;color:#166534;margin-bottom:4px;">Aronson rule (Aronson et al., PEDIATRICS 2019)</div>';
    html += '<strong>Age:</strong> 8-60 days, febrile ≥38°C. Point-based score for invasive bacterial infection (IBI):<br>';
    html += '&nbsp;&bull; Age 22-28 days: <strong>+1</strong><br>';
    html += '&nbsp;&bull; Max temperature ≥38.5°C: <strong>+2</strong><br>';
    html += '&nbsp;&bull; ANC ≥5,185 /&mu;L: <strong>+2</strong><br>';
    html += '&nbsp;&bull; Abnormal UA: <strong>+3</strong><br>';
    html += '<strong>Score 0-1</strong> → low risk. <strong>≥2</strong> → consider full workup + abx. Higher scores → higher IBI risk.';
    html += '</div>';

    // Rochester
    html += '<div style="padding:10px 12px;background:#fffbeb;border-radius:6px;margin-bottom:8px;border-left:4px solid #f59e0b;">';
    html += '<div style="font-weight:700;color:#92400e;margin-bottom:4px;">Rochester criteria (Jaskiewicz et al., Pediatrics 1994)</div>';
    html += '<strong>Age:</strong> 0-60 days, febrile. <strong>Low-risk if ALL:</strong><br>';
    html += '&nbsp;&bull; Previously healthy (term, no perinatal complications, no prior abx/hospitalization)<br>';
    html += '&nbsp;&bull; Well-appearing, no focal infection (not skin/bone/joint/soft tissue)<br>';
    html += '&nbsp;&bull; WBC 5,000-15,000 /&mu;L and absolute band count ≤1,500 /&mu;L<br>';
    html += '&nbsp;&bull; UA ≤10 WBC/hpf<br>';
    html += '&nbsp;&bull; If diarrhea: stool ≤5 WBC/hpf<br>';
    html += '<strong>Low-risk</strong> → observation without abx possible (NPV &gt;98%). Does not include procal.';
    html += '</div>';

    // Step-by-Step
    html += '<div style="padding:10px 12px;background:#fdf4ff;border-radius:6px;margin-bottom:4px;border-left:4px solid #a855f7;">';
    html += '<div style="font-weight:700;color:#6b21a8;margin-bottom:4px;">Step-by-Step (Gomez et al., Pediatrics 2016 — European)</div>';
    html += '<strong>Age:</strong> ≤90 days, febrile. Sequential triage; stop at first positive:<br>';
    html += '&nbsp;<strong>1.</strong> Ill-appearing? → <em>high risk</em><br>';
    html += '&nbsp;<strong>2.</strong> Age ≤21 days? → <em>high risk</em><br>';
    html += '&nbsp;<strong>3.</strong> Leukocyturia (UA abnormal)? → <em>high risk</em><br>';
    html += '&nbsp;<strong>4.</strong> Procalcitonin ≥0.5 ng/mL? → <em>high risk</em><br>';
    html += '&nbsp;<strong>5.</strong> CRP &gt;20 mg/L AND/OR ANC &gt;10,000 /&mu;L? → <em>intermediate</em><br>';
    html += '&nbsp;<strong>6.</strong> Otherwise → <em>low risk</em>';
    html += '<div style="margin-top:4px;color:var(--g500);">Highest sensitivity for IBI among these rules when procal available.</div>';
    html += '</div>';

    html += '<div style="margin-top:8px;padding:8px 10px;background:var(--g50);border-radius:6px;font-size:11px;color:var(--g600);"><strong>Practical note:</strong> AAP 2021 Clinical Practice Guideline on the well-appearing febrile infant 8-60 days synthesizes these — ages 8-21 d full workup regardless, 22-28 d inflammatory markers guide LP, 29-60 d UA + markers guide LP/abx. Defer to your local institutional pathway if available.</div>';
    html += '</div></details>';

    html += S.drugTable(
      S.drugRow('Ceftriaxone', wt ? S.dStr(wt, 75, 2000) : '50-75 mg/kg/dose', 'IV / IM', 'q24h (or 100 mg/kg/day divided q12h for meningitis). <strong>Avoid &lt;28 days</strong> if hyperbilirubinemia.') +
      S.drugRow('Ampicillin', wt ? S.dStr(wt, 100, 2000) : '50-100 mg/kg/dose', 'IV', 'If &lt;6 wks: add for Listeria coverage.') +
      S.drugRow('Vancomycin', wt ? S.dStr(wt, 15, 1000) : '15 mg/kg/dose', 'IV', 'If severe / MRSA risk / meningitis. Target trough 15-20.') +
      S.drugRow('Acyclovir', wt ? S.dStr(wt, 20, 1200) : '20 mg/kg/dose', 'IV q8h', '&lt;6 weeks with suspicion of HSV.')
    );
  } else {
    html += '<div style="padding:10px;background:var(--g50);border-radius:6px;font-size:12px;margin-bottom:10px;">';
    html += '<strong>Recognition:</strong> Phoenix score or clinical concern + suspected infection. <strong>Workup:</strong> CBC, CRP, procalcitonin, blood cx (+ site-specific cx), lactate, blood gas, glucose, electrolytes, coags, LP if CNS concern. Source-directed imaging.<br>';
    html += '<strong>Common sources:</strong> respiratory, UTI, CNS, skin/soft tissue, intra-abdominal, bone/joint, indwelling device.</div>';
    html += S.drugTable(
      S.drugRow('Ceftriaxone', wt ? S.dStr(wt, 50, 2000) : '50 mg/kg/dose', 'IV', 'q24h (or 100 mg/kg/day divided for meningitis).') +
      S.drugRow('Vancomycin', wt ? S.dStr(wt, 15, 1000) : '15 mg/kg/dose', 'IV', 'q6h. If severe, indwelling line, or MRSA prevalence &gt;10%.') +
      S.drugRow('Piperacillin-tazobactam', wt ? S.dStr(wt, 100, 4500) : '80-100 mg/kg/dose', 'IV', 'If intra-abdominal / neutropenic.') +
      S.drugRow('Clindamycin', wt ? S.dStr(wt, 10, 900) : '10-13 mg/kg/dose', 'IV', 'Adjunct for toxic shock syndrome (toxin suppression).') +
      S.drugRow('Acyclovir', wt ? S.dStr(wt, 20, 1200) : '10-20 mg/kg/dose', 'IV q8h', 'If HSV CNS concern.')
    );
  }

  // First-hour bundle
  html += '<h5 style="font-size:13px;font-weight:700;color:var(--g700);margin:14px 0 6px;">First-hour bundle (SSC Peds 2020)</h5>';
  html += S.stepBox('#3b82f6', '0-5 min — Recognize', 'Screen for sepsis; sepsis huddle / activation. Assess ABCs. O2 to SpO2 &gt;94%. Warm patient.');
  html += S.stepBox('#8b5cf6', '5-15 min — Access &amp; labs', 'Two IVs or IO. Draw: blood cx (ideally before abx), lactate, CBC, CMP, coags, blood gas, glucose. UA + culture. Source-specific cultures.');
  html += S.stepBox('#f59e0b', '15-30 min — Fluids', (wt ? 'NS or LR <strong>' + S.d(wt, 20) + ' mL</strong> bolus over 5-10 min (20 mL/kg). ' : 'NS/LR 10-20 mL/kg bolus over 5-10 min. ') + 'Reassess after each bolus: HR, perfusion, lung sounds, liver size. Repeat up to 40-60 mL/kg; stop if crackles or hepatomegaly.');
  html += S.stepBox('#10b981', '30-60 min — Antibiotics + reassess', 'Broad-spectrum empiric abx within 1 hour (ideally 3 hr in sepsis, &le;1 hr in septic shock). Recheck lactate, perfusion.');
  html += S.stepBox('#ef4444', '&gt;60 min — Fluid-refractory shock', 'Start vasoactive (<strong>epinephrine 0.05-0.3 mcg/kg/min</strong> for cold shock or <strong>norepinephrine 0.05-0.3 mcg/kg/min</strong> for warm shock). Consider central/IO access. Stress-dose hydrocortisone ' + (wt ? '<strong>' + S.d(wt, 2, 100) + ' mg</strong> IV <span style="color:var(--g500);font-size:11px;">(2 mg/kg, max 100 mg)</span>' : '2 mg/kg IV (max 100 mg)') + ' if catecholamine-resistant. Consider ICU transfer.');

  // Key targets
  html += '<h5 style="font-size:13px;font-weight:700;color:var(--g700);margin:14px 0 6px;">Resuscitation targets</h5>';
  html += '<div style="padding:10px;background:var(--g50);border-radius:6px;font-size:12px;">Normal mentation • Cap refill ≤2 s • Warm extremities • Strong peripheral pulses • UOP ≥1 mL/kg/hr • MAP ≥5th %ile for age (&gt;65 mmHg adolescent) • SpO2 ≥94% • Lactate trending down.</div>';
  html += S.ref('Phoenix Sepsis Criteria (Schlapbach et al., JAMA 2024). Surviving Sepsis Campaign Pediatric 2020. AAP pediatric sepsis guidance.');
  el.innerHTML = html;
}

export function init() {
  document.addEventListener('click', function(e) {
    if (e.target.id === 'btn-sepsis-show' || e.target.closest('#btn-sepsis-show')) showSepsis();
  });
}
