// ============================================================
// PHYSICAL EXAM GUIDE — step-by-step OSCE reference + report generator
// ============================================================
// Sources for the exam content:
//   - Bates' Guide to Physical Examination, 13th edition (technique)
//   - Nelson Textbook of Pediatrics, 22nd edition (age-specific content)
//   - Hutchison's Clinical Methods, 25th edition (systematic approach)
//   - Developmental reflex timing: Fenichel Clinical Pediatric Neurology, 8th ed
//
// Data model:
//   PE_DATA[ageGroup][system] = { overview, components: [{ name, steps: [{label, method, normal}], abnormalHints }] }
// Each step has its own Normal / Abnormal / Skip toggle so the physician
// ticks the exam off step-by-step and flags specific abnormal findings.
// Report generation (POST /api/generate-pe-narrative) receives the flat
// step array and produces a Technique + Findings narrative.
// ============================================================

(function () {

  // ────────────────────────────────────────────────────────────
  // GRADING SCALES — universal reference shown at top of each system
  // ────────────────────────────────────────────────────────────
  var SCALES = {
    mrc: {
      title: 'MRC strength grade (0–5)',
      icon: 'fa-hand-fist',
      rows: [
        ['5', 'Normal power — holds against full resistance'],
        ['4', 'Reduced — moves against gravity + some resistance'],
        ['3', 'Moves against gravity only (no added resistance)'],
        ['2', 'Full range with gravity eliminated (horizontal plane)'],
        ['1', 'Flicker / trace contraction, no joint movement'],
        ['0', 'No contraction']
      ]
    },
    dtr: {
      title: 'Deep-tendon reflex grade (0–4+)',
      icon: 'fa-circle-dot',
      rows: [
        ['0',  'Absent'],
        ['1+', 'Hypoactive — trace, only with reinforcement'],
        ['2+', 'Normal'],
        ['3+', 'Brisk — may still be normal in anxious patients'],
        ['4+', 'Hyperactive with sustained clonus — always abnormal']
      ]
    },
    plantar: {
      title: 'Plantar response (Babinski)',
      icon: 'fa-shoe-prints',
      rows: [
        ['Down-going', 'Normal in anyone ≥ 2 years'],
        ['Up-going',   'Normal < 2 years; abnormal after — UMN lesion'],
        ['Asymmetric', 'Always abnormal at any age']
      ]
    },
    beighton: {
      title: 'Beighton hypermobility score (0–9)',
      icon: 'fa-hands',
      rows: [
        ['≤ 3', 'Normal flexibility'],
        ['4',   'Borderline — consider in context'],
        ['≥ 5', 'Hypermobility spectrum; screen for hEDS if other features present']
      ]
    },
    atr: {
      title: 'Scoliometer — angle of trunk rotation',
      icon: 'fa-ruler',
      rows: [
        ['< 5°',  'Normal, no follow-up'],
        ['5–6°',  'Borderline — re-check at each visit'],
        ['≥ 7°',  'Refer for PA/lateral spine x-ray + orthopedic evaluation']
      ]
    },
    rr: {
      title: 'Respiratory rate — upper limit by age (awake)',
      icon: 'fa-lungs',
      rows: [
        ['Newborn',       '≤ 60 /min'],
        ['< 2 months',    '≤ 60 /min (WHO tachypnea cutoff)'],
        ['2–12 months',   '≤ 50 /min (WHO tachypnea cutoff)'],
        ['1–5 years',     '≤ 40 /min (WHO tachypnea cutoff)'],
        ['6–11 years',    '≤ 30 /min'],
        ['≥ 12 years',    '≤ 20 /min (adult pattern)']
      ]
    },
    spo2: {
      title: 'Pulse oximetry (SpO₂) — at room air',
      icon: 'fa-heart-pulse',
      rows: [
        ['≥ 95%',   'Normal'],
        ['92–94%',  'Mild hypoxemia — investigate cause'],
        ['< 92%',   'Moderate hypoxemia — supplemental O₂'],
        ['< 88%',   'Severe — urgent intervention; target ≥ 90% acutely']
      ]
    },
    silverman: {
      title: 'Silverman–Andersen retraction score (neonatal, 0–10)',
      icon: 'fa-baby',
      rows: [
        ['0',     'No respiratory distress'],
        ['1–3',   'Mild — close observation'],
        ['4–6',   'Moderate distress — consider CPAP / support'],
        ['7–10',  'Severe — imminent respiratory failure, intubate']
      ]
    },
    westley: {
      title: 'Westley croup severity score',
      icon: 'fa-stethoscope',
      rows: [
        ['≤ 2',    'Mild — home management, cool mist, oral dexamethasone'],
        ['3–5',    'Moderate — nebulised epinephrine + dexamethasone'],
        ['6–11',   'Severe — admit, continuous monitoring'],
        ['≥ 12',   'Impending respiratory failure — ICU / airway management']
      ]
    },
    murmurGrade: {
      title: 'Heart-murmur grading (Levine 1–6)',
      icon: 'fa-wave-square',
      rows: [
        ['1/6',   'Very faint — heard only with concentration'],
        ['2/6',   'Soft but readily heard'],
        ['3/6',   'Moderately loud, no thrill'],
        ['4/6',   'Loud WITH a palpable thrill'],
        ['5/6',   'Very loud; audible with stethoscope just off the chest'],
        ['6/6',   'Audible without the stethoscope touching the chest']
      ]
    },
    pulseAmp: {
      title: 'Pulse amplitude grade (0–4)',
      icon: 'fa-heart-pulse',
      rows: [
        ['0',   'Absent'],
        ['1+',  'Diminished, thready'],
        ['2+',  'Normal'],
        ['3+',  'Bounding'],
        ['4+',  'Bounding with visible pulsation (e.g., aortic regurgitation)']
      ]
    },
    capRefill: {
      title: 'Capillary refill time',
      icon: 'fa-hand',
      rows: [
        ['< 2 sec',  'Normal'],
        ['2–3 sec',  'Borderline — consider hydration / perfusion'],
        ['≥ 3 sec',  'Delayed — dehydration, shock, low cardiac output']
      ]
    }
  };
  // Which scales are relevant per system
  var SYSTEM_SCALES = {
    msk:   ['atr', 'beighton'],
    neuro: ['mrc', 'dtr', 'plantar'],
    resp:  ['rr', 'spo2', 'silverman', 'westley'],
    cv:    ['murmurGrade', 'pulseAmp', 'capRefill']
  };

  // ────────────────────────────────────────────────────────────
  // APTM DIAGRAM — the 5 classic auscultation points
  // ────────────────────────────────────────────────────────────
  // Inline SVG showing: Aortic, Pulmonic, Erb's, Tricuspid, Mitral.
  // Rendered at the top of the cardiovascular system view.
  // Patient faces viewer — viewer's LEFT = patient's right.
  var APTM_SVG =
    '<svg viewBox="0 0 340 340" xmlns="http://www.w3.org/2000/svg" style="max-width:360px;width:100%;height:auto;display:block;margin:0 auto;" aria-label="Cardiac auscultation points — Aortic, Pulmonic, Erb\'s point, Tricuspid, Mitral">' +
      // Chest outline
      '<path d="M60,60 Q60,30 170,25 Q280,30 280,60 L280,290 Q280,320 220,325 L120,325 Q60,320 60,290 Z" fill="#f9fafb" stroke="#d1d5db" stroke-width="2"/>' +
      // Clavicles
      '<path d="M80,55 Q110,42 160,58" stroke="#cbd5e1" stroke-width="5" fill="none" stroke-linecap="round"/>' +
      '<path d="M260,55 Q230,42 180,58" stroke="#cbd5e1" stroke-width="5" fill="none" stroke-linecap="round"/>' +
      // Sternum
      '<rect x="161" y="60" width="18" height="170" fill="#e2e8f0" stroke="#cbd5e1"/>' +
      // ICS level dashed lines
      '<line x1="80" y1="90"  x2="260" y2="90"  stroke="#e2e8f0" stroke-dasharray="3,3"/>' +
      '<line x1="80" y1="120" x2="260" y2="120" stroke="#e2e8f0" stroke-dasharray="3,3"/>' +
      '<line x1="80" y1="150" x2="260" y2="150" stroke="#e2e8f0" stroke-dasharray="3,3"/>' +
      '<line x1="80" y1="180" x2="260" y2="180" stroke="#e2e8f0" stroke-dasharray="3,3"/>' +
      // Midclavicular line (left — patient\'s, viewer\'s right)
      '<line x1="230" y1="55" x2="230" y2="310" stroke="#cbd5e1" stroke-dasharray="2,5"/>' +
      // ICS labels
      '<text x="74" y="93"  font-size="9" fill="#94a3b8" text-anchor="end">ICS 2</text>' +
      '<text x="74" y="123" font-size="9" fill="#94a3b8" text-anchor="end">ICS 3</text>' +
      '<text x="74" y="153" font-size="9" fill="#94a3b8" text-anchor="end">ICS 4</text>' +
      '<text x="74" y="183" font-size="9" fill="#94a3b8" text-anchor="end">ICS 5</text>' +
      '<text x="266" y="54" font-size="9" fill="#94a3b8" text-anchor="start">Mid-clavicular</text>' +
      // Patient labels
      '<text x="90"  y="42" font-size="11" fill="#64748b" font-weight="600">Patient\'s RIGHT</text>' +
      '<text x="250" y="42" font-size="11" fill="#64748b" font-weight="600" text-anchor="end">Patient\'s LEFT</text>' +
      // Aortic — 2nd ICS right sternal border (viewer\'s left)
      '<circle cx="145" cy="90" r="15" fill="#dc2626" stroke="#7f1d1d" stroke-width="2"/>' +
      '<text x="145" y="95" font-size="15" font-weight="700" fill="white" text-anchor="middle">A</text>' +
      // Pulmonic — 2nd ICS left sternal border (viewer\'s right)
      '<circle cx="195" cy="90" r="15" fill="#2563eb" stroke="#1e3a8a" stroke-width="2"/>' +
      '<text x="195" y="95" font-size="15" font-weight="700" fill="white" text-anchor="middle">P</text>' +
      // Erb\'s point — 3rd ICS left sternal border
      '<circle cx="195" cy="120" r="13" fill="#059669" stroke="#064e3b" stroke-width="2"/>' +
      '<text x="195" y="125" font-size="13" font-weight="700" fill="white" text-anchor="middle">E</text>' +
      // Tricuspid — 4th ICS left sternal border
      '<circle cx="195" cy="175" r="15" fill="#d97706" stroke="#78350f" stroke-width="2"/>' +
      '<text x="195" y="180" font-size="15" font-weight="700" fill="white" text-anchor="middle">T</text>' +
      // Mitral — 5th ICS midclavicular (apex)
      '<circle cx="230" cy="195" r="15" fill="#7c3aed" stroke="#4c1d95" stroke-width="2"/>' +
      '<text x="230" y="200" font-size="15" font-weight="700" fill="white" text-anchor="middle">M</text>' +
    '</svg>';

  var APTM_LEGEND = [
    { letter: 'A', color: '#dc2626', title: 'Aortic area',      location: '2nd ICS, right sternal border',       listen: 'S2 (aortic component), aortic stenosis, aortic regurgitation' },
    { letter: 'P', color: '#2563eb', title: 'Pulmonic area',    location: '2nd ICS, left sternal border',        listen: 'S2 (pulmonic component), pulmonic stenosis, PDA, physiologic split of S2',
      innocent: 'Pulmonary flow murmur (children, adolescents) — upper left sternal border' },
    { letter: 'E', color: '#059669', title: 'Erb\'s point',     location: '3rd ICS, left sternal border',        listen: 'Aortic regurgitation (best here), transitional zone murmurs',
      innocent: 'Still\'s murmur classically radiates to Erb\'s / LLSB' },
    { letter: 'T', color: '#d97706', title: 'Tricuspid area',   location: '4th–5th ICS, lower left sternal border', listen: 'Tricuspid regurgitation, VSD, S3/S4, holosystolic murmurs',
      innocent: 'Still\'s murmur — vibratory, musical, age 3–7 y (loudest between LLSB and apex)' },
    { letter: 'M', color: '#7c3aed', title: 'Mitral area (apex)', location: '5th ICS, mid-clavicular line',      listen: 'S1, mitral regurgitation, mitral stenosis (with bell, left-lateral decubitus)' }
  ];

  // ────────────────────────────────────────────────────────────
  // INNOCENT MURMURS — the classic benign murmurs of childhood
  // ────────────────────────────────────────────────────────────
  var INNOCENT_MURMURS = [
    { name: 'Still\'s (vibratory) murmur',
      age: '3–7 y (most common in children)',
      location: 'LLSB, radiating to apex',
      character: 'Low-frequency vibratory / musical systolic, grade 2–3/6, mid-systolic, "twanging-string" quality',
      confirm: 'Louder supine, softer or disappears on standing or Valsalva. No radiation to neck/back. Normal S2.' },
    { name: 'Pulmonary flow murmur',
      age: 'School-age and adolescents, thin chest',
      location: 'Upper left sternal border (2nd–3rd ICS)',
      character: 'Soft blowing early systolic ejection, grade 1–2/6, higher-pitched',
      confirm: 'No ejection click. Physiologic split of S2. Louder supine, softer on standing. No radiation.' },
    { name: 'Venous hum',
      age: 'Ages 3–8, disappears by adolescence',
      location: 'Supraclavicular or infraclavicular area, usually right',
      character: 'Soft continuous hum, louder in diastole. Only innocent continuous murmur.',
      confirm: 'Disappears when supine OR when jugular vein is gently compressed (key maneuver). Turning head to opposite side also alters it.' },
    { name: 'Carotid bruit / supraclavicular bruit',
      age: 'Children and adolescents',
      location: 'Supraclavicular fossa, right > left; may radiate to carotid',
      character: 'Brief early systolic, grade 2–3/6, higher-pitched than Still\'s',
      confirm: 'Softer or disappears with hyperextension of the shoulders. Normal cardiac exam otherwise. No radiation below the clavicles.' },
    { name: 'Peripheral pulmonary stenosis (PPS, neonatal)',
      age: 'Newborns and infants < 6–12 months',
      location: 'Upper LSB, radiates to BOTH axillae and the back',
      character: 'Soft systolic ejection murmur, grade 1–2/6',
      confirm: 'Typical age + radiation to back/axillae. Resolves by age 1 as branch pulmonary arteries grow. Persistence or louder grade warrants echo.' }
  ];

  // ────────────────────────────────────────────────────────────
  // RESPIRATORY SOUNDS LIBRARY
  // ────────────────────────────────────────────────────────────
  // Displayed as a dedicated card at the top of the Respiratory system.
  // src = real recording path served from /public/audio/respiratory/.
  var RESP_SOUNDS = [
    { key: 'normal',         src: '/audio/respiratory/normal-vesicular.ogg', title: 'Normal vesicular breath sounds',
      where: 'Peripheral lung fields',
      features: 'Soft, rustling. Inspiration louder and longer than expiration.',
      clinical: 'Baseline — deviation elsewhere is what you listen for.' },
    { key: 'wheeze',         src: '/audio/respiratory/wheeze.ogg',      title: 'Wheeze',
      where: 'Diffuse in asthma; localised in foreign body',
      features: 'Continuous, high-pitched, musical. Usually expiratory; biphasic if severe.',
      clinical: 'Lower-airway narrowing — asthma, bronchiolitis, foreign body, bronchomalacia. Silent chest in severe asthma is an ominous sign.' },
    { key: 'stridor',        src: '/audio/respiratory/stridor.ogg',     title: 'Stridor',
      where: 'Louder over neck than chest — upper airway',
      features: 'Continuous, high-pitched, harsh. Classically inspiratory (extrathoracic obstruction); biphasic if fixed.',
      clinical: 'Croup, epiglottitis, foreign body, laryngomalacia (infant). Distinguish from wheeze by auscultating the neck — stridor is loudest there.' },
    { key: 'finecrackles',   src: '/audio/respiratory/crackles-fine.ogg',   title: 'Fine (end-inspiratory) crackles',
      where: 'Bibasilar in pulmonary edema/fibrosis; focal in pneumonia',
      features: 'Discontinuous, brief, high-pitched. "Velcro" quality. Late inspiratory, do NOT clear with cough.',
      clinical: 'Alveolar opening — pulmonary fibrosis, pulmonary edema, early pneumonia, atelectasis.' },
    { key: 'coarsecrackles', src: '/audio/respiratory/crackles-coarse.ogg', title: 'Coarse crackles',
      where: 'Lower lobes; either side',
      features: 'Discontinuous, longer and louder than fine crackles. Lower-pitched. Can be early or late inspiratory; often clear partly with cough.',
      clinical: 'Secretions in larger airways — bronchitis, later pneumonia, bronchiectasis, aspiration.' },
    { key: 'rhonchi',        src: '/audio/respiratory/rhonchi.ogg',    title: 'Rhonchi',
      where: 'Central or anywhere with airway secretions',
      features: 'Continuous, low-pitched, snore-like. Typically expiratory. Clear or change with cough.',
      clinical: 'Large-airway secretions — bronchitis, pneumonia with large-airway involvement, cystic fibrosis, bronchiectasis.' },
    { key: 'pleuralrub',     src: '/audio/respiratory/pleural-rub.ogg', title: 'Pleural friction rub',
      where: 'Focal, often lateral or posterior lower chest',
      features: 'Grating, creaky — "leather on leather". Biphasic (heard in inspiration and expiration). Does NOT clear with cough.',
      clinical: 'Pleural inflammation — pleuritis, pulmonary embolism, pneumonia with pleural involvement, viral pleurisy.' }
  ];

  // ────────────────────────────────────────────────────────────
  // CARDIAC SOUNDS LIBRARY — real recordings from Wikimedia Commons
  // ────────────────────────────────────────────────────────────
  var CARDIAC_SOUNDS = [
    { key: 'normal', src: '/audio/cardiac/normal.ogg', title: 'Normal heart sounds (S1, S2)',
      where: 'All four classic auscultation points', rate: '~61 bpm reference',
      features: '"lub-dub": S1 (closure of mitral + tricuspid) louder at apex; S2 (closure of aortic + pulmonic) louder at base. Physiologic S2 split on inspiration.',
      clinical: 'Reference for rhythm, rate, and the normal S1–S2 interval. Listen for what\'s changed — not just what\'s added.' },
    { key: 'infant-normal', src: '/audio/cardiac/infant-normal.ogg', title: 'Infant normal heart sounds',
      where: 'Infant chest — rate will be higher than adult', rate: 'Pediatric reference (120–160 bpm range)',
      features: 'Same S1–S2 pattern, faster rate. Short diastole makes murmurs easier to miss — careful auscultation needed.',
      clinical: 'Reference for neonatal/infant rhythm. Any murmur in the first 72 h should prompt pre/postductal sat screening.' },
    { key: 'vsd', src: '/audio/cardiac/vsd.wav', title: 'Ventricular septal defect (VSD)',
      where: 'Lower left sternal border (4th ICS)',
      features: 'Harsh, blowing, holosystolic (pansystolic) murmur — plateau shape through all of systole. Often accompanied by a thrill if large.',
      clinical: 'Most common congenital heart defect. Small VSD: loud murmur, usually asymptomatic, may close spontaneously. Large VSD: softer murmur (less pressure gradient) but signs of heart failure, pulmonary hypertension.' },
    { key: 'mvp', src: '/audio/cardiac/mitral-prolapse.wav', title: 'Mitral valve prolapse (MVP) — click + late systolic murmur',
      where: 'Apex (5th ICS, mid-clavicular line)',
      features: 'Mid-systolic click followed by a late-systolic crescendo murmur. Timing of click changes with maneuvers: earlier with standing or Valsalva, later with squatting.',
      clinical: 'Often benign, especially in thin young women. Features suggesting need for echo: thickened/redundant leaflets, associated MR, symptoms (palpitations, chest pain), arrhythmias.' },
    { key: 'stills', src: '/audio/cardiac/stills-murmur.ogg', title: 'Still\'s murmur (innocent)',
      where: 'LLSB, radiating to apex', rate: 'Classic age 3–7 y (this recording is a toddler)',
      features: 'Low-frequency vibratory / musical systolic, grade 2–3/6, mid-systolic, "twanging-string" quality.',
      clinical: 'The most common innocent murmur of childhood. Louder supine, softer or disappears on standing or Valsalva. Normal S2. No radiation to neck or back. No workup needed when classic.' },
    { key: 'functional', src: '/audio/cardiac/functional-murmur.wav', title: 'Functional (innocent) murmur — adult female',
      where: 'Left sternal border, soft systolic',
      features: 'Soft systolic murmur in a structurally normal heart — often from increased cardiac output, thin chest wall, anemia, hyperthyroidism, or pregnancy.',
      clinical: 'Benign if it meets the 7 S criteria. Investigate if loud (≥3/6), holosystolic, diastolic, radiating, or with thrill / symptoms.' }
  ];

  // ────────────────────────────────────────────────────────────
  // DATA
  // ────────────────────────────────────────────────────────────
  var PE_DATA = {

    newborn: {
      label: 'Newborn (0–28 days)',
      msk: {
        overview: 'Exam done warm, quiet, undressed. Focus: birth injury, DDH, congenital anomaly. All steps symmetric.',
        components: [
          { name: 'Resting posture', steps: [
            { label: 'Observe posture', method: 'Place supine and undisturbed for 30s', normal: 'Symmetric flexion at hips, knees, elbows' },
            { label: 'Hand position', method: 'Inspect resting hands', normal: 'Loosely fisted; opens intermittently' },
            { label: 'Symmetry', method: 'Compare left vs right side at rest', normal: 'Mirror-image posture' }
          ], abnormalHints: ['Frog-leg (hypotonia)', 'Asymmetric arm (brachial plexus/clavicle fx)', 'Opisthotonos (CNS)', 'Persistent fisting with thumb in palm'] },

          { name: 'Clavicles', steps: [
            { label: 'Palpate right clavicle', method: 'Trace from sternoclavicular joint to acromion with index finger', normal: 'Smooth, continuous, no step-off' },
            { label: 'Palpate left clavicle', method: 'Same technique on left side', normal: 'Smooth, continuous' },
            { label: 'Crepitus check', method: 'Light pressure along length of clavicle while gently abducting arm', normal: 'No crepitus, no pain response' }
          ], abnormalHints: ['Palpable step-off or callus (fracture — LGA, shoulder dystocia)', 'Asymmetric Moro on affected side'] },

          { name: 'Hips — DDH screen', steps: [
            { label: 'Thigh/gluteal folds', method: 'Undress completely; compare skin-fold symmetry', normal: 'Symmetric thigh and gluteal folds' },
            { label: 'Abduction', method: 'Flex hips 90°, abduct simultaneously', normal: 'Both hips abduct to ≥75° symmetrically' },
            { label: 'Barlow maneuver', method: 'Thumb on medial thigh, flex hip 90°, adduct, apply gentle posterior pressure', normal: 'No clunk or movement felt (negative)' },
            { label: 'Ortolani maneuver', method: 'From Barlow position: abduct and lift with fingers on greater trochanter', normal: 'No clunk as hip returns (negative)' },
            { label: 'Galeazzi sign', method: 'Knees flexed together with feet on table; compare knee heights', normal: 'Knees level — no leg-length discrepancy' }
          ], abnormalHints: ['Palpable Ortolani clunk (dislocated, reducible)', 'Barlow clunk (dislocatable)', 'Limited abduction', 'Positive Galeazzi (shortened femur)'] },

          { name: 'Spine and back', steps: [
            { label: 'Position prone', method: 'Turn infant prone, support chest', normal: 'Tolerates position, lifts head briefly' },
            { label: 'Palpate midline', method: 'Run finger from C-spine to coccyx', normal: 'Straight midline, no step-offs or gaps' },
            { label: 'Sacral inspection', method: 'Inspect sacral dimple if present; measure depth, distance from anus', normal: 'No dimple, or dimple <5mm deep and <2.5cm from anus' },
            { label: 'Cutaneous markers', method: 'Inspect midline skin from neck to coccyx', normal: 'No hair tuft, hemangioma, lipoma, or sinus tract' }
          ], abnormalHints: ['Deep sacral dimple (>5mm) or >2.5cm from anus — imaging', 'Hair tuft, hemangioma, lipoma (occult dysraphism)', 'Palpable defect'] },

          { name: 'Upper extremities', steps: [
            { label: 'Spontaneous movement', method: 'Observe both arms for 30s', normal: 'Symmetric antigravity movement' },
            { label: 'Digits', method: 'Count and inspect fingers both hands', normal: '5 digits each, no webbing or duplication' },
            { label: 'Palmar creases', method: 'Inspect palmar creases', normal: 'Normal triradiate creases' }
          ], abnormalHints: ['Erb/Klumpke palsy (paucity of movement)', 'Polydactyly, syndactyly', 'Single transverse (simian) palmar crease'] },

          { name: 'Lower extremities / feet', steps: [
            { label: 'Hip and knee range', method: 'Gently flex, extend, internally/externally rotate each', normal: 'Full symmetric range, no contracture' },
            { label: 'Foot alignment', method: 'Inspect resting foot position', normal: 'Midline or mildly adducted forefoot' },
            { label: 'Passive correction', method: 'Gently attempt to bring foot to neutral', normal: 'Fully correctable to neutral' },
            { label: 'Stroke test', method: 'Stroke lateral border of foot', normal: 'Foot dorsiflexes and everts reflexively' }
          ], abnormalHints: ['Rigid clubfoot (non-correctable talipes equinovarus)', 'Fixed metatarsus adductus', 'Rocker-bottom foot (trisomy 18)', 'Calcaneovalgus'] }
        ]
      },
      neuro: {
        overview: 'Primitive reflexes present and symmetric. Tone assessed passively and actively. Full exam 3–5 min on a quiet, fed infant.',
        components: [
          { name: 'Alertness and behavior', steps: [
            { label: 'State cycling', method: 'Observe over 1–2 min for alert periods', normal: 'Alert periods with spontaneous eye opening' },
            { label: 'Response to voice', method: 'Speak softly near ear', normal: 'Quiets to voice or turns toward sound' },
            { label: 'Consolability', method: 'If crying, attempt to soothe with swaddling or voice', normal: 'Consolable within 1–2 min' }
          ], abnormalHints: ['Lethargy', 'Jitteriness not stopped by passive flexion', 'Irritability unrelieved by feeding'] },

          { name: 'Cranial nerves', steps: [
            { label: 'CN II — pupil response', method: 'Shine light in each eye', normal: 'Pupils equal, reactive to light, direct and consensual' },
            { label: 'CN II — blink to light', method: 'Bright light in the line of sight', normal: 'Reflex blink' },
            { label: 'CN VII — facial symmetry at rest', method: 'Observe resting face', normal: 'Symmetric nasolabial folds' },
            { label: 'CN VII — facial symmetry with cry', method: 'Note face during a cry', normal: 'Symmetric grimace' },
            { label: 'CN IX, X, XII — suck and swallow', method: 'Offer clean gloved finger, pacifier, or during feed', normal: 'Strong coordinated suck-swallow, no choking' }
          ], abnormalHints: ['Asymmetric face (CN VII injury — usually forceps)', 'Poor suck or uncoordinated swallow', 'Fixed or unequal pupil'] },

          { name: 'Tone — passive', steps: [
            { label: 'Pull-to-sit', method: 'Grasp hands/wrists, pull smoothly to sit', normal: 'Brief head lag at term; not dramatic' },
            { label: 'Ventral suspension', method: 'Suspend prone over hand at chest', normal: 'Head briefly lifts to horizontal; extremities flexed' },
            { label: 'Arm recoil', method: 'Extend both arms fully at elbows, release', normal: 'Rapid return to flexion' },
            { label: 'Popliteal angle', method: 'Hip flexed 90°, extend knee maximally', normal: '≤110°' }
          ], abnormalHints: ['Marked head lag (hypotonia)', 'Slip-through on vertical suspension', 'Hypertonia / scissoring', 'Floppy limbs with no recoil'] },

          { name: 'Spontaneous movement', steps: [
            { label: 'Observe limbs', method: 'Undisturbed over 1 min, note movement', normal: 'Symmetric antigravity movement of all 4 limbs' },
            { label: 'Quality of movement', method: 'Note smoothness vs jitteriness', normal: 'Smooth, mildly variable movements' }
          ], abnormalHints: ['Paucity of movement in one limb', 'Coarse jitteriness', 'Clonic jerks', 'Tonic posturing'] },

          { name: 'Primitive reflexes', steps: [
            { label: 'Moro', method: 'Support head; allow 30° head drop or loud clap', normal: 'Symmetric arm abduction then flexion, often cry' },
            { label: 'Rooting', method: 'Stroke cheek at corner of mouth', normal: 'Turns head toward stroke and opens mouth' },
            { label: 'Palmar grasp', method: 'Press into palm with finger', normal: 'Strong, symmetric finger flexion' },
            { label: 'Plantar grasp', method: 'Press ball of foot below toes', normal: 'Toes flex around finger symmetrically' },
            { label: 'Stepping', method: 'Hold upright with feet touching surface', normal: 'Alternating stepping movements' },
            { label: 'Tonic neck (fencing)', method: 'Turn head to one side with infant supine', normal: 'Same-side arm extends, opposite flexes (not obligate)' },
            { label: 'Galant', method: 'Stroke paravertebrally from shoulder to buttock, one side', normal: 'Trunk curves toward stroked side' }
          ], abnormalHints: ['Absent or asymmetric Moro — CNS injury, brachial plexus, clavicle fx', 'Absent grasps — CNS depression', 'Obligate tonic neck is abnormal'] },

          { name: 'Babinski (plantar response)', steps: [
            { label: 'Stroke lateral sole', method: 'Firm stroke from heel toward toes along lateral plantar border', normal: 'Up-going great toe with fanning (normal in newborn)' },
            { label: 'Symmetry check', method: 'Repeat opposite foot', normal: 'Symmetric response' }
          ], abnormalHints: ['Asymmetric response is always abnormal'] }
        ]
      },
      resp: {
        overview: 'Newborn respiratory transition — RDS, TTN, pneumonia, meconium aspiration dominate the differential. Normal RR ≤ 60. Grunting is an alarm sign.',
        components: [
          { name: 'Inspection',
            significance: 'Detects distress and localises cause. Silverman score quantifies retraction severity.',
            pearl: 'Grunting is physiologic PEEP against a partially closed glottis — always a sign of significant lung pathology in a newborn. Never dismiss it as fussy breathing.',
            steps: [
              { label: 'Respiratory rate', method: 'Count over full 60 s, quiet and undisturbed.', normal: '40–60 /min; tachypnea > 60' },
              { label: 'Work of breathing (Silverman)', method: 'Inspect for upper-chest retraction, lower-chest retraction, xiphoid retraction, nasal flaring, grunting. Score 0–2 for each.', normal: 'Total Silverman 0 — no distress' },
              { label: 'Audible sounds', method: 'Listen without stethoscope — stridor? grunting? wheeze across the room?', normal: 'Quiet respirations' },
              { label: 'Colour', method: 'Inspect trunk and mucous membranes for central cyanosis; acrocyanosis (blue hands/feet) is normal in the first days.', normal: 'Pink trunk and mucous membranes' },
              { label: 'Chest shape', method: 'Inspect AP:transverse diameter and symmetry.', normal: 'Slightly barrel-shaped is normal; symmetric' }
            ],
            abnormalHints: ['Grunting — RDS, pneumonia, sepsis, CHD', 'Retractions + tachypnea — RDS, TTN, pneumothorax', 'Central cyanosis — cyanotic CHD, severe lung disease, persistent pulmonary HTN', 'Asymmetric chest movement — pneumothorax, diaphragmatic hernia'] },
          { name: 'Auscultation',
            significance: 'Short stethoscope time in neonates because they fuss easily — get the most important zones first.',
            pearl: 'Listen at the axilla, not just the anterior chest — pneumothorax can sound normal anteriorly. Auscultate both axillae systematically.',
            steps: [
              { label: 'Air entry — anterior', method: 'Listen bilaterally at the upper and lower anterior chest.', normal: 'Symmetric bilateral air entry' },
              { label: 'Air entry — axillary', method: 'Listen bilaterally at each axilla — this is the most sensitive area for detecting a small pneumothorax.', normal: 'Clear and symmetric' },
              { label: 'Adventitious sounds', method: 'Listen for transmitted upper-airway sounds, crackles (RDS, pneumonia), grunting sounds.', normal: 'No crackles, no wheeze, clear sounds' },
              { label: 'Inspiration:expiration ratio', method: 'Observe breath-sound timing.', normal: 'Inspiration > expiration in length' }
            ],
            abnormalHints: ['Asymmetric air entry — pneumothorax, diaphragmatic hernia, endobronchial intubation', 'Fine crackles — RDS, TTN, pneumonia', 'Absent breath sounds unilaterally — pneumothorax or selective intubation'] }
        ]
      },
      cv: {
        overview: 'Neonatal CV exam screens for CHD — the window of presentation is short and some lesions (duct-dependent) decompensate within hours of birth. Pre/postductal saturations + femoral pulses are the two fastest screens.',
        components: [
          { name: 'Inspection and pre/postductal saturations',
            significance: 'Pre/postductal SpO₂ differential > 3% suggests a duct-dependent lesion or persistent pulmonary HTN. Universal CCHD screening uses this.',
            pearl: 'Pulse ox on the right hand = preductal (proximal to PDA insertion). Foot = postductal. Both arms and both legs should match; a differential is a red flag for critical CHD.',
            steps: [
              { label: 'Central cyanosis', method: 'Inspect tongue, lips, oral mucosa.', normal: 'Pink mucous membranes' },
              { label: 'Pre/postductal SpO₂', method: 'Measure SpO₂ in right hand (preductal) AND either foot (postductal). Baby must be ≥24 hr old for CCHD screening.', normal: 'Both ≥ 95% AND difference < 3%' },
              { label: 'Peripheral perfusion', method: 'Capillary refill on sternum; note mottling or distal cyanosis.', normal: 'Capillary refill < 2 s, warm pink extremities' },
              { label: 'Precordial activity', method: 'Inspect anterior chest for hyperactive precordium.', normal: 'Not visible or minimally visible' }
            ],
            abnormalHints: ['Central cyanosis with SpO₂ < 95% → cyanotic CHD workup (4-extremity BP, ECG, hyperoxia test, echo)', 'Differential > 3% (pre > post) → duct-dependent systemic flow (HLHS, coarctation, interrupted arch)', 'Preductal < postductal — persistent pulmonary HTN with reversed shunt'] },
          { name: 'Palpation and auscultation',
            significance: 'Absent femoral pulses + arm-leg BP gradient = coarctation. Many CHD lesions manifest murmurs only after ductus closes (48–72 h).',
            pearl: 'Always palpate femoral pulses before discharging any newborn. Absent femorals in a well-appearing baby can be the only finding in a ductal-dependent coarctation — catastrophic if missed.',
            steps: [
              { label: 'Apex beat', method: 'Palpate at the 4th ICS left of sternum (apex is higher in newborns).', normal: 'Palpable at 4th ICS, mid-clavicular or just lateral' },
              { label: 'Femoral pulses', method: 'Palpate both femoral pulses at the mid-inguinal point while simultaneously feeling the right brachial pulse — detects delay.', normal: 'Present, symmetric, equal timing with brachial' },
              { label: 'Auscultate each cardiac area', method: 'Use pediatric diaphragm at each classic point; baby quiet if possible.', normal: 'S1 S2 crisp; physiologic flow murmur sometimes present in the first 24–48 h' },
              { label: 'Continuous murmur', method: 'Listen below the left clavicle for a continuous ("machinery") murmur of PDA.', normal: 'No continuous murmur after the first day of life in a term baby' },
              { label: 'Four-limb BP (if any concern)', method: 'Right arm, left arm, both legs.', normal: 'Within 10 mmHg across limbs' }
            ],
            abnormalHints: ['Absent femoral pulses — coarctation of the aorta (surgical emergency if duct-dependent)', 'Harsh holosystolic at LLSB — VSD', 'Continuous machinery murmur — PDA (expected in preterm; in term > 48 h is abnormal)', 'Gallop S3/S4 — heart failure', 'Single S2 — transposition, truncus, severe AS/PS'] }
        ]
      }
    },

    infant: {
      label: 'Infant (1–12 months)',
      msk: {
        overview: 'Continued DDH screen through 6 months. Watch motor progression and symmetry of tone/movement.',
        components: [
          { name: 'Hips — continued DDH screen', steps: [
            { label: 'Thigh-fold symmetry', method: 'Inspect with infant supine, thighs flexed', normal: 'Symmetric folds' },
            { label: 'Barlow/Ortolani (through 3mo)', method: 'As in newborn — thumb medial, flex 90°, adduct+push then abduct+lift', normal: 'Negative bilaterally' },
            { label: 'Abduction (any age)', method: 'Flex 90°, abduct simultaneously', normal: '≥70° symmetric abduction' },
            { label: 'Galeazzi', method: 'Knees flexed feet flat on exam table', normal: 'Knees equal height' }
          ], abnormalHints: ['Clunk on Barlow/Ortolani (<3mo)', 'Limited abduction', 'Asymmetric folds', 'Positive Galeazzi'] },

          { name: 'Gross-motor milestones (age-appropriate)', steps: [
            { label: 'Head control', method: 'Prone, pull-to-sit, held upright', normal: 'Age-appropriate: 2mo lifts head 45°; 4mo no head lag' },
            { label: 'Rolling', method: 'Observe on flat surface', normal: 'Rolls back-to-front by 5–6mo' },
            { label: 'Sitting', method: 'Place in sitting position', normal: 'Tripod sit by 6mo; sits without support by 7–8mo' },
            { label: 'Standing', method: 'Support under arms', normal: 'Bears weight by 6mo; pulls to stand by 9mo' }
          ], abnormalHints: ['Milestone delay by ≥2mo', 'Loss of previously attained milestone', 'Asymmetric use of limbs'] },

          { name: 'Spine', steps: [
            { label: 'Palpate seated', method: 'Run finger along spine with infant sitting or held upright', normal: 'Midline, no step-offs' },
            { label: 'Back curvature', method: 'Inspect sitting and lying', normal: 'Physiologic gentle kyphosis in early infancy; lumbar lordosis as sitting develops' }
          ], abnormalHints: ['Fixed kyphoscoliosis', 'Sacral dimple with cutaneous marker', 'Step-off'] },

          { name: 'Extremities', steps: [
            { label: 'Passive range', method: 'Through each major joint', normal: 'Full symmetric range' },
            { label: 'Joint inspection', method: 'Inspect for swelling, warmth, effusion', normal: 'No swelling, warmth, or effusion' },
            { label: 'Feet alignment', method: 'Observe standing if pulling up, else passive positioning', normal: 'Correctable or aligned feet; flexible' }
          ], abnormalHints: ['Joint swelling/warmth (septic vs reactive arthritis)', 'Rigid clubfoot', 'Persistent asymmetric tone'] }
        ]
      },
      neuro: {
        overview: 'Primitive reflexes fading on schedule; protective reflexes emerging; gross motor and tone interlinked.',
        components: [
          { name: 'Alertness and social engagement', steps: [
            { label: 'Social smile', method: 'Face-to-face interaction', normal: 'Social smile by 6–8 weeks' },
            { label: 'Tracking', method: 'Move object across visual field', normal: '180° horizontal tracking by 3mo' },
            { label: 'Engagement', method: 'Face-to-face, voice, toys', normal: 'Age-appropriate reciprocal interaction' }
          ], abnormalHints: ['No social smile by 3mo', 'Absent tracking past 3mo', 'Poor engagement (developmental concern)'] },

          { name: 'Cranial nerves', steps: [
            { label: 'Pupils', method: 'Light response each eye', normal: 'Equal reactive' },
            { label: 'Eye alignment', method: 'Inspect with gaze forward and in all directions', normal: 'No strabismus past 4mo' },
            { label: 'Facial symmetry', method: 'Observe smile and cry', normal: 'Symmetric' },
            { label: 'Suck and swallow', method: 'Observe feeding', normal: 'Coordinated, no choking' }
          ], abnormalHints: ['Persistent nystagmus', 'Strabismus past 4mo', 'Asymmetric face'] },

          { name: 'Tone', steps: [
            { label: 'Pull-to-sit', method: 'Gently pull wrists/hands', normal: 'No head lag by 4mo' },
            { label: 'Ventral suspension', method: 'Support prone, observe', normal: 'Head above horizontal, extremities actively flexed (age-dependent)' },
            { label: 'Vertical suspension', method: 'Support under arms, lift', normal: 'Does not slip through hands' }
          ], abnormalHints: ['Persistent head lag past 4mo (hypotonia)', 'Hypertonia / scissoring (UMN)', 'Slip-through on vertical suspension'] },

          { name: 'Primitive reflex integration', steps: [
            { label: 'Moro', method: 'Head drop or clap', normal: 'Absent by 6mo' },
            { label: 'Palmar grasp', method: 'Press into palm', normal: 'Integrated by 5–6mo; replaced by voluntary grasp' },
            { label: 'Tonic neck', method: 'Turn head to side', normal: 'Absent by 6mo' },
            { label: 'Rooting', method: 'Stroke cheek', normal: 'Absent by 3–4mo' }
          ], abnormalHints: ['Persistence of any primitive reflex past 6mo warrants eval (CP, CNS injury)'] },

          { name: 'Protective and postural reflexes', steps: [
            { label: 'Parachute', method: 'Held prone, tilt head downward suddenly', normal: 'Symmetric arm extension protectively by 9mo (emerges 6–9mo)' },
            { label: 'Lateral propping', method: 'Seated infant, gentle tilt to one side', normal: 'Arm extends to catch by 6–7mo' },
            { label: 'Landau', method: 'Suspend prone', normal: 'Extends head, spine, legs by 6mo' }
          ], abnormalHints: ['Absent parachute after 12mo (concerning)', 'Asymmetric lateral propping', 'Absent Landau'] }
        ]
      },
      resp: {
        overview: 'Infant respiratory disease centers on bronchiolitis, reactive airways, and pneumonia. Normal RR ≤ 50 (< 2 mo: ≤ 60). Infants are obligate nose-breathers — nasal congestion alone can cause significant WOB.',
        components: [
          { name: 'Inspection',
            significance: 'Infant distress signs escalate fast. Nasal flaring, tracheal tug, head bobbing = significant WOB. Apnea in an infant < 2 mo is an emergency.',
            pearl: 'A quiet infant with retractions is more worrying than a crying one — exhausted infants stop crying and become hypoxic silently.',
            steps: [
              { label: 'Respiratory rate', method: 'Count over full 60 s while quiet.', normal: '< 2 mo: ≤ 60; 2–12 mo: ≤ 50' },
              { label: 'Work of breathing', method: 'Inspect nasal flaring, subcostal/intercostal/suprasternal retractions, tracheal tug, head-bobbing, accessory muscle use.', normal: 'No retractions, effortless breathing' },
              { label: 'Audible sounds', method: 'Stridor? Wheeze across the room? Grunting? Prolonged expiration?', normal: 'Quiet respirations' },
              { label: 'Colour and feeding history', method: 'Central cyanosis? Poor feeding (feeding is an effort marker in infants)?', normal: 'Pink, feeds well' },
              { label: 'Apnea observation', method: 'Watch for ≥ 20-s pauses or pauses < 20 s with bradycardia/cyanosis.', normal: 'No apneas' }
            ],
            abnormalHints: ['Grunting / persistent retractions — pneumonia, bronchiolitis, CHF', 'Wheeze — bronchiolitis (RSV), asthma, foreign body', 'Stridor — croup (6 mo–6 y), laryngomalacia (infant), foreign body', 'Apnea — bronchiolitis, sepsis, pertussis, seizure'] },
          { name: 'Auscultation',
            significance: 'Infants have a thin chest wall — sounds transmit widely. Symmetry, wheeze, and crackles are the main findings.',
            pearl: 'In bronchiolitis, the classical finding is widespread end-inspiratory fine crackles PLUS expiratory wheeze. Tachypnea + retractions in an RSV-season infant confirms.',
            steps: [
              { label: 'Air entry — bilateral', method: 'Warm stethoscope; listen at anterior chest and both axillae, both sides.', normal: 'Symmetric air entry' },
              { label: 'Wheeze', method: 'Listen in expiration. Diffuse wheeze = lower airway; focal wheeze = foreign body or local obstruction.', normal: 'No wheeze' },
              { label: 'Crackles', method: 'Listen in late inspiration. Focal = pneumonia; diffuse fine = bronchiolitis.', normal: 'No crackles' },
              { label: 'Prolonged expiration', method: 'Note expiration:inspiration length ratio.', normal: 'Inspiration ≥ expiration' }
            ],
            abnormalHints: ['Focal crackles + fever — pneumonia', 'Diffuse wheeze + fine crackles in an RSV-season infant — bronchiolitis', 'Silent chest with extreme WOB — impending respiratory failure'] }
        ]
      },
      cv: {
        overview: 'Most CHD manifests in the first year as pulmonary blood-flow changes and the ductus closes. Infant CV exam = growth review + inspection + femoral pulses + auscultation. A harsh pan-systolic LLSB murmur in a 6-week-old = VSD until proven otherwise.',
        components: [
          { name: 'Inspection and functional assessment',
            significance: 'Heart failure in infants presents as poor feeding, sweating during feeds (diaphoresis), tachypnea, and poor weight gain. These historical features predict bad exam findings.',
            pearl: 'Ask "Does the baby sweat while feeding?" — infant CHF presents with diaphoresis on the forehead during feeds, well before peripheral edema appears.',
            steps: [
              { label: 'Growth trajectory', method: 'Plot weight-for-age on WHO chart. Failure to thrive raises CHD concern.', normal: 'Tracking ≥ 10th percentile or stable on personal curve' },
              { label: 'Feeding history', method: 'Ask about feed duration, sweating with feeds, tachypnea with feeds, tiring easily.', normal: 'Feeds < 20 min, no diaphoresis, no tachypnea' },
              { label: 'Central cyanosis', method: 'Inspect tongue and oral mucosa.', normal: 'Pink' },
              { label: 'Clubbing', method: 'Inspect finger nail beds (subtle in infants).', normal: 'No clubbing' },
              { label: 'Peripheral perfusion', method: 'Cap refill, warmth of extremities.', normal: 'Cap refill < 2 s, warm extremities' }
            ],
            abnormalHints: ['Poor weight gain — consider CHF from L-to-R shunt (VSD, PDA, AVSD)', 'Diaphoresis with feeds — infant CHF', 'Tiring with feeds — significant CHD', 'Central cyanosis — cyanotic CHD (ToF, TGA, TA, etc.)'] },
          { name: 'Palpation and auscultation',
            significance: 'Femoral pulses + 4-limb BP screen coarctation. A harsh holosystolic murmur at LLSB is almost always a VSD in this age.',
            pearl: 'Listen over each of the 5 classic points as in the adult exam — the locations shift slightly with infant chest size but relative positions are the same. Also listen at the back: coarctation murmurs radiate there.',
            steps: [
              { label: 'Apex beat', method: 'Palpate at 4th ICS mid-clavicular line.', normal: 'Palpable at 4th ICS in infants' },
              { label: 'Femoral pulses', method: 'Palpate bilaterally, simultaneously with right brachial.', normal: 'Present, equal, no delay vs brachial' },
              { label: 'Listen at each classic area (APTM)', method: 'See APTM diagram. Use pediatric stethoscope with both diaphragm and bell.', normal: 'S1 and S2 crisp, no murmur or physiologic only' },
              { label: 'Listen over the back (interscapular)', method: 'Check for radiation of coarctation murmurs.', normal: 'No radiating murmur' }
            ],
            abnormalHints: ['Harsh holosystolic LLSB murmur — VSD', 'Continuous "machinery" murmur below left clavicle — PDA', 'Systolic ejection at ULSB + fixed split S2 — ASD', 'Ejection murmur at ULSB + cyanosis — tetralogy of Fallot', 'Absent femorals + radio-femoral delay — coarctation', 'Gallop + tachycardia — heart failure'] }
        ]
      }
    },

    toddler: {
      label: 'Toddler (1–3 years)',
      msk: {
        overview: 'Gait, physiologic alignment changes, in-toeing, joint range. Cooperation unpredictable — use play.',
        components: [
          { name: 'Gait', steps: [
            { label: 'Base of support', method: 'Have child walk ~10 feet', normal: 'Wide-based initially, narrowing by 2y' },
            { label: 'Heel-strike', method: 'Observe foot contact pattern', normal: 'Heel-strike developing by 18mo, consistent by 2y' },
            { label: 'Arm swing', method: 'Observe reciprocal arm swing', normal: 'Reciprocal arm swing by 18mo' },
            { label: 'Symmetry', method: 'Watch both sides in stance and swing', normal: 'Symmetric stride length and cadence' }
          ], abnormalHints: ['Toe-walking past 2y (idiopathic vs CP vs DMD)', 'Limp (Legg-Calvé-Perthes, transient synovitis, trauma)', 'Wide-based ataxia'] },

          { name: 'Knee alignment', steps: [
            { label: 'Stand feet together', method: 'Feet/medial malleoli touching; inspect knees', normal: 'Genu varum resolving by 18–24mo; mild genu valgum common by 2–3y' },
            { label: 'Intercondylar or intermalleolar distance', method: 'Measure if alignment appears abnormal', normal: '<5cm intercondylar (varum) or <8cm intermalleolar (valgum)' },
            { label: 'Symmetry', method: 'Compare sides', normal: 'Symmetric' }
          ], abnormalHints: ['Persistent varum past 2y', 'Severe valgum >8cm', 'Unilateral (Blount disease, rickets)'] },

          { name: 'Feet alignment', steps: [
            { label: 'In-toeing / out-toeing', method: 'Observe foot angle during gait', normal: 'Mild in-toeing common (tibial torsion, femoral anteversion)' },
            { label: 'Arch during stance', method: 'Stand flat, then on tiptoes', normal: 'Flexible flat foot that forms arch on tiptoe' },
            { label: 'Heel alignment', method: 'View from behind standing', normal: 'Neutral or mildly valgus heel' }
          ], abnormalHints: ['Rigid flat foot (tarsal coalition)', 'Fixed metatarsus adductus', 'Severe in-toeing >15°'] },

          { name: 'Joint range', steps: [
            { label: 'Hips', method: 'Flex, abduct, rotate each hip', normal: 'Full symmetric range, no pain' },
            { label: 'Knees', method: 'Flex, extend; palpate for effusion', normal: 'Full range, no effusion, stable' },
            { label: 'Ankles', method: 'Dorsiflex, plantarflex, invert, evert', normal: 'Full range' },
            { label: 'Shoulders, elbows, wrists', method: 'Through full range each', normal: 'Full symmetric range' }
          ], abnormalHints: ['Joint effusion (septic vs reactive)', 'Guarded or painful motion', 'Asymmetric limitation'] },

          { name: 'Spine', steps: [
            { label: 'Inspect standing', method: 'View spine from behind', normal: 'Midline, no prominent curve' },
            { label: 'Palpate midline', method: 'Run finger along spinous processes', normal: 'Midline, no step-off, no tenderness' },
            { label: 'Shoulder/hip symmetry', method: 'Compare shoulder and hip heights', normal: 'Symmetric' }
          ], abnormalHints: ['Fixed scoliosis', 'Abnormal kyphosis', 'Asymmetric shoulder/hip', 'Midline tenderness'] }
        ]
      },
      neuro: {
        overview: 'Shifting to adult-pattern exam. Primitive reflexes should be absent. Use play-based techniques.',
        components: [
          { name: 'Mental status and language', steps: [
            { label: 'Engagement', method: 'Interaction with examiner/parent', normal: 'Alert, interactive, age-appropriate' },
            { label: 'Language — expressive', method: 'Note spontaneous utterances', normal: '1y: 1–3 words; 2y: 2-word phrases; 3y: short sentences' },
            { label: 'Language — receptive', method: 'Ask to point to body parts or follow simple commands', normal: 'Follows age-appropriate commands' }
          ], abnormalHints: ['Language regression (autism, epileptic encephalopathy)', 'Poor engagement', 'No 2-word phrases by 2y'] },

          { name: 'Cranial nerves', steps: [
            { label: 'CN II — pupil response', method: 'Shine light each eye', normal: 'Pupils equal reactive' },
            { label: 'CN III, IV, VI — EOM', method: 'Follow toy in H pattern', normal: 'Full smooth tracking, no strabismus' },
            { label: 'CN V — facial sensation', method: 'Light touch on forehead, cheek, jaw', normal: 'Responds to touch, symmetric' },
            { label: 'CN VII — face', method: 'Elicit smile, watch eye closure during cry', normal: 'Symmetric face' },
            { label: 'CN IX, X, XII — mouth', method: 'Say "ahh"; stick out tongue', normal: 'Palate rises symmetrically; tongue midline' }
          ], abnormalHints: ['Strabismus', 'Facial asymmetry', 'Tongue deviation', 'Absent palate elevation'] },

          { name: 'Motor — tone and bulk', steps: [
            { label: 'Passive tone', method: 'Move each limb through full range', normal: 'Normal resistance throughout' },
            { label: 'Bulk inspection', method: 'Inspect muscle bulk of thighs, calves, glutes', normal: 'Symmetric, age-appropriate bulk' },
            { label: 'Contracture check', method: 'Test for heel-cord tightness, hamstring tightness', normal: 'No contractures' }
          ], abnormalHints: ['Spasticity (especially catch in ankles)', 'Hypotonia', 'Calf pseudo-hypertrophy (DMD)'] },

          { name: 'Motor — functional strength', steps: [
            { label: 'Rising from floor', method: 'Place flat on back; ask to stand up', normal: 'Rises without using hands to push off thighs (no Gowers)' },
            { label: 'Climbing stairs', method: 'Observe or history', normal: 'Climbs holding rail' },
            { label: 'Squatting/getting up', method: 'Encourage via play', normal: 'Squats and rises without help' }
          ], abnormalHints: ['Gowers sign (proximal weakness — DMD)', 'Unable to climb stairs at age expected', 'Calf pain on walking (myositis)'] },

          { name: 'Deep tendon reflexes', steps: [
            { label: 'Patellar', method: 'Sitting or supine with distraction (toy)', normal: '2+ symmetric' },
            { label: 'Biceps', method: 'Arm at rest, strike thumb on tendon', normal: '2+ symmetric' },
            { label: 'Achilles', method: 'With distraction', normal: '2+ symmetric' }
          ], abnormalHints: ['Hyperreflexia or clonus (UMN, CP)', 'Absent reflexes (LMN, neuropathy)', 'Asymmetry'] },

          { name: 'Coordination and gait', steps: [
            { label: 'Run', method: 'Watch run ~10 feet', normal: 'Runs with reciprocal arm swing by 2y' },
            { label: 'Stairs', method: 'Observe', normal: 'Climbs with rail' },
            { label: 'Kick ball', method: 'Place ball; observe kick', normal: 'Kicks by 2y' },
            { label: 'Ataxia check', method: 'Watch for fluency of movement', normal: 'Smooth, no tremor' }
          ], abnormalHints: ['Ataxic gait', 'Intention tremor', 'Clumsiness beyond age'] },

          { name: 'Plantar response', steps: [
            { label: 'Stroke lateral sole', method: 'Firm stroke from heel to toes', normal: 'Down-going great toe (plantar flexion) by age 2' }
          ], abnormalHints: ['Up-going toe after age 2 = UMN sign (Babinski positive)'] }
        ]
      },
      resp: {
        overview: 'Toddler respiratory disease: viral URIs, reactive airways, croup (6 mo–6 y classical age), foreign-body aspiration (age 1–3 is peak). Normal RR ≤ 40.',
        components: [
          { name: 'Inspection',
            pearl: 'Sudden onset of unilateral wheeze + choking history in a toddler = foreign body until proven otherwise. CXR in expiration (or decubitus) helps show the trapped air.',
            steps: [
              { label: 'Respiratory rate', method: 'Count over full 60 s if possible.', normal: '≤ 40 /min' },
              { label: 'Work of breathing', method: 'Retractions, nasal flaring, tracheal tug.', normal: 'No retractions' },
              { label: 'Audible sounds', method: 'Stridor (croup), wheeze, barking cough.', normal: 'Quiet respirations' },
              { label: 'Drooling / posture', method: 'Tripod positioning, drooling (epiglottitis in unvaccinated child).', normal: 'No drooling, normal posture' }
            ],
            abnormalHints: ['Barking cough + stridor — croup', 'Drooling + tripod + toxic — epiglottitis (emergency)', 'Sudden unilateral wheeze — foreign body aspiration'] },
          { name: 'Auscultation',
            steps: [
              { label: 'Air entry', method: 'Cooperation variable — listen quickly and systematically.', normal: 'Symmetric' },
              { label: 'Adventitious sounds', method: 'Wheeze, crackles, stridor at the neck.', normal: 'Clear lung fields' },
              { label: 'Unilateral findings', method: 'Focal wheeze, decreased air entry, or asymmetry — think foreign body or pneumonia.', normal: 'Symmetric bilateral' }
            ],
            abnormalHints: ['Unilateral decreased breath sounds + wheeze — foreign body', 'Focal crackles — pneumonia', 'Diffuse wheeze — asthma/RAD'] }
        ]
      },
      cv: {
        overview: 'Most hemodynamically significant CHD has been detected by this age. Innocent murmurs peak here (Still\'s murmur, venous hum). The exam is adult-pattern but with smaller chest and less cooperation.',
        components: [
          { name: 'Inspection and palpation',
            pearl: 'Innocent murmurs are a normal finding in well toddlers — soft, systolic, at the LLSB, musical, and they change with position. Anything that doesn\'t fit that pattern deserves referral.',
            steps: [
              { label: 'General appearance + growth', method: 'Happy, active, tracking growth.', normal: 'Normal growth and activity' },
              { label: 'Colour and clubbing', method: 'Inspect tongue, nail beds.', normal: 'Pink, no clubbing' },
              { label: 'Apex beat', method: 'Palpate at 5th ICS mid-clavicular line.', normal: 'Located at 5th ICS MCL, tapping quality' },
              { label: 'Peripheral pulses', method: 'Brachial + femoral, symmetric and simultaneous.', normal: 'Symmetric, no delay' }
            ],
            abnormalHints: ['Tiring with play, poor growth — missed CHD', 'Cyanosis + clubbing — cyanotic CHD', 'Absent femorals — coarctation'] },
          { name: 'Auscultation',
            steps: [
              { label: 'All 5 classic points', method: 'See APTM diagram above — Aortic, Pulmonic, Erb\'s, Tricuspid, Mitral.', normal: 'Crisp S1, S2 with physiologic split at pulmonic area' },
              { label: 'Evaluate any murmur', method: 'Timing, location, radiation, grade. Apply the "7 S" innocent-murmur criteria.', normal: 'No murmur, or soft (≤ grade 2) innocent murmur' },
              { label: 'Change with position', method: 'Have toddler sit, stand, lie down — does the murmur change? Innocent murmurs typically disappear or soften with standing.', normal: 'Murmur (if any) changes with position' }
            ],
            abnormalHints: ['Harsh, loud (≥3/6), radiating, or diastolic murmur — not innocent, refer', 'Cyanosis + murmur — CHD workup', 'Fixed split S2 — ASD'] }
        ]
      }
    },

    preschool: {
      label: 'Preschool (3–5 years)',
      msk: {
        overview: 'Functional gait maneuvers, scoliosis screen, resolving physiologic alignment.',
        components: [
          { name: 'Gait — multiple patterns', steps: [
            { label: 'Normal gait', method: 'Walk ~15 feet barefoot', normal: 'Symmetric, smooth, reciprocal arm swing' },
            { label: 'Heel walking', method: 'Walk on heels only', normal: 'Able by 4y' },
            { label: 'Toe walking', method: 'Walk on toes only', normal: 'Able by 4y' },
            { label: 'Tandem walking', method: 'Heel-to-toe along a line for 5 steps', normal: 'Able by 4y with minimal deviation' },
            { label: 'Hopping', method: 'Hop on one foot', normal: '3–5 hops on preferred foot by 4y' }
          ], abnormalHints: ['Persistent toe-walking', 'Asymmetric stance/stride', 'Difficulty with any pattern'] },

          { name: 'Alignment', steps: [
            { label: 'Knee alignment', method: 'Stand feet together', normal: 'Mild residual valgus resolving; neutral by 6–7y' },
            { label: 'Foot arch', method: 'Standing, then tiptoe', normal: 'Arch forms on tiptoe (flexible flat foot)' },
            { label: 'Heel position', method: 'View from behind standing', normal: 'Neutral or mild valgus' }
          ], abnormalHints: ['Persistent unilateral varum', 'Rigid flat foot (no arch on tiptoe)', 'Pes cavus'] },

          { name: 'Scoliosis screen (Adam forward-bend)', steps: [
            { label: 'Position', method: 'Feet together, bend forward at waist, arms hanging, palms together', normal: 'Arms and head relaxed' },
            { label: 'View from behind', method: 'Examiner at same height; look along back', normal: 'Symmetric paraspinal contour' },
            { label: 'View from side', method: 'Side view for kyphosis', normal: 'Smooth thoracic curve' }
          ], abnormalHints: ['Rib hump (thoracic scoliosis)', 'Lumbar prominence', 'Asymmetric scapular height'] },

          { name: 'Joint range and stability', steps: [
            { label: 'Active range', method: 'Ask to perform full range at hips, knees, ankles, shoulders, elbows, wrists', normal: 'Full symmetric range, no pain' },
            { label: 'Knee stability', method: 'Palpate for effusion; assess stability if complaint', normal: 'Stable, no effusion' },
            { label: 'Carrying angle (elbows)', method: 'Arms at sides, palms forward', normal: 'Normal valgus carrying angle' }
          ], abnormalHints: ['Joint hypermobility (Beighton score)', 'Effusion', 'Pain with motion', 'Valgus >15°'] },

          { name: 'Feet', steps: [
            { label: 'Standing inspection', method: 'View from front and behind', normal: 'Symmetric feet, neutral heel, flexible flat feet common' },
            { label: 'Tiptoe', method: 'Stand on tiptoes', normal: 'Arch forms, symmetric' },
            { label: 'Pes planus vs cavus', method: 'Note arch height', normal: 'Flexible flat foot or mild arch' }
          ], abnormalHints: ['Rigid flat foot', 'Pes cavus (Charcot-Marie-Tooth)', 'Pain'] }
        ]
      },
      neuro: {
        overview: 'Formal pediatric neuro exam now feasible — most 4- and 5-year-olds cooperate with structured testing.',
        components: [
          { name: 'Mental status and language', steps: [
            { label: 'Orientation (age-appropriate)', method: 'Ask name, age, where you are', normal: 'Knows name and age by 3y; location by 4–5y' },
            { label: 'Speech intelligibility', method: 'Listen to spontaneous speech', normal: 'Strangers understand by 4y' },
            { label: 'Receptive language', method: '2- and 3-step commands', normal: 'Follows 3-step commands by 4–5y' }
          ], abnormalHints: ['Dysarthria', 'Expressive or receptive language delay', 'Inattention'] },

          { name: 'Cranial nerves (II–XII)', steps: [
            { label: 'CN II — visual acuity', method: 'HOTV chart or pictures at 10ft, each eye', normal: '20/30 or better by 4y; 20/25 by 5y' },
            { label: 'CN II — visual fields', method: 'Confrontation with toys from periphery', normal: 'Full fields' },
            { label: 'CN II — pupils', method: 'Light response each eye', normal: 'PERRL' },
            { label: 'CN III, IV, VI — EOM', method: 'Follow toy in H pattern; include convergence', normal: 'Full EOM, convergence present' },
            { label: 'CN V — sensation', method: 'Light touch forehead, cheek, jaw each side', normal: 'Intact, symmetric' },
            { label: 'CN V — motor', method: 'Clench teeth, palpate masseter', normal: 'Symmetric strong bulk' },
            { label: 'CN VII — face', method: 'Smile, wrinkle forehead, close eyes, puff cheeks', normal: 'Symmetric movement of all regions' },
            { label: 'CN VIII — hearing', method: 'Finger rub each ear or whispered words', normal: 'Intact bilaterally' },
            { label: 'CN IX, X — palate', method: 'Open mouth, say "ahh"', normal: 'Palate rises symmetrically, uvula midline' },
            { label: 'CN XI — SCM/trapezius', method: 'Shrug shoulders, turn head against resistance', normal: 'Symmetric strength' },
            { label: 'CN XII — tongue', method: 'Stick tongue out, move side to side', normal: 'Midline, no atrophy, full movement' }
          ], abnormalHints: ['Strabismus (amblyopia risk)', 'Facial weakness', 'Tongue deviation/fasciculations', 'Uvula off-midline'] },

          { name: 'Motor — tone, bulk, strength', steps: [
            { label: 'Tone inspection', method: 'Passive range all four limbs', normal: 'Normal tone throughout' },
            { label: 'Bulk inspection', method: 'Observe muscle bulk symmetry', normal: 'Symmetric, age-appropriate' },
            { label: 'Strength — shoulder abduction', method: 'Arms out, push down against resistance', normal: '5/5 bilaterally' },
            { label: 'Strength — elbow flexion', method: 'Flex elbow against resistance', normal: '5/5 bilaterally' },
            { label: 'Strength — grip', method: 'Squeeze examiner\'s fingers', normal: '5/5 symmetric' },
            { label: 'Strength — hip flexion', method: 'Lift leg off table against resistance', normal: '5/5 bilaterally' },
            { label: 'Strength — knee extension', method: 'Straighten knee against resistance', normal: '5/5 bilaterally' },
            { label: 'Strength — dorsiflexion', method: 'Pull toes up against resistance', normal: '5/5 bilaterally' }
          ], abnormalHints: ['Focal weakness', 'Gowers sign', 'Pseudohypertrophy (DMD)', 'Atrophy'] },

          { name: 'Deep tendon reflexes', steps: [
            { label: 'Biceps', method: 'Thumb on biceps tendon, strike', normal: '2+ symmetric' },
            { label: 'Patellar', method: 'Knees hanging, strike patellar tendon', normal: '2+ symmetric' },
            { label: 'Achilles', method: 'Slight dorsiflexion, strike Achilles tendon', normal: '2+ symmetric' },
            { label: 'Plantar response', method: 'Stroke lateral sole heel-to-toes', normal: 'Down-going great toe' }
          ], abnormalHints: ['Hyperreflexia or clonus (UMN)', 'Hyporeflexia (LMN)', 'Up-going plantar (Babinski — abnormal past 2y)', 'Asymmetry'] },

          { name: 'Coordination', steps: [
            { label: 'Finger-to-nose', method: 'Touch examiner\'s finger then own nose, repeat', normal: 'Smooth, no dysmetria' },
            { label: 'Heel-to-shin', method: 'Run heel down opposite shin', normal: 'Smooth bilaterally' },
            { label: 'Rapid alternating movements', method: 'Tap palm with opposite hand alternating palm/back', normal: 'Rhythmic, symmetric' },
            { label: 'Tandem walk', method: 'Heel-to-toe for 5 steps', normal: 'Minimal deviation' }
          ], abnormalHints: ['Dysmetria', 'Dysdiadochokinesia', 'Intention tremor', 'Ataxic tandem'] },

          { name: 'Sensory', steps: [
            { label: 'Light touch — hands', method: 'Cotton wisp on palm/dorsum, eyes closed', normal: 'Feels each touch' },
            { label: 'Light touch — feet', method: 'Same on dorsum of foot bilaterally', normal: 'Feels each touch' }
          ], abnormalHints: ['Focal sensory loss', 'Stocking-glove loss'] },

          { name: 'Gait and Romberg', steps: [
            { label: 'Normal gait', method: 'Walk ~20 feet', normal: 'Smooth, symmetric' },
            { label: 'Heel walk', method: 'Walk on heels', normal: 'Able without difficulty' },
            { label: 'Toe walk', method: 'Walk on toes', normal: 'Able without difficulty' },
            { label: 'Tandem', method: 'Heel-to-toe', normal: 'Intact' },
            { label: 'Romberg (5y+)', method: 'Feet together, eyes closed, stand 10s', normal: 'Stable without sway' }
          ], abnormalHints: ['Ataxic gait (cerebellar)', 'Romberg positive (dorsal column)', 'Circumduction (UMN)'] }
        ]
      },
      resp: {
        overview: 'Adult-pattern but shorter. Cooperation better than toddler. RR ≤ 30. Common: asthma/RAD, pneumonia, URIs.',
        components: [
          { name: 'Inspection',
            steps: [
              { label: 'Respiratory rate', method: 'Count over full 60 s quietly.', normal: '≤ 30 /min' },
              { label: 'Work of breathing', method: 'Retractions, nasal flaring, accessory muscle use.', normal: 'Effortless breathing' },
              { label: 'Audible sounds', method: 'Wheeze, stridor, cough quality (barking = croup).', normal: 'Quiet' },
              { label: 'Chest shape', method: 'AP:transverse, hyperinflation signs.', normal: 'Not barrel-chested' }
            ],
            abnormalHints: ['Barrel chest — chronic asthma, cystic fibrosis', 'Retractions + wheeze — asthma exacerbation'] },
          { name: 'Auscultation',
            steps: [
              { label: 'Systematic zones', method: 'Upper, mid, lower fields anteriorly and posteriorly; axillae bilaterally. Cooperative deep breaths through mouth.', normal: 'Symmetric vesicular sounds' },
              { label: 'Wheeze', method: 'Expiratory, diffuse (asthma) or focal (foreign body, rare at this age).', normal: 'No wheeze' },
              { label: 'Crackles', method: 'Focal = pneumonia; diffuse fine = interstitial disease (rare in kids).', normal: 'No crackles' }
            ],
            abnormalHints: ['Focal crackles + fever — pneumonia', 'Diffuse wheeze — asthma', 'Prolonged expiration with wheeze — lower airway obstruction'] }
        ]
      },
      cv: {
        overview: 'Most CHD is detected by this age. Innocent murmurs peak in this range. Sports participation exams require thorough CV screening.',
        components: [
          { name: 'Inspection and palpation',
            steps: [
              { label: 'General and growth', method: 'Track on growth curve; activity tolerance.', normal: 'Normal growth, active' },
              { label: 'Apex beat', method: '5th ICS mid-clavicular line.', normal: 'Normal position and character' },
              { label: 'Peripheral pulses', method: 'Brachial + femoral simultaneously. BP in arm and leg if HTN.', normal: 'Symmetric, no delay' }
            ],
            abnormalHints: ['Absent femorals or arm-leg BP gradient — coarctation (always check in HTN screening)', 'Displaced apex — cardiomegaly'] },
          { name: 'Auscultation',
            pearl: 'The 7 "S" criteria and the 5 classic innocent murmurs (see panel above) handle most murmurs you\'ll find in this age group. Still\'s murmur is the single most common.',
            steps: [
              { label: 'All 5 classic points', method: 'Walk through A → P → E → T → M with diaphragm then bell.', normal: 'S1 S2 clear, physiologic S2 split at pulmonic, no added sounds' },
              { label: 'Any murmur', method: 'Characterise: timing, location, radiation, grade, character. Apply 7 S criteria + compare to innocent-murmur panel.', normal: 'No murmur, or innocent flow murmur meeting all 7 S criteria' },
              { label: 'Position change', method: 'Standing vs supine. Innocent murmurs typically soften or disappear on standing.', normal: 'Murmur (if any) changes with position' },
              { label: 'Sports screening extras (if applicable)', method: 'Screen for HOCM — murmur intensifies with Valsalva and standing (opposite of most).', normal: 'No murmur worsening on Valsalva' }
            ],
            abnormalHints: ['Murmur breaking any of the 7 S criteria — refer', 'Harsh systolic at LUSB + fixed split S2 — ASD', 'Murmur louder with Valsalva — HOCM (sports participation risk)', 'Diastolic murmur — always pathologic'] }
        ]
      }
    },

    school: {
      label: 'School-age (6–11 years)',
      msk: {
        overview: 'Scoliosis screening peri-puberty, sports overuse injuries, resolving alignment.',
        components: [
          { name: 'Scoliosis screen (forward-bend + scoliometer)', steps: [
            { label: 'Standing inspection', method: 'Shoulders and iliac crest heights', normal: 'Symmetric shoulder and pelvic heights' },
            { label: 'Forward bend (Adam test)', method: 'Feet together, bend forward at waist, arms hanging palms together', normal: 'Symmetric paraspinal contour' },
            { label: 'Rib hump', method: 'View tangentially from behind at level of curve', normal: 'No rib hump' },
            { label: 'Lumbar prominence', method: 'Same view at lumbar level', normal: 'No prominence' },
            { label: 'Scoliometer (if available)', method: 'Place scoliometer across rib hump, read angle of trunk rotation', normal: 'ATR < 5°; ≥7° → refer' }
          ], abnormalHints: ['Rib hump', 'ATR ≥7°', 'Asymmetric shoulders or pelvis', 'Decompensation (plumb line offset)'] },

          { name: 'Back and spine', steps: [
            { label: 'Posture inspection', method: 'Standing, view front/back/side', normal: 'Normal spinal curves; plumb line centered' },
            { label: 'Palpate spinous processes', method: 'From C2 to S1', normal: 'No tenderness, no step-off' },
            { label: 'Range of motion', method: 'Flex, extend, lateral bend, rotate', normal: 'Full painless range' }
          ], abnormalHints: ['Midline tenderness', 'Step-off (spondylolisthesis)', 'Limited motion with pain'] },

          { name: 'Alignment', steps: [
            { label: 'Knees', method: 'Feet together, inspect', normal: 'Neutral alignment by 6–7y' },
            { label: 'Feet', method: 'Stand, then tiptoes', normal: 'Medial arch present, symmetric' },
            { label: 'Leg lengths', method: 'Supine, measure ASIS to medial malleolus if asymmetric', normal: 'Equal within 1cm' }
          ], abnormalHints: ['Residual valgum', 'Pes cavus', 'Leg-length discrepancy >1cm'] },

          { name: 'Joint stability and sports exam (if active)', steps: [
            { label: 'Active range all joints', method: 'Through full range', normal: 'Full symmetric range, no pain or crepitus' },
            { label: 'Knee — Lachman (if sports-active)', method: 'Knee 20° flexion, stabilize femur, pull tibia forward', normal: 'Firm endpoint, no laxity' },
            { label: 'Knee — McMurray', method: 'Flexed knee, rotate tibia while extending', normal: 'No pain or click' },
            { label: 'Shoulder — impingement (Neer/Hawkins)', method: 'Passive shoulder flexion with arm in internal rotation', normal: 'No pain' },
            { label: 'Ankle stability', method: 'Anterior drawer and talar tilt', normal: 'No laxity' }
          ], abnormalHints: ['ACL laxity (positive Lachman)', 'Meniscal click', 'Shoulder impingement', 'Ankle instability'] },

          { name: 'Gait and functional movement', steps: [
            { label: 'Normal gait', method: 'Walk 20 feet', normal: 'Smooth, symmetric' },
            { label: 'Single-leg stance', method: 'Stand on one foot 10s each side', normal: 'Stable without Trendelenburg drop' },
            { label: 'Squat', method: 'Full squat and rise', normal: 'Full squat without pain or asymmetry' },
            { label: 'Hop on one foot', method: '5 hops each side', normal: 'Able and symmetric' }
          ], abnormalHints: ['Trendelenburg sign (hip abductor weakness)', 'Antalgic gait', 'Asymmetric squat', 'Pain with hop'] }
        ]
      },
      neuro: {
        overview: 'Adult-pattern six-component exam: mental status, CN, motor, reflexes, sensory, coordination/gait.',
        components: [
          { name: 'Mental status', steps: [
            { label: 'Orientation', method: 'Name, age, school, city, day of week', normal: 'Oriented x 4' },
            { label: 'Attention', method: 'Count backward from 20; days of week backward', normal: 'Intact' },
            { label: '3-item recall', method: 'Ball-flag-tree; ask at 3 and 5 min', normal: '3/3 recall at 5 min' },
            { label: 'Language', method: 'Name common objects; repeat a sentence', normal: 'Fluent, no paraphasia' }
          ], abnormalHints: ['Inattention (ADHD features)', 'Memory deficits', 'Word-finding difficulty', 'Perseveration'] },

          { name: 'Cranial nerves (II–XII)', steps: [
            { label: 'CN II — acuity', method: 'Snellen at 20ft each eye with corrective lenses if worn', normal: '20/20 or baseline' },
            { label: 'CN II — fields', method: 'Confrontation, 4 quadrants each eye', normal: 'Full fields' },
            { label: 'CN II — fundoscopy (if indicated)', method: 'Direct ophthalmoscopy — disc, vessels, macula', normal: 'Sharp disc, normal cup-disc ratio, no papilledema' },
            { label: 'CN II, III — pupils', method: 'Direct and consensual light, accommodation', normal: 'PERRLA' },
            { label: 'CN III, IV, VI — EOM', method: 'Follow finger in H pattern; convergence', normal: 'Full EOM, no nystagmus, convergence intact' },
            { label: 'CN V — sensation', method: 'Light touch V1 (forehead), V2 (cheek), V3 (jaw) each side', normal: 'Intact, symmetric' },
            { label: 'CN V — motor', method: 'Clench teeth, palpate masseter/temporalis; jaw opening', normal: 'Symmetric strength' },
            { label: 'CN VII', method: 'Raise eyebrows, close eyes tight, smile/show teeth, puff cheeks', normal: 'Symmetric movement, all regions' },
            { label: 'CN VIII', method: 'Finger rub each ear; Weber/Rinne if deficit', normal: 'Hears bilaterally' },
            { label: 'CN IX, X', method: 'Palate elevation with "ahh"; uvula midline; voice quality', normal: 'Symmetric elevation, uvula midline, normal voice' },
            { label: 'CN XI', method: 'Shrug shoulders against resistance; head turn against resistance', normal: '5/5 SCM and trapezius' },
            { label: 'CN XII', method: 'Stick tongue out; side-to-side', normal: 'Midline, no atrophy or fasciculations' }
          ], abnormalHints: ['Papilledema (increased ICP)', 'Focal cranial nerve deficit — any warrants workup', 'Tongue fasciculations (LMN/MND)'] },

          { name: 'Motor — bulk, tone, strength', steps: [
            { label: 'Bulk inspection', method: 'Shoulders, thighs, calves, intrinsic hand muscles', normal: 'Symmetric, no atrophy' },
            { label: 'Tone', method: 'Passive range at elbows, wrists, knees, ankles', normal: 'Normal resistance throughout' },
            { label: 'Strength — deltoids', method: 'Shoulder abduction against resistance', normal: '5/5 bilaterally' },
            { label: 'Strength — biceps', method: 'Elbow flexion against resistance', normal: '5/5' },
            { label: 'Strength — triceps', method: 'Elbow extension against resistance', normal: '5/5' },
            { label: 'Strength — grip', method: 'Squeeze 2 fingers', normal: '5/5 symmetric' },
            { label: 'Strength — finger abduction', method: 'Spread fingers against resistance', normal: '5/5' },
            { label: 'Strength — hip flexion', method: 'Lift leg supine against resistance', normal: '5/5' },
            { label: 'Strength — knee extension', method: 'Straighten knee against resistance', normal: '5/5' },
            { label: 'Strength — dorsiflexion', method: 'Pull toes up against resistance', normal: '5/5' },
            { label: 'Strength — plantarflexion', method: 'Push foot down against resistance', normal: '5/5' }
          ], abnormalHints: ['Focal weakness (localize)', 'Spasticity (UMN)', 'Atrophy', 'Fasciculations'] },

          { name: 'Deep tendon reflexes', steps: [
            { label: 'Biceps (C5-C6)', method: 'Thumb on tendon, strike', normal: '2+ symmetric' },
            { label: 'Triceps (C7-C8)', method: 'Strike triceps tendon', normal: '2+ symmetric' },
            { label: 'Brachioradialis (C5-C6)', method: 'Strike distal radius', normal: '2+ symmetric' },
            { label: 'Patellar (L3-L4)', method: 'Knees hanging, strike tendon', normal: '2+ symmetric' },
            { label: 'Achilles (S1)', method: 'Slight dorsiflexion, strike tendon', normal: '2+ symmetric' },
            { label: 'Plantar response', method: 'Stroke lateral sole heel-to-toes', normal: 'Down-going bilaterally' },
            { label: 'Clonus', method: 'Rapid dorsiflexion at ankle', normal: 'No sustained clonus' }
          ], abnormalHints: ['Hyperreflexia with clonus (UMN: stroke, MS, cord lesion)', 'Hyporeflexia (LMN, neuropathy, myopathy)', 'Asymmetry', 'Up-going Babinski', 'Sustained clonus'] },

          { name: 'Sensory', steps: [
            { label: 'Light touch — upper', method: 'Cotton wisp dorsum of hands, eyes closed', normal: 'Intact, symmetric' },
            { label: 'Light touch — lower', method: 'Same on dorsum of feet', normal: 'Intact, symmetric' },
            { label: 'Pain — upper', method: 'Broken Q-tip or pin on hands', normal: 'Intact, symmetric' },
            { label: 'Pain — lower', method: 'Same on feet', normal: 'Intact, symmetric' },
            { label: 'Vibration', method: '128 Hz tuning fork at distal IP joint of great toes', normal: 'Feels vibration; counts down seconds' },
            { label: 'Proprioception', method: 'Move great toe up/down with eyes closed', normal: 'Identifies direction correctly' }
          ], abnormalHints: ['Dermatomal loss (nerve root)', 'Stocking-glove (neuropathy)', 'Loss of vibration/proprioception (dorsal column — B12, tabes, MS)'] },

          { name: 'Coordination', steps: [
            { label: 'Finger-nose-finger', method: 'Touch examiner finger then own nose, examiner moves target', normal: 'Smooth, accurate, no dysmetria' },
            { label: 'Heel-to-shin', method: 'Supine: heel down opposite shin', normal: 'Smooth, on-target' },
            { label: 'Rapid alternating movements', method: 'Supinate/pronate hand on knee rapidly', normal: 'Rhythmic, symmetric' },
            { label: 'Fine motor', method: 'Finger tapping (thumb to each finger in sequence)', normal: 'Rhythmic, accurate' }
          ], abnormalHints: ['Dysmetria (past-pointing, overshoot)', 'Intention tremor', 'Dysdiadochokinesia'] },

          { name: 'Gait and Romberg', steps: [
            { label: 'Normal gait', method: 'Walk 20 feet', normal: 'Narrow-based, smooth, reciprocal arm swing' },
            { label: 'Heel walk', method: 'Walk on heels', normal: 'Able without difficulty' },
            { label: 'Toe walk', method: 'Walk on toes', normal: 'Able without difficulty' },
            { label: 'Tandem', method: 'Heel-to-toe along a line', normal: 'Minimal deviation, 10+ steps' },
            { label: 'Romberg', method: 'Feet together, eyes closed, 30s', normal: 'Stable without fall or significant sway' }
          ], abnormalHints: ['Wide-based (cerebellar)', 'Steppage (peripheral neuropathy)', 'Scissoring (UMN)', 'Romberg positive (dorsal column)', 'Circumduction'] }
        ]
      },
      resp: {
        overview: 'Nearly adult-pattern. Exam the same as adolescent with slightly more flexibility in cooperation. RR ≤ 30 in younger school-age, ≤ 20 in older. Sports history relevant (exercise-induced asthma).',
        components: [
          { name: 'Inspection',
            steps: [
              { label: 'Respiratory rate', method: 'Count over 60 s.', normal: '≤ 30 (6–11 y)' },
              { label: 'Work of breathing', method: 'Retractions, accessory muscles.', normal: 'Effortless' },
              { label: 'Audible sounds', method: 'Listen for wheeze, stridor.', normal: 'Quiet' },
              { label: 'Chest shape', method: 'Barrel chest, pectus deformities.', normal: 'Normal shape' },
              { label: 'Clubbing', method: 'Schamroth window test.', normal: 'No clubbing' }
            ],
            abnormalHints: ['Clubbing — CF, chronic hypoxemia, bronchiectasis', 'Barrel chest — chronic asthma, CF'] },
          { name: 'Palpation and percussion',
            steps: [
              { label: 'Tracheal position', method: 'Middle finger in suprasternal notch.', normal: 'Midline' },
              { label: 'Chest expansion', method: 'Hands laterally, thumbs meeting at spine. Deep breath.', normal: 'Symmetric 3–5 cm' },
              { label: 'Tactile fremitus', method: 'Ulnar side of hand; "ninety-nine". Compare sides.', normal: 'Symmetric' },
              { label: 'Percussion', method: 'Pleximeter + plexor technique. Compare sides.', normal: 'Resonant throughout' }
            ],
            abnormalHints: ['Deviated trachea — pneumothorax, effusion, collapse', 'Dull percussion — consolidation, effusion', 'Hyper-resonant — pneumothorax, hyperinflation'] },
          { name: 'Auscultation',
            steps: [
              { label: 'Systematic zones', method: 'Six anterior + four lateral + six posterior zones, compare side-to-side.', normal: 'Symmetric vesicular sounds' },
              { label: 'Adventitious sounds', method: 'Wheeze, crackles, rhonchi, rub, stridor at neck. Use sounds library for reference.', normal: 'No added sounds' },
              { label: 'Cough re-listen', method: 'Secretions (rhonchi, coarse crackles) should clear; fibrosis crackles do not.', normal: 'Secretion-based sounds clear with cough' }
            ],
            abnormalHints: ['Focal crackles + fever — pneumonia', 'Diffuse fine crackles — early interstitial disease', 'Expiratory wheeze — asthma / RAD'] }
        ]
      },
      cv: {
        overview: 'Nearly adult-pattern. Sports participation screening is a key indication in this age. HOCM screening (family history of sudden cardiac death, exertional syncope, murmur louder with Valsalva) is specifically relevant.',
        components: [
          { name: 'Inspection and palpation',
            pearl: 'For sports participation exams, always ask about exertional symptoms (syncope, chest pain, unexpected fatigue) AND family history of sudden cardiac death before age 50. Screening exam alone catches only ~3% of HOCM.',
            steps: [
              { label: 'General and growth', method: 'Track on growth curve; review activity tolerance.', normal: 'Normal growth, age-appropriate activity' },
              { label: 'Colour and clubbing', method: 'Inspect mucous membranes and nail beds.', normal: 'Pink, no clubbing' },
              { label: 'Apex beat', method: 'Palpate at 5th ICS mid-clavicular line.', normal: 'Normal position, tapping character' },
              { label: 'Peripheral pulses', method: 'Simultaneous brachial + femoral.', normal: 'Symmetric, no delay' },
              { label: 'Blood pressure', method: 'Measure BP with appropriately sized cuff. If elevated, check both arms and one leg.', normal: 'Age-appropriate (< 120/80 roughly by 10+ years)' }
            ],
            abnormalHints: ['Exertional syncope — HOCM, arrhythmia, LQTS', 'BP differential — coarctation', 'Displaced apex — cardiomegaly'] },
          { name: 'Auscultation',
            steps: [
              { label: 'All 5 classic points', method: 'See APTM diagram. A → P → E → T → M with diaphragm and bell.', normal: 'S1, S2 clear with physiologic split at P, no added sounds' },
              { label: 'Grade any murmur', method: 'Levine 1–6 (see scales above); characterise timing, location, radiation.', normal: 'No murmur, or innocent flow murmur meeting all 7 S criteria' },
              { label: 'Innocent vs pathologic', method: 'Apply 7 S criteria; compare to innocent-murmur panel.', normal: 'Innocent murmur (if present) clearly fits all 7 S features' },
              { label: 'Dynamic maneuvers', method: 'Standing: HOCM louder; most others soften. Valsalva: HOCM louder.', normal: 'Murmur (if any) softens on standing and Valsalva' }
            ],
            abnormalHints: ['Murmur louder with Valsalva / standing — HOCM (sports disqualification considerations)', 'Any diastolic murmur', 'Murmur ≥ grade 3, radiating, or with thrill'] }
        ]
      }
    },

    adolescent: {
      label: 'Adolescent (12–21 years)',
      msk: {
        overview: 'Sports-related injuries, adolescent scoliosis, apophyseal overuse, hypermobility screening.',
        components: [
          { name: 'Scoliosis screen', steps: [
            { label: 'Standing inspection', method: 'Patient undressed to waist (keep privacy); compare shoulders, iliac crests, scapular heights', normal: 'Symmetric shoulders and pelvis' },
            { label: 'Forward bend (Adam)', method: 'Feet together, bend forward, arms hanging palms together', normal: 'Symmetric paraspinal contour' },
            { label: 'Scoliometer', method: 'Place across thoracic and lumbar regions at maximum prominence', normal: 'ATR <5°; 5–6° monitor; ≥7° refer' },
            { label: 'Plumb line check', method: 'Drop plumb from C7; note where it falls', normal: 'Passes through gluteal cleft (compensated)' },
            { label: 'Leg lengths', method: 'Supine; ASIS to medial malleolus each side', normal: 'Within 1cm' }
          ], abnormalHints: ['Rib/lumbar hump', 'ATR ≥7°', 'Decompensation (plumb off gluteal cleft)', 'Leg-length discrepancy driving apparent curve'] },

          { name: 'Back pain evaluation (if complaint)', steps: [
            { label: 'Inspect and palpate', method: 'Spinous processes, paraspinal muscles, SI joints', normal: 'Non-tender' },
            { label: 'Range of motion', method: 'Flex, extend, lateral bend, rotate', normal: 'Full painless range' },
            { label: 'Single-leg hyperextension (stork)', method: 'Stand on one foot, extend back — each side', normal: 'No pain (negative for spondylolysis)' },
            { label: 'Straight-leg raise', method: 'Supine, lift straight leg to 70°+', normal: 'No radicular pain to 70°' },
            { label: 'SI joint tests', method: 'FABER, SI compression', normal: 'No pain' }
          ], abnormalHints: ['Spondylolysis (positive stork test)', 'Radicular pain (disc herniation)', 'SI joint pathology', 'Inflammatory back pain pattern'] },

          { name: 'Joint stability — sports-specific', steps: [
            { label: 'Knee — Lachman', method: 'Knee 20° flexion, stabilize femur, pull tibia anteriorly', normal: 'Firm endpoint, no laxity (ACL intact)' },
            { label: 'Knee — anterior drawer', method: 'Knee 90°, pull tibia forward', normal: 'No excess anterior translation' },
            { label: 'Knee — varus/valgus stress', method: 'Stress at 0 and 30° flexion', normal: 'No gap opening (LCL/MCL intact)' },
            { label: 'Knee — McMurray', method: 'Flex, rotate tibia while extending', normal: 'No pain or click' },
            { label: 'Shoulder — apprehension', method: 'Abduct and externally rotate', normal: 'No apprehension' },
            { label: 'Shoulder — Neer/Hawkins', method: 'Passive flexion with internal rotation', normal: 'No pain' },
            { label: 'Ankle — anterior drawer', method: 'Pull heel forward with tibia stabilized', normal: 'No laxity' },
            { label: 'Ankle — talar tilt', method: 'Invert heel with tibia stabilized', normal: 'No excess tilt' }
          ], abnormalHints: ['ACL/PCL tear', 'MCL/LCL laxity', 'Meniscal injury', 'Shoulder instability/impingement', 'Ankle ligament laxity'] },

          { name: 'Apophysitis and overuse screen', steps: [
            { label: 'Tibial tubercle', method: 'Palpate with knee flexed', normal: 'Non-tender' },
            { label: 'Calcaneal apophysis', method: 'Palpate posterior calcaneus', normal: 'Non-tender' },
            { label: 'Iliac apophyses', method: 'Palpate ASIS, AIIS, iliac crest', normal: 'Non-tender' },
            { label: 'Rotator cuff', method: 'Empty-can (Jobe) test', normal: 'No pain or weakness' }
          ], abnormalHints: ['Osgood-Schlatter (tibial tubercle tender)', 'Sever (calcaneal tender)', 'Iliac apophysitis', 'Rotator cuff tendinopathy'] },

          { name: 'Hypermobility screen (Beighton)', steps: [
            { label: 'Fifth finger extension', method: 'Passive extension of fifth MCP to >90°', normal: 'No hyperextension (1 pt each side if positive)' },
            { label: 'Thumb to forearm', method: 'Passive flexion of thumb to touch forearm', normal: 'Does not reach (1 pt each side if positive)' },
            { label: 'Elbow hyperextension', method: 'Hyperextension >10°', normal: 'No hyperextension (1 pt each side if positive)' },
            { label: 'Knee hyperextension', method: 'Hyperextension >10°', normal: 'No hyperextension (1 pt each side if positive)' },
            { label: 'Palms to floor', method: 'Feet together, bend forward, palms flat on floor with knees straight', normal: 'Cannot reach (1 pt if positive)' }
          ], abnormalHints: ['Beighton ≥5/9 suggests hypermobility spectrum (hEDS workup if with other features)'] },

          { name: 'Alignment and gait', steps: [
            { label: 'Standing alignment', method: 'View knees, feet', normal: 'Neutral alignment, medial arch' },
            { label: 'Normal gait', method: 'Walk 20 feet', normal: 'Symmetric, smooth' },
            { label: 'Functional movements', method: 'Squat, single-leg stance, hop', normal: 'Full symmetric function' }
          ], abnormalHints: ['Antalgic gait', 'Trendelenburg', 'Asymmetric squat'] }
        ]
      },
      neuro: {
        overview: 'Full adult-pattern neuro exam across six pillars: mental status, cranial nerves, motor, reflexes, sensory, coordination/gait. In adolescents, screen concussion sequelae if sports-active; frontal release signs must be absent.',
        components: [
          { name: 'Mental status',
            significance: 'Detects cognitive change (concussion, substance use, mood disorder, rare neurodegenerative disease).',
            pearl: 'Attention precedes memory. A patient who can\'t attend (serial 7s, months backward) will fail memory even with intact hippocampus — distinguish before calling it a memory problem.',
            steps: [
            { label: 'Orientation', method: 'Name, age, date, location, situation', normal: 'Oriented x 4' },
            { label: 'Attention', method: 'Count backward from 100 by 7s (serial 7s) or months of year backward', normal: 'Intact' },
            { label: 'Short-term memory', method: '3-item registration and recall at 5 min', normal: '3/3 recall' },
            { label: 'Language', method: 'Object naming; sentence repetition; reading; writing', normal: 'Fluent, no paraphasia, comprehends written and spoken' },
            { label: 'Executive function', method: 'Similarities (apple/orange); interpret proverb', normal: 'Abstract, age-appropriate' }
          ], abnormalHints: ['Post-concussion cognitive changes', 'Mood or personality changes', 'Subtle executive dysfunction', 'Word-finding difficulty'] },

          { name: 'Cranial nerves (II–XII, full formal exam)',
            significance: 'Localises brainstem, base-of-skull, and specific nerve pathology. Subtle deficits (RAPD, mild facial weakness, Horner) are easily missed — exam discipline matters.',
            pearl: 'The fastest screen for a CN deficit is asking the patient to speak, smile, look around, and swallow water. What\'s preserved in everyday function tells you what\'s likely intact — then examine formally to confirm and to catch the subtle.',
            steps: [
            { label: 'CN I (if indicated)', method: 'Coffee or cinnamon each nostril separately', normal: 'Identifies both' },
            { label: 'CN II — acuity', method: 'Snellen at 20ft each eye; corrective lenses if worn', normal: '20/20 or baseline' },
            { label: 'CN II — fields', method: 'Confrontation, 4 quadrants each eye', normal: 'Full fields' },
            { label: 'CN II — fundoscopy', method: 'Direct ophthalmoscopy — disc, vessels, macula', normal: 'Sharp disc, normal cup/disc, no papilledema' },
            { label: 'CN II, III — pupils', method: 'Direct, consensual, swinging flashlight, accommodation', normal: 'PERRLA, no RAPD' },
            { label: 'CN III, IV, VI — EOM', method: 'H pattern, convergence, note nystagmus or ptosis', normal: 'Full conjugate movement, no nystagmus, convergence intact' },
            { label: 'CN V — sensation', method: 'Light touch V1, V2, V3 each side', normal: 'Intact, symmetric' },
            { label: 'CN V — motor', method: 'Clench jaw, palpate masseter/temporalis; lateral jaw movement', normal: 'Symmetric strength and bulk' },
            { label: 'CN V — corneal reflex (if indicated)', method: 'Cotton wisp to cornea', normal: 'Blinks bilaterally' },
            { label: 'CN VII', method: 'Wrinkle forehead, close eyes against resistance, smile/bare teeth, puff cheeks', normal: 'Symmetric all four movements' },
            { label: 'CN VIII — hearing', method: 'Finger rub each ear; Weber (midline) + Rinne (air > bone) if deficit', normal: 'Equal bilaterally' },
            { label: 'CN IX, X', method: 'Palate elevation with "ahh"; uvula midline; voice; gag (if indicated)', normal: 'Symmetric palate, uvula midline, normal voice' },
            { label: 'CN XI', method: 'Shoulder shrug and head turn against resistance', normal: '5/5 SCM and trapezius bilaterally' },
            { label: 'CN XII', method: 'Tongue protrusion, side to side; inspect for fasciculations/atrophy', normal: 'Midline, no atrophy or fasciculations, full movement' }
          ], abnormalHints: ['Any focal cranial nerve deficit', 'Papilledema', 'RAPD', 'Nystagmus', 'Facial asymmetry', 'Tongue deviation'] },

          { name: 'Motor — bulk, tone, strength',
            significance: 'Localises lesion to UMN vs LMN vs muscle vs junction. Pattern of weakness (proximal vs distal, symmetric vs focal) narrows differential.',
            pearl: 'Pronator drift is the most sensitive screen for subtle UMN weakness — a normal-feeling arm that drifts down with eyes closed still has corticospinal tract dysfunction. Always do it even when formal strength is 5/5.',
            steps: [
            { label: 'Bulk inspection', method: 'Inspect shoulders, biceps, thighs, calves, dorsal interossei (between metacarpals) of hands.', normal: 'Symmetric bulk; no atrophy, no pseudohypertrophy' },
            { label: 'Tone — upper', method: 'Passive flex-extend elbow and pronate-supinate wrist at slow then quick speeds. Then pronator drift: arms outstretched, palms up, eyes closed for 10 s.', normal: 'Smooth passive range; no drift, no pronation of the outstretched hand' },
            { label: 'Tone — lower', method: 'Passive knee flexion-extension; quick ankle dorsiflexion to check for catch. Heel-slap test: roll thigh and watch for ankle swing.', normal: 'Normal resistance, no catch, symmetric' },
            { label: 'Strength — deltoid (C5)',            method: 'Patient abducts both arms to 90°. Examiner pushes down on each arm just above the elbow while patient resists. Compare sides.', normal: 'Holds against full resistance — MRC 5/5 bilaterally' },
            { label: 'Strength — biceps (C5–C6)',          method: 'Elbow flexed 90°, supinated. Examiner grasps wrist and pulls to extend while patient resists.', normal: 'Holds against full resistance — 5/5' },
            { label: 'Strength — triceps (C7)',            method: 'Elbow flexed 90°. Examiner pushes wrist toward shoulder while patient extends against resistance.', normal: 'Extends against full resistance — 5/5' },
            { label: 'Strength — wrist extension (C6–C7)', method: 'Patient makes fist, extends wrist. Examiner pushes down on knuckles while patient holds wrist up.', normal: 'Holds against full resistance — 5/5' },
            { label: 'Strength — finger flexion / grip (C8)', method: 'Patient grips two of examiner\'s crossed fingers as hard as possible. Compare sides.', normal: 'Strong symmetric grip — 5/5' },
            { label: 'Strength — finger abduction (T1)',   method: 'Patient spreads fingers wide. Examiner squeezes index and little fingers together while patient resists.', normal: 'Holds fingers apart — 5/5' },
            { label: 'Strength — hip flexion (L2–L3)',     method: 'Supine. Patient lifts straight leg 30° off table. Examiner pushes down on thigh just above knee while patient resists.', normal: 'Holds thigh up against full resistance — 5/5' },
            { label: 'Strength — knee extension (L3–L4)',  method: 'Sitting, knee 90°. Patient straightens knee while examiner pushes distal shin down.', normal: 'Extends against full resistance — 5/5' },
            { label: 'Strength — ankle dorsiflexion (L4–L5)', method: 'Patient pulls toes and foot up toward shin. Examiner pushes foot down at the dorsum.', normal: 'Holds dorsiflexion against full resistance — 5/5; preserved heel-walk' },
            { label: 'Strength — great toe extension (L5)', method: 'Patient extends great toe up while examiner pushes it down with thumb.', normal: 'Holds against full resistance — 5/5 (classic L5 test)' },
            { label: 'Strength — ankle plantarflexion (S1)', method: 'Patient pushes foot down against examiner\'s hand at the ball. OR ask patient to toe-walk 10 steps (more sensitive — unilateral plantarflexion weakness shows immediately).', normal: 'Full power; toe-walks symmetrically — 5/5' }
          ], abnormalHints: ['Focal weakness → localise by myotome', 'Pronator drift (subtle UMN, always check even with 5/5)', 'Spasticity / catch (UMN)', 'Atrophy (LMN, disuse)', 'Fasciculations (MND, ALS)', 'Pseudohypertrophy of calves (DMD in a young male)'] },

          { name: 'Deep tendon reflexes',
            significance: 'Reflex pattern (increased, decreased, asymmetric) localises UMN vs LMN vs root vs peripheral nerve. Inexpensive and fast, but asymmetry is the most informative finding.',
            pearl: 'A reinforced reflex is still a reflex. If you can\'t elicit it initially, use Jendrassik (teeth clench or pull interlocked fingers apart) to boost — absent reflexes without reinforcement aren\'t truly absent.',
            steps: [
            { label: 'Biceps (C5–C6)', method: 'Patient\'s arm relaxed across lap. Examiner places thumb firmly on biceps tendon at the cubital fossa, strikes thumb with reflex hammer. Compare both sides sequentially.', normal: '2+ symmetric — visible contraction of biceps, slight elbow flexion' },
            { label: 'Brachioradialis (C5–C6)', method: 'Arm relaxed. Strike the distal radius about 3 cm proximal to the wrist, on its radial (thumb) side.', normal: '2+ symmetric — elbow flexion and slight forearm supination' },
            { label: 'Triceps (C7)', method: 'Support the patient\'s arm at the wrist with elbow at 90°. Strike the triceps tendon just above the olecranon.', normal: '2+ symmetric — triceps contraction, slight elbow extension' },
            { label: 'Finger flexors — Hoffmann sign', method: 'Grasp the middle finger\'s distal phalanx, flick it downward quickly and release. Watch the thumb and index finger.', normal: 'Negative — no thumb flexion, no index flexion (positive = corticospinal tract dysfunction)' },
            { label: 'Patellar (L3–L4)', method: 'Patient sits with knees hanging freely off the table. Strike the patellar tendon just below the patella.', normal: '2+ symmetric — quadriceps contraction with knee extension' },
            { label: 'Achilles (S1)', method: 'Patient\'s knee slightly flexed and leg externally rotated, or kneeling on a chair. Slightly dorsiflex the foot and strike the Achilles tendon.', normal: '2+ symmetric — plantar flexion of the foot' },
            { label: 'Plantar response (Babinski)', method: 'Stroke the lateral aspect of the sole firmly from the heel toward the little toe, then curve across the ball of the foot.', normal: 'Toes flex downward (plantar flexion, "down-going") bilaterally in anyone ≥ 2 years' },
            { label: 'Ankle clonus', method: 'Knee slightly bent. Support the shin with one hand, quickly and sharply dorsiflex the foot with the other, hold in dorsiflexion.', normal: '≤ 3 non-sustained beats is acceptable; sustained rhythmic oscillation = pathological clonus (UMN)' }
          ], abnormalHints: ['Hyperreflexia + sustained clonus = UMN (MS, myelopathy, cord lesion, stroke)', 'Symmetric hyporeflexia = peripheral polyneuropathy, GBS, myopathy, hypothyroid, B12 deficiency', 'Asymmetric hyporeflexia = radiculopathy at that segment', 'Hoffmann positive = corticospinal tract dysfunction at cervical cord or above', 'Up-going Babinski after age 2 = UMN (always abnormal)'] },

          { name: 'Sensory', steps: [
            { label: 'Light touch — upper', method: 'Cotton wisp, dorsum of hands, eyes closed', normal: 'Intact, symmetric' },
            { label: 'Light touch — lower', method: 'Dorsum of feet', normal: 'Intact, symmetric' },
            { label: 'Pain — upper', method: 'Broken Q-tip sharp end, hands', normal: 'Intact, symmetric' },
            { label: 'Pain — lower', method: 'Same on feet', normal: 'Intact, symmetric' },
            { label: 'Temperature (if indicated)', method: 'Cold tuning fork each area', normal: 'Intact' },
            { label: 'Vibration', method: '128 Hz tuning fork at distal IP of great toes; count seconds to fade', normal: 'Feels vibration; appropriate duration' },
            { label: 'Proprioception', method: 'Move great toe up/down with eyes closed', normal: 'Identifies direction correctly' },
            { label: 'Two-point discrimination (if indicated)', method: 'Blunt calipers on fingertip', normal: '<5mm on fingertip' },
            { label: 'Stereognosis (if indicated)', method: 'Identify coin/key in hand with eyes closed', normal: 'Correct identification' }
          ], abnormalHints: ['Dermatomal loss (nerve root)', 'Stocking-glove loss (length-dependent neuropathy)', 'Dorsal column loss (B12, tabes, MS — positive Romberg, vibration loss)', 'Cortical deficit (astereognosis, impaired 2-pt)'] },

          { name: 'Coordination', steps: [
            { label: 'Finger-nose-finger', method: 'Alternate examiner\'s finger and own nose; examiner moves target', normal: 'Smooth, accurate bilaterally' },
            { label: 'Heel-to-shin', method: 'Supine: heel down opposite shin and back', normal: 'Smooth, accurate' },
            { label: 'Rapid alternating (Dysdiadochokinesis)', method: 'Supinate/pronate hand rapidly on thigh', normal: 'Rhythmic, symmetric' },
            { label: 'Finger tapping', method: 'Thumb to each finger in sequence rapidly', normal: 'Rhythmic, smooth, symmetric' }
          ], abnormalHints: ['Dysmetria (cerebellar)', 'Intention tremor', 'Dysdiadochokinesia', 'Decomposed movement'] },

          { name: 'Gait and Romberg', steps: [
            { label: 'Normal gait', method: 'Walk 20 feet', normal: 'Narrow-based, smooth, reciprocal arm swing' },
            { label: 'Heel walk', method: 'Walk on heels only', normal: 'Able without difficulty' },
            { label: 'Toe walk', method: 'Walk on toes only', normal: 'Able without difficulty' },
            { label: 'Tandem', method: 'Heel-to-toe along a line, 10+ steps', normal: 'Minimal deviation' },
            { label: 'Romberg', method: 'Feet together, eyes open then closed, 30s', normal: 'Stable — no significant sway or fall with eyes closed' },
            { label: 'Single-leg stance', method: '10s each side, eyes open', normal: 'Stable without drift' }
          ], abnormalHints: ['Ataxic (wide-based — cerebellar)', 'Steppage (peripheral neuropathy / foot drop)', 'Circumduction (UMN hemiparesis)', 'Scissoring', 'Romberg positive (dorsal column)'] },

          { name: 'Frontal release / primitive reflexes', steps: [
            { label: 'Grasp reflex', method: 'Stroke palm', normal: 'Absent' },
            { label: 'Snout reflex', method: 'Tap upper lip', normal: 'No lip pucker' },
            { label: 'Glabellar tap', method: 'Tap between eyebrows — should habituate after 3–4 taps', normal: 'Habituates (no sustained blink)' },
            { label: 'Palmomental', method: 'Stroke thenar eminence', normal: 'No ipsilateral chin twitch' }
          ], abnormalHints: ['Presence suggests frontal lobe pathology, neurodegenerative disease, or severe TBI — rare in adolescence but relevant in post-concussion workup'] }
        ]
      },
      resp: {
        overview: 'Systematic respiratory exam: inspection → palpation → percussion → auscultation → special maneuvers. Always start from observation — rate, pattern, work of breathing, and audible sounds (stridor, grunting) can be diagnostic before the stethoscope touches the chest.',
        components: [
          { name: 'Inspection — observation before touching',
            significance: 'Detects respiratory distress and localises the level of airway compromise before any equipment is used. High yield: RR, WOB, audible sounds, chest shape, colour.',
            pearl: 'Audible stridor at rest from across the room = upper-airway obstruction, often urgent. Grunting in an infant = significant distress — never dismiss as fussiness.',
            steps: [
              { label: 'Respiratory rate', method: 'Count over a full 60 seconds (not 15×4) — children normally breathe irregularly. Count while the patient is calm, before any interaction.', normal: 'Within age-appropriate range (see scales card above)' },
              { label: 'Respiratory pattern', method: 'Observe depth, regularity, and inspiration:expiration ratio. Watch for prolonged expiration, paradoxical chest-abdominal movement, or apneas.', normal: 'Regular, I:E ratio ~1:2, no pauses > 10 s in an infant' },
              { label: 'Work of breathing', method: 'Inspect for nasal flaring, suprasternal/intercostal/subcostal retractions, accessory muscle use (SCM, abdominals), tripod positioning, head-bobbing in infants.', normal: 'No retractions; breathing effortless' },
              { label: 'Audible sounds (no stethoscope)', method: 'Listen at the bedside without the stethoscope. Grunting? Stridor? Wheezing audible across the room? Hoarse voice?', normal: 'No audible stridor, grunting, or wheeze' },
              { label: 'Chest shape and symmetry', method: 'Inspect from front and lateral. Note AP-to-transverse diameter, pectus excavatum/carinatum, chest wall asymmetry.', normal: 'AP:transverse ~1:2 (not barrel-chested); symmetric' },
              { label: 'Colour and perfusion', method: 'Inspect lips, tongue, nail beds for central cyanosis. Check peripheral perfusion (capillary refill, mottling).', normal: 'Pink, cap refill < 2 s, no cyanosis' },
              { label: 'Clubbing', method: 'Inspect fingernails: Schamroth sign (reverse a finger against its mirror — normal forms a diamond-shaped window, clubbed does not).', normal: 'Normal nail angle, Schamroth window present' }
            ],
            abnormalHints: ['Audible stridor — upper airway (croup, epiglottitis, foreign body, laryngomalacia)', 'Grunting in infant — significant distress', 'Tripod positioning, accessory muscle use — severe distress', 'Barrel chest — chronic air-trapping (asthma, CF)', 'Central cyanosis — significant hypoxemia', 'Clubbing in a child — cystic fibrosis, chronic hypoxemia, bronchiectasis, cyanotic CHD'] },

          { name: 'Palpation',
            significance: 'Localises pathology: consolidation increases tactile fremitus; pneumothorax/effusion decreases it. Trachea deviates AWAY from expanding lesions and TOWARD collapsing ones.',
            pearl: 'Tracheal deviation is one of the fastest bedside clues to mediastinal shift — tension pneumothorax pushes it away, lobar collapse pulls it toward. Palpate with the middle finger in the suprasternal notch.',
            steps: [
              { label: 'Tracheal position', method: 'Patient sitting upright, neck slightly extended. Place middle finger in the suprasternal notch, check equal distance to each SCM.', normal: 'Midline' },
              { label: 'Chest expansion — symmetry', method: 'Hands on lateral chest wall with thumbs meeting at the spine (posterior) or xiphoid (anterior). Patient takes a deep breath. Watch thumbs separate symmetrically.', normal: 'Symmetric 3–5 cm separation' },
              { label: 'Tactile fremitus', method: 'Ulnar surface of hand on chest wall. Ask patient to say "ninety-nine" repeatedly. Move hand systematically across each zone, comparing sides.', normal: 'Equal mild vibration bilaterally over lung fields' },
              { label: 'Chest wall tenderness', method: 'Palpate ribs, costochondral junctions, sternum, and intercostal spaces.', normal: 'No tenderness' },
              { label: 'Subcutaneous emphysema', method: 'Gentle palpation along clavicles, neck, chest wall.', normal: 'No crepitus under skin' }
            ],
            abnormalHints: ['Tracheal deviation — tension pneumothorax, large pleural effusion (away); upper lobe collapse (toward)', 'Asymmetric expansion — pneumothorax, large effusion, lobar collapse, phrenic palsy', 'Increased fremitus — consolidation (pneumonia), lobar pneumonia', 'Decreased/absent fremitus — pleural effusion, pneumothorax, obstruction', 'Costochondral tenderness — costochondritis, trauma', 'Subcutaneous emphysema — pneumothorax, tracheobronchial injury'] },

          { name: 'Percussion',
            significance: 'Differentiates air (hyper-resonant), fluid (dull), and consolidated lung (dull) without imaging. Well-performed percussion detects a pleural effusion > 300 mL or a pneumothorax with ~90% sensitivity.',
            pearl: 'Pleximeter fingertip must be flat against the chest wall — lift other fingers off. The "feel" of a percussion note is as informative as the sound: dullness has a dense, reflected quality; hyper-resonance feels hollow and springy.',
            steps: [
              { label: 'Technique', method: 'Place middle finger of non-dominant hand (pleximeter) flat on chest wall; strike distal IP joint with tip of dominant middle finger (plexor) using a quick wrist flick.', normal: 'N/A — technique step' },
              { label: 'Systematic zones', method: 'Percuss from apex to base, comparing side-to-side at each level. Include anterior, lateral (mid-axillary), and posterior fields.', normal: 'Resonant throughout lung fields' },
              { label: 'Cardiac dullness', method: 'Percuss from resonant lung toward the heart border. Left sternal border dullness starts at the 3rd–5th ICS.', normal: 'Dullness beginning at the expected cardiac border' },
              { label: 'Hepatic dullness', method: 'Right 5th–6th ICS mid-clavicular line transitions from resonant to dull.', normal: 'Liver edge dullness at expected level' },
              { label: 'Diaphragmatic excursion', method: 'Patient inhales fully then exhales fully; mark level of dullness at each end. Difference is diaphragm excursion.', normal: '3–5 cm excursion bilaterally' }
            ],
            abnormalHints: ['Hyper-resonant — pneumothorax, emphysematous bulla, severe asthma attack', 'Dull — consolidation, pleural effusion (stony dull), atelectasis, pleural thickening, large mass', 'Raised diaphragm (loss of excursion) — effusion, paralysis, subdiaphragmatic pathology'] },

          { name: 'Auscultation — normal breath sounds',
            significance: 'Breath sound quality varies by location. Bronchial sounds heard peripherally = consolidation; absent breath sounds = pneumothorax, effusion, obstruction.',
            pearl: 'Always compare corresponding points side-to-side sequentially — your ear calibrates to "normal" one side and immediately hears asymmetry. Listen through a full respiratory cycle at each zone.',
            steps: [
              { label: 'Technique', method: 'Diaphragm of stethoscope directly on skin (not over clothing). Patient breathes slowly and deeply through an open mouth.', normal: 'N/A — technique' },
              { label: 'Vesicular sounds (peripheral)', method: 'Listen over lung fields away from the sternum. Play the "Normal vesicular" sample above for reference.', normal: 'Soft, low-pitched, inspiration > expiration in length and loudness' },
              { label: 'Bronchovesicular (over main bronchi)', method: 'Listen at the 1st–2nd ICS anteriorly and between scapulae posteriorly.', normal: 'Intermediate pitch, inspiration = expiration' },
              { label: 'Bronchial (over trachea)', method: 'Listen directly over the manubrium or trachea.', normal: 'Harsh, high-pitched, expiration > inspiration' },
              { label: 'Systematic comparison', method: 'Six zones anteriorly (upper/mid/lower × L/R), four lateral, six posterior. Compare side-to-side at each zone.', normal: 'Symmetric breath sounds at every paired zone' }
            ],
            abnormalHints: ['Bronchial sounds heard peripherally — consolidation (pneumonia)', 'Absent/diminished breath sounds — pneumothorax, effusion, severe obstruction, obesity / muscular chest', 'Prolonged expiration — lower airway obstruction (asthma, bronchiolitis)'] },

          { name: 'Auscultation — adventitious sounds',
            significance: 'Adventitious (added) sounds are the key diagnostic finding. Timing (inspiratory vs expiratory vs biphasic), character (continuous vs discontinuous), and location are all informative.',
            pearl: 'Ask the patient to cough and re-listen. Secretions (rhonchi, some coarse crackles) clear or change; fine crackles of fibrosis or early pneumonia do not. The cough test separates two differential groups in one maneuver.',
            steps: [
              { label: 'Listen for wheeze', method: 'Continuous musical sounds, typically expiratory. Use the "Wheeze" sample for reference.', normal: 'No wheeze' },
              { label: 'Listen for crackles — fine', method: 'Short, high-pitched, discontinuous "Velcro" sounds. Typically end-inspiratory, bibasilar. Use the "Fine crackles" sample.', normal: 'No crackles' },
              { label: 'Listen for crackles — coarse', method: 'Longer, lower-pitched, louder than fine. Use the "Coarse crackles" sample.', normal: 'No crackles' },
              { label: 'Listen for rhonchi', method: 'Low-pitched, continuous, snore-like. Often change with cough. Use the "Rhonchi" sample.', normal: 'No rhonchi' },
              { label: 'Listen for pleural rub', method: 'Grating, creaky, biphasic, does NOT clear with cough. Use the "Pleural rub" sample.', normal: 'No pleural rub' },
              { label: 'Listen at the neck (for stridor)', method: 'Place stethoscope over the anterior neck. Stridor is loudest here and differentiates from wheeze (loudest over chest). Use the "Stridor" sample.', normal: 'No stridor' },
              { label: 'Listen for expiratory grunting (infants)', method: 'Often audible without a stethoscope at the bedside — short, low-pitched sound at the end of each expiration (glottal closure against exhaled air).', normal: 'No grunting' },
              { label: 'Cough re-listen', method: 'Have patient cough forcefully; re-listen to any abnormal area. Note if the sound clears or changes.', normal: 'Any secretion-based sound should clear or change with cough' }
            ],
            abnormalHints: ['Wheeze — asthma, bronchiolitis, foreign body (localised), anaphylaxis', 'Fine crackles — pulmonary edema, interstitial lung disease, early pneumonia', 'Coarse crackles — bronchitis, pneumonia, bronchiectasis, aspiration', 'Rhonchi — large-airway secretions', 'Pleural rub — pleurisy, PE, pneumonia with pleural involvement', 'Stridor — upper airway obstruction (croup, epiglottitis, FB)'] },

          { name: 'Special maneuvers — transmitted voice sounds',
            significance: 'Vocal resonance tests detect consolidation (increased transmission) and effusion/pneumothorax (decreased). Useful when auscultation suggests asymmetry.',
            pearl: 'Whispered pectoriloquy is the most sensitive of the three — whispered words transmitted clearly through consolidated lung. If "one, two, three" whispered becomes clearly audible over one lung zone, there is consolidation underneath.',
            steps: [
              { label: 'Bronchophony', method: 'Patient says "ninety-nine" in normal voice. Listen at each lung zone with the stethoscope.', normal: 'Muffled, indistinct sound' },
              { label: 'Egophony', method: 'Patient says "ee" continuously. Listen over any suspicious area.', normal: '"Ee" sounds like "ee" (no change)' },
              { label: 'Whispered pectoriloquy', method: 'Patient whispers "one, two, three" or "ninety-nine". Listen over each zone.', normal: 'Whisper is faint and indistinct' }
            ],
            abnormalHints: ['Bronchophony increased — consolidation', 'Egophony positive ("ee" → "A" / "ay") — consolidation, sometimes top of an effusion', 'Whispered pectoriloquy positive (whisper clearly audible) — consolidation'] }
        ]
      },
      cv: {
        overview: 'Systematic cardiovascular exam: inspection → palpation → auscultation at the five classic points → peripheral vascular exam. Always palpate the apex BEFORE auscultating — knowing where the apex lies tells you where to put the stethoscope and flags cardiomegaly immediately.',
        components: [
          { name: 'Inspection',
            significance: 'Detects obvious precordial activity, chest-wall signs of congenital heart disease, and systemic markers (cyanosis, clubbing, dysmorphic features).',
            pearl: 'Clubbing + central cyanosis in a well-appearing adolescent = cyanotic congenital heart disease until proven otherwise. Inspect the fingernails before reaching for the stethoscope.',
            steps: [
              { label: 'General appearance', method: 'Observe body habitus, features suggesting syndromic CHD (Turner, Down, Marfan, Williams).', normal: 'No dysmorphic features, appropriate growth' },
              { label: 'Central cyanosis', method: 'Inspect lips, tongue, and oral mucosa for bluish discoloration.', normal: 'Pink oral mucosa, no cyanosis' },
              { label: 'Peripheral cyanosis / clubbing', method: 'Inspect nail beds; do Schamroth\'s window (oppose nails of 4th fingers — normally forms a diamond-shaped window).', normal: 'Pink nail beds, Schamroth window present' },
              { label: 'Precordial bulge', method: 'Inspect anterior chest wall tangentially for asymmetric prominence over the heart.', normal: 'Symmetric chest, no bulge' },
              { label: 'Visible apex beat', method: 'Inspect for a visible cardiac impulse at the 5th ICS mid-clavicular line.', normal: 'Apex may be visible in thin patients; should not be displaced' },
              { label: 'Neck veins (JVP)', method: 'Patient reclined 45°, head turned slightly left. Observe the right internal jugular pulsation; measure vertical height above the sternal angle.', normal: '≤ 4 cm above sternal angle (≤ 9 cm H₂O from right atrium)' }
            ],
            abnormalHints: ['Central cyanosis — right-to-left shunt, severe hypoxemia', 'Clubbing — cyanotic CHD, chronic hypoxemia', 'Precordial bulge — long-standing cardiomegaly (grew during skeletal growth)', 'Visible apex displaced lateral/inferior — cardiomegaly', 'Elevated JVP — right-heart failure, fluid overload, cardiac tamponade'] },

          { name: 'Palpation',
            significance: 'Localises the apex (confirms cardiac size), detects thrills (loud murmurs), and identifies a parasternal heave (RV hypertrophy).',
            pearl: 'If you feel a thrill, the murmur is at least grade 4/6 — grade your murmur as ≥4 even if it sounds less impressive. Thrill = loud, palpable turbulence.',
            steps: [
              { label: 'Apex beat — localise', method: 'Feel with the tips of the fingers at the 5th ICS mid-clavicular line. If not found, roll the patient to the left lateral decubitus position.', normal: 'Located at 5th ICS, mid-clavicular line, less than 2 cm in diameter' },
              { label: 'Apex character', method: 'Describe: tapping (normal), heaving (pressure overload, e.g. AS/HTN), thrusting (volume overload, e.g. AR/MR), dyskinetic (MI/aneurysm).', normal: 'Brief tapping quality' },
              { label: 'Parasternal heave', method: 'Place the heel of the hand along the left sternal border. Sustained outward movement with each systole = heave.', normal: 'No heave' },
              { label: 'Thrills', method: 'Use the palmar aspect of the hand at each of the 5 auscultation areas (A, P, E, T, M). A thrill = palpable turbulence.', normal: 'No thrills' },
              { label: 'Peripheral pulses — upper', method: 'Palpate radial pulses bilaterally, then brachial. Note rate, rhythm, volume, and symmetry.', normal: 'Symmetric 2+ pulses, regular rhythm, age-appropriate rate' },
              { label: 'Peripheral pulses — lower', method: 'Palpate femoral pulses. Compare to brachial — radio-femoral or brachio-femoral delay suggests coarctation of the aorta.', normal: 'Femoral pulses 2+ symmetric, no delay relative to radial' }
            ],
            abnormalHints: ['Apex displaced laterally/inferiorly — cardiomegaly', 'Heaving apex — pressure overload (AS, HTN)', 'Thrusting apex — volume overload (AR, MR)', 'Thrill over precordium — always pathological; at least grade 4/6 murmur', 'Parasternal heave — RV hypertrophy (pulmonary HTN, pulmonary stenosis, VSD with Eisenmenger)', 'Radio-femoral delay — coarctation of the aorta (always check in a hypertensive adolescent)'] },

          { name: 'Auscultation — approach',
            significance: 'Systematic technique ensures every relevant finding is detected. Listen at all 5 points, with both diaphragm and bell, in supine/sitting/left-lateral positions as needed.',
            pearl: 'Time every murmur by simultaneously palpating the carotid pulse with the fingers of your free hand. Pulse = systole. Murmur heard during the pulse = systolic; in between pulses = diastolic.',
            steps: [
              { label: 'Positioning', method: 'Patient supine, head of bed at 30°. Exam room quiet, patient relaxed. Warm the stethoscope first.', normal: 'N/A — technique' },
              { label: 'Diaphragm technique', method: 'Firm contact with skin. Detects HIGH-pitched sounds: S1, S2, systolic ejection murmurs, AR, MR.', normal: 'N/A — technique' },
              { label: 'Bell technique', method: 'Very light contact — enough to make a seal but not stretch the skin. Detects LOW-pitched sounds: S3, S4, mitral stenosis rumble.', normal: 'N/A — technique' },
              { label: 'Listen at each of the 5 points', method: 'A → P → E → T → M in order, each with diaphragm then bell. Spend a full cycle at each zone.', normal: 'S1 crisp, S2 clear (splits physiologically on inspiration at P), no added sounds, no murmur' },
              { label: 'Left lateral decubitus position', method: 'If apex murmur suspected. Roll patient to left side. Listen at the apex with the BELL for mitral stenosis rumble or S3/S4.', normal: 'No added sounds, no diastolic rumble' },
              { label: 'Sitting forward, held expiration', method: 'Patient leans forward, exhales fully, holds. Listen at left lower sternal border and Erb\'s point with the DIAPHRAGM for aortic regurgitation (soft early diastolic decrescendo).', normal: 'No early-diastolic murmur' }
            ],
            abnormalHints: ['Fixed split S2 (no change with respiration) — ASD', 'Loud S2 at pulmonic area — pulmonary HTN', 'S3 — volume overload, CHF (can be normal in young athletes)', 'S4 — stiff ventricle (HTN, HCM, ischemia)', 'Audible opening snap — mitral stenosis (rare in children)'] },

          { name: 'Auscultation — heart sounds and murmurs',
            significance: 'Characterising a murmur by timing, location, radiation, pitch, quality, and dynamic maneuvers narrows the differential.',
            pearl: 'Innocent murmurs in children share 7 "S" features: Soft (≤ grade 2), Systolic, Short, Single (no added S3/S4), Small (localised, non-radiating), Sweet (musical), Sensitive to position/respiration (louder supine, softer standing). Anything breaking this pattern deserves workup.',
            steps: [
              { label: 'S1', method: 'Listen at the apex (mitral). Coincides with the carotid pulse upstroke. Mitral + tricuspid closure.', normal: 'Single, crisp, single-component sound' },
              { label: 'S2', method: 'Listen at the pulmonic area in HELD INSPIRATION and HELD EXPIRATION. Note whether S2 splits physiologically (wider in inspiration, narrower/absent in expiration).', normal: 'Physiologic split (widens on inspiration, narrows on expiration)' },
              { label: 'S3 / S4 gallops', method: 'Bell at the apex in left lateral decubitus. S3 = early diastole (after S2), low-pitched. S4 = late diastole (just before S1).', normal: 'Absent in adults; S3 can be normal in young athletes under age 30' },
              { label: 'Identify murmur — timing', method: 'Time vs carotid pulse. Systolic (during pulse) vs diastolic (between pulses) vs continuous.', normal: 'No murmur, or only soft innocent flow murmur' },
              { label: 'Identify murmur — location + radiation', method: 'Where loudest? Does it radiate? AS → carotids. MR → axilla. Coarctation → back.', normal: 'N/A — characterise only if murmur present' },
              { label: 'Identify murmur — character', method: 'Crescendo-decrescendo (ejection) vs holosystolic (plateau) vs decrescendo early-diastolic (AR, PR) vs mid-diastolic rumble (MS, TS).', normal: 'N/A — characterise only if murmur present' },
              { label: 'Grade intensity', method: 'Levine 1–6 scale (see scales card above).', normal: 'No murmur, or grade ≤ 2 soft innocent flow murmur' },
              { label: 'Dynamic maneuvers', method: 'Standing: ↑HOCM, ↑MVP click (earlier). Squatting: opposite. Valsalva: ↑HOCM, most others decrease.', normal: 'No significant change with posture' }
            ],
            abnormalHints: ['Holosystolic murmur at apex → axilla — mitral regurgitation', 'Holosystolic at lower left sternal border (LLSB) — VSD, tricuspid regurgitation', 'Systolic ejection at upper right sternal border → carotids — aortic stenosis', 'Systolic ejection at upper left sternal border — pulmonary stenosis', 'Continuous "machinery" below left clavicle — PDA', 'Early diastolic at Erb\'s point, leaning forward — aortic regurgitation', 'Diastolic rumble at apex, bell in left-lateral — mitral stenosis', 'Fixed split S2 + systolic flow murmur — ASD'] },

          { name: 'Peripheral vascular exam',
            significance: 'Coarctation of the aorta hides until BP and pulses are checked in all four extremities. Differential diagnosis of a hypertensive adolescent should include this in the first 60 seconds.',
            pearl: 'Four-limb BP measurement is mandatory in any adolescent with hypertension or a murmur. Upper-extremity BP > lower-extremity BP (or brachio-femoral delay) = coarctation until excluded.',
            steps: [
              { label: 'Four-limb blood pressure', method: 'Measure BP in right arm, left arm, and at least one leg. Use appropriately sized cuff (bladder width 40% of limb circumference, length 80–100%).', normal: 'Arm BPs within 10 mmHg of each other; leg systolic within 20 mmHg of arm systolic (may be higher)' },
              { label: 'Radial pulses', method: 'Palpate both radials simultaneously — note any delay or asymmetry.', normal: 'Simultaneous, symmetric, 2+' },
              { label: 'Radio-femoral delay', method: 'Palpate radial and femoral simultaneously. Feel the femoral as clearly "after" the radial = delay.', normal: 'No delay' },
              { label: 'Femoral pulses', method: 'Palpate both femoral pulses at the mid-inguinal point. Compare amplitude to radials.', normal: 'Symmetric 2+ pulses, equal amplitude to radial' },
              { label: 'Dorsalis pedis + posterior tibialis', method: 'Palpate in both feet.', normal: '2+ pulses bilaterally' },
              { label: 'Capillary refill', method: 'Press and release the nail bed; time to normal colour.', normal: '< 2 sec' }
            ],
            abnormalHints: ['Asymmetric upper-extremity BP (> 10 mmHg) — subclavian stenosis or coarctation at the origin', 'Upper >> lower-extremity BP — coarctation of the aorta', 'Diminished or absent femoral pulses with brachio-femoral delay — coarctation', 'Bounding pulses with wide pulse pressure — AR, PDA, arteriovenous fistula, thyrotoxicosis, anemia', 'Weak thready pulses — low output state (heart failure, shock, hypovolemia)', 'Prolonged capillary refill — dehydration, shock, cold stress'] }
        ]
      }
    }
  };

  // ────────────────────────────────────────────────────────────
  // STATE + RENDER
  // ────────────────────────────────────────────────────────────
  var _inited = false;
  // state keyed as 'system-componentIdx-stepIdx' → { label, method, normal, status, note }
  var state = {};
  var currentSystem = 'msk';
  var currentAgeGroup = '';

  document.addEventListener('tabChanged', function (e) {
    if (e.detail.tab !== 'peguide' || _inited) return;
    _inited = true;
    init();
  });

  function init() {
    var ageSelect = document.getElementById('pe-age-group');
    var content = document.getElementById('pe-content');
    var actions = document.getElementById('pe-actions');

    function applyAgeGroup(ag) {
      currentAgeGroup = ag;
      state = {};
      document.getElementById('pe-output').classList.add('hidden');
      if (!currentAgeGroup || !PE_DATA[currentAgeGroup]) {
        content.innerHTML = '<p style="text-align:center;color:#9ca3af;padding:40px;">Select an age group above.</p>';
        actions.style.display = 'none';
        return;
      }
      renderSystem();
      actions.style.display = 'flex';
    }
    ageSelect.addEventListener('change', function () {
      applyAgeGroup(ageSelect.value);
      if (window.UIState) window.UIState.set('pe.ageGroup', ageSelect.value || '');
    });

    function applySystem(sys) {
      document.querySelectorAll('[data-pesystem]').forEach(function (b) {
        b.classList.toggle('active', b.dataset.pesystem === sys);
      });
      currentSystem = sys;
      state = {};
      document.getElementById('pe-output').classList.add('hidden');
      if (currentAgeGroup) renderSystem();
    }
    document.querySelectorAll('[data-pesystem]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        applySystem(btn.dataset.pesystem);
        if (window.UIState) window.UIState.set('pe.system', btn.dataset.pesystem);
      });
    });

    // Restore persisted selections. Age group must be restored first because
    // the system render depends on it.
    if (window.UIState) {
      var savedAge = window.UIState.get('pe.ageGroup');
      if (savedAge && PE_DATA[savedAge]) {
        ageSelect.value = savedAge;
        applyAgeGroup(savedAge);
      }
      var savedSys = window.UIState.get('pe.system');
      if (savedSys && /^(msk|neuro|resp|cv)$/.test(savedSys)) {
        applySystem(savedSys);
      }
    }

    document.getElementById('pe-all-normal').addEventListener('click', setAllNormal);
    document.getElementById('pe-all-clear').addEventListener('click', clearAll);
    document.getElementById('pe-generate-btn').addEventListener('click', generate);
  }

  // Responsive two-column grid helper: side-by-side on wide screens, stacked on narrow
  var TWO_COL_GRID = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;align-items:start;';

  // Render a single sound card with native <audio controls> (play/pause/seek
  // free on all platforms incl. mobile). Falls back to a synth play button
  // when the sound has no real recording.
  function renderSoundCard(s) {
    var player = '<audio class="pe-audio" controls preload="none" src="' + esc(s.src) + '" style="width:100%;height:36px;"></audio>';
    var html = '';
    html += '<div style="border:1px solid var(--g200);border-radius:8px;padding:10px;background:#fff;">';
    html += '  <div style="font-weight:600;font-size:13px;color:var(--g800);margin-bottom:4px;">' + esc(s.title) + '</div>';
    if (s.where)    html += '  <div style="font-size:11px;color:var(--g500);margin-bottom:3px;"><strong>Where:</strong> ' + esc(s.where) + '</div>';
    if (s.rate)     html += '  <div style="font-size:11px;color:var(--g500);margin-bottom:3px;"><strong>Rate:</strong> ' + esc(s.rate) + '</div>';
    if (s.features) html += '  <div style="font-size:12px;color:var(--g700);line-height:1.5;margin-bottom:3px;"><strong>Features:</strong> ' + esc(s.features) + '</div>';
    if (s.clinical) html += '  <div style="font-size:11px;color:var(--g600);line-height:1.5;margin-bottom:8px;"><strong>Clinical:</strong> ' + esc(s.clinical) + '</div>';
    html += '  <div style="margin-top:6px;">' + player + '</div>';
    html += '</div>';
    return html;
  }

  function renderSoundsLibrary(title, sounds, accent, accentTint, icon) {
    var html = '';
    html += '<div class="card" style="margin-bottom:14px;border:1px solid ' + accent + '33;">';
    html += '  <div class="card-header" style="background:' + accentTint + ';"><h3 style="margin:0;font-size:14px;color:' + accent + ';"><i class="fas ' + icon + '"></i> ' + esc(title) + '</h3></div>';
    html += '  <div style="padding:10px 14px;display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:10px;">';
    sounds.forEach(function (s) { html += renderSoundCard(s); });
    html += '  </div>';
    html += '</div>';
    return html;
  }

  function renderSystem() {
    var content = document.getElementById('pe-content');
    var group = PE_DATA[currentAgeGroup];
    if (!group || !group[currentSystem]) {
      content.innerHTML = '<p style="text-align:center;color:#9ca3af;padding:40px;">No data for this combination.</p>';
      return;
    }
    var section = group[currentSystem];
    var accentMap    = { msk: '#0891b2', neuro: '#7c3aed', resp: '#0ea5e9', cv: '#e11d48' }; // cyan / purple / sky / rose
    var accentTintMap = { msk: '#ecfeff', neuro: '#f5f3ff', resp: '#f0f9ff', cv: '#fff1f2' };
    var iconMap       = { msk: 'bone',    neuro: 'brain',   resp: 'lungs',   cv: 'heart-pulse' };
    var labelMap      = { msk: 'Musculoskeletal', neuro: 'Neurologic', resp: 'Respiratory', cv: 'Cardiovascular' };
    var accent     = accentMap[currentSystem]    || '#0891b2';
    var accentTint = accentTintMap[currentSystem] || '#ecfeff';
    var icon       = iconMap[currentSystem]       || 'circle-info';
    var sysLabel   = labelMap[currentSystem]      || currentSystem;
    var html = '';

    // ─ Overview banner ─
    html += '<div class="card" style="margin-bottom:14px;border-left:4px solid ' + accent + ';">';
    html += '  <div class="card-header" style="border:0;padding:14px 16px 6px;"><h3 style="margin:0;font-size:16px;color:' + accent + ';"><i class="fas fa-' + icon + '"></i> ' + esc(group.label) + ' — ' + sysLabel + '</h3></div>';
    html += '  <div style="padding:0 16px 14px;font-size:13px;line-height:1.65;color:var(--g700);">' + esc(section.overview) + '</div>';
    html += '</div>';

    // ─ APTM cardiac auscultation diagram + innocent-murmur map (cv only) ─
    if (currentSystem === 'cv') {
      html += '<div class="card" style="margin-bottom:14px;border:1px solid ' + accent + '33;">';
      html += '  <div class="card-header" style="background:' + accentTint + ';"><h3 style="margin:0;font-size:14px;color:' + accent + ';"><i class="fas fa-stethoscope"></i> Auscultation landmarks — APTM + Erb\'s</h3></div>';
      // Image ALWAYS on its own row (full width on every device, responsive
      // max-width caps it so it isn't huge on desktop). Tap/click to open
      // full-size in a new tab — native browser zoom works there. Legend
      // below stacks on narrow screens via auto-fit grid with minmax.
      html += '  <div style="padding:14px 16px 6px;">';
      html += '    <a href="/images/pe-guide/aptm.png" target="_blank" rel="noopener" aria-label="Open APTM diagram full size in a new tab" style="display:block;text-align:center;cursor:zoom-in;">';
      html += '      <img src="/images/pe-guide/aptm.png" alt="APTM cardiac auscultation points diagram" style="max-width:100%;width:100%;max-width:420px;height:auto;display:inline-block;border-radius:8px;border:1px solid var(--g200);"/>';
      html += '      <div style="font-size:11px;color:var(--g500);margin-top:6px;"><i class="fas fa-up-right-from-square" style="margin-right:4px;"></i>Tap / click to open full-size in a new tab (pinch to zoom on mobile)</div>';
      html += '    </a>';
      html += '  </div>';
      html += '  <div style="padding:4px 16px 14px;">';
      html += '    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:10px 16px;font-size:12px;line-height:1.55;">';
      APTM_LEGEND.forEach(function (p) {
        html += '<div style="display:flex;gap:10px;align-items:flex-start;">';
        html += '  <div style="flex-shrink:0;width:24px;height:24px;border-radius:50%;background:' + p.color + ';color:#fff;font-weight:700;display:flex;align-items:center;justify-content:center;font-size:12px;">' + p.letter + '</div>';
        html += '  <div style="flex:1;min-width:0;">';
        html += '    <div style="font-weight:600;color:var(--g800);font-size:13px;">' + esc(p.title) + '</div>';
        html += '    <div style="color:var(--g600);font-size:11px;margin-top:1px;">' + esc(p.location) + '</div>';
        html += '    <div style="color:var(--g700);margin-top:3px;font-size:12px;"><strong>Listen for:</strong> ' + esc(p.listen) + '</div>';
        if (p.innocent) {
          html += '    <div style="color:#047857;margin-top:2px;font-size:11px;"><i class="fas fa-leaf" style="margin-right:3px;"></i><em>Innocent:</em> ' + esc(p.innocent) + '</div>';
        }
        html += '  </div>';
        html += '</div>';
      });
      html += '    </div>';
      html += '  </div>';

      // ─ Cardiac sounds library ─
      html += '  <div style="border-top:1px solid var(--g200);padding:14px;">';
      html += '    <div style="font-weight:600;font-size:13px;color:' + accent + ';margin-bottom:10px;"><i class="fas fa-volume-high"></i> Cardiac sounds library</div>';
      html += '    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:10px;">';
      CARDIAC_SOUNDS.forEach(function (s) {
        html += renderSoundCard(s);
      });
      html += '    </div>';
      html += '  </div>';

      // ─ Innocent murmur reference panel ─
      html += '  <div style="border-top:1px solid var(--g200);padding:14px;background:#f0fdf4;">';
      html += '    <div style="font-weight:600;font-size:13px;color:#047857;margin-bottom:8px;"><i class="fas fa-leaf"></i> Classic innocent murmurs (benign, no workup needed)</div>';
      html += '    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px;">';
      INNOCENT_MURMURS.forEach(function (m) {
        html += '<div style="background:#fff;border:1px solid var(--g200);border-radius:8px;padding:10px 12px;">';
        html += '  <div style="font-weight:600;color:var(--g800);font-size:13px;margin-bottom:3px;">' + esc(m.name) + '</div>';
        html += '  <div style="font-size:11px;color:var(--g500);margin-bottom:4px;">Age: ' + esc(m.age) + ' · Location: ' + esc(m.location) + '</div>';
        html += '  <div style="font-size:12px;color:var(--g700);line-height:1.55;"><strong>Sound:</strong> ' + esc(m.character) + '</div>';
        html += '  <div style="font-size:12px;color:var(--g700);line-height:1.55;margin-top:3px;"><strong>Confirm innocent:</strong> ' + esc(m.confirm) + '</div>';
        html += '</div>';
      });
      html += '    </div>';
      html += '    <div style="margin-top:10px;font-size:11px;color:var(--g600);line-height:1.55;"><strong>The 7 "S" innocent-murmur criteria:</strong> Soft (≤ 2/6) · Systolic · Short · Single (no S3/S4) · Small (non-radiating) · Sweet (musical) · Sensitive to position/respiration. Any murmur breaking this pattern — diastolic, ≥ grade 3, radiating, continuous, accompanied by symptoms — deserves pediatric cardiology referral.</div>';
      html += '  </div>';
      html += '</div>';
    }

    // ─ Respiratory sounds library (only for resp system) ─
    if (currentSystem === 'resp') {
      html += renderSoundsLibrary('Respiratory sounds library', RESP_SOUNDS, accent, accentTint, 'fa-lungs');
    }

    // ─ Grading scales reference (collapsible) ─
    var scaleKeys = SYSTEM_SCALES[currentSystem] || [];
    if (scaleKeys.length) {
      html += '<details class="card" style="margin-bottom:14px;background:' + accentTint + ';border:1px solid ' + accent + '33;">';
      html += '  <summary style="padding:10px 16px;cursor:pointer;font-weight:600;font-size:13px;color:' + accent + ';list-style:none;display:flex;align-items:center;gap:8px;"><i class="fas fa-book-medical"></i> Grading scales &amp; reference <span style="font-weight:400;color:var(--g500);font-size:11px;">(click to expand)</span></summary>';
      html += '  <div style="padding:0 16px 14px;display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:14px;">';
      scaleKeys.forEach(function (sk) {
        var sc = SCALES[sk]; if (!sc) return;
        html += '<div style="background:#fff;border:1px solid var(--g200);border-radius:8px;padding:10px 12px;">';
        html += '  <div style="font-weight:600;font-size:12px;color:var(--g800);margin-bottom:6px;"><i class="fas ' + sc.icon + '" style="color:' + accent + ';margin-right:6px;"></i>' + esc(sc.title) + '</div>';
        html += '  <table style="width:100%;font-size:11px;line-height:1.5;border-collapse:collapse;">';
        sc.rows.forEach(function (row) {
          html += '<tr><td style="padding:2px 0;white-space:nowrap;color:' + accent + ';font-weight:600;font-family:ui-monospace,monospace;">' + esc(row[0]) + '</td><td style="padding:2px 0 2px 10px;color:var(--g700);">' + esc(row[1]) + '</td></tr>';
        });
        html += '  </table>';
        html += '</div>';
      });
      html += '  </div>';
      html += '</details>';
    }

    // ─ Components ─
    section.components.forEach(function (c, ci) {
      html += '<div class="card" style="margin-bottom:12px;border-left:3px solid ' + accent + ';">';

      // Header
      html += '  <div style="padding:12px 16px 8px;display:flex;align-items:center;justify-content:space-between;gap:10px;">';
      html += '    <h3 style="margin:0;font-size:15px;color:var(--g800);">' + esc(c.name) + '</h3>';
      html += '    <span style="font-size:10px;font-weight:600;padding:3px 8px;border-radius:10px;background:' + accent + '22;color:' + accent + ';text-transform:uppercase;letter-spacing:0.5px;white-space:nowrap;">' + c.steps.length + ' steps</span>';
      html += '  </div>';

      // Significance line
      if (c.significance) {
        html += '  <div style="padding:0 16px 6px;font-size:12px;color:var(--g600);line-height:1.55;"><i class="fas fa-bullseye" style="color:' + accent + ';margin-right:6px;font-size:11px;"></i>' + esc(c.significance) + '</div>';
      }

      // Teaching pearl
      if (c.pearl) {
        html += '  <div style="margin:6px 16px 10px;padding:10px 12px;background:#fef7e7;border-left:3px solid #f59e0b;border-radius:0 6px 6px 0;font-size:12px;line-height:1.6;color:#78350f;"><i class="fas fa-lightbulb" style="color:#f59e0b;margin-right:6px;"></i><em>' + esc(c.pearl) + '</em></div>';
      }

      // Steps
      html += '  <div style="padding:4px 12px 10px;">';
      c.steps.forEach(function (s, si) {
        var key = currentSystem + '-' + ci + '-' + si;
        if (!state[key]) state[key] = { component: c.name, label: s.label, method: s.method, normal: s.normal, status: null, note: '' };
        var st = state[key].status;
        var rowBg = st === 'normal' ? '#ecfdf5' : st === 'abnormal' ? '#fef2f2' : 'transparent';
        var rowBorder = st === 'normal' ? '#a7f3d0' : st === 'abnormal' ? '#fecaca' : 'var(--g200)';
        html += '<div class="pe-step" data-pe-key="' + key + '" style="padding:10px 12px;border:1px solid ' + rowBorder + ';border-radius:8px;margin-bottom:6px;background:' + rowBg + ';transition:background 0.12s,border-color 0.12s;">';
        html += '  <div style="display:flex;align-items:flex-start;gap:10px;">';
        html += '    <div style="flex-shrink:0;width:22px;height:22px;border-radius:50%;background:' + accent + '22;color:' + accent + ';font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;line-height:1;">' + (si + 1) + '</div>';
        html += '    <div style="flex:1;min-width:0;">';
        html += '      <div style="font-weight:600;font-size:13px;color:var(--g800);">' + esc(s.label) + '</div>';
        html += '      <div style="font-size:12px;color:var(--g600);margin-top:3px;line-height:1.55;"><span style="color:var(--g500);font-weight:600;text-transform:uppercase;letter-spacing:0.5px;font-size:10px;">How</span> &nbsp;' + esc(s.method) + '</div>';
        html += '      <div style="font-size:12px;color:var(--g600);margin-top:2px;line-height:1.55;"><span style="color:#059669;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;font-size:10px;">Normal</span> &nbsp;' + esc(s.normal) + '</div>';
        html += '    </div>';
        html += '    <div style="display:flex;gap:3px;flex-shrink:0;">';
        html += '      <button class="visit-status-btn ' + (st === 'normal' ? 'done' : '') + '" data-pe-status="normal" data-pe-key="' + key + '" title="Normal">✓</button>';
        html += '      <button class="visit-status-btn ' + (st === 'abnormal' ? 'refused' : '') + '" data-pe-status="abnormal" data-pe-key="' + key + '" title="Abnormal">✗</button>';
        html += '      <button class="visit-status-btn ' + (st === null ? 'not-due' : '') + '" data-pe-status="skip" data-pe-key="' + key + '" title="Skip">—</button>';
        html += '    </div>';
        html += '  </div>';
        html += '  <div class="pe-abnormal-detail" style="margin-top:8px;' + (st === 'abnormal' ? '' : 'display:none;') + '">';
        html += '    <input type="text" class="pe-note" data-pe-key="' + key + '" placeholder="Describe the abnormal finding (e.g., 4/5 strength, left pronator drift)" value="' + esc(state[key].note || '') + '" style="width:100%;padding:6px 10px;font-size:12px;border:1px solid #fecaca;border-radius:6px;background:#fff;">';
        html += '  </div>';
        html += '</div>';
      });
      html += '  </div>';

      // Watch-for
      if (c.abnormalHints && c.abnormalHints.length) {
        html += '<div style="margin:0 12px 12px;padding:10px 12px;background:#fef2f2;border-left:3px solid #ef4444;border-radius:0 6px 6px 0;font-size:11px;line-height:1.7;color:#7f1d1d;">';
        html += '<div style="font-weight:600;text-transform:uppercase;letter-spacing:0.5px;color:#991b1b;margin-bottom:4px;font-size:10px;"><i class="fas fa-triangle-exclamation"></i> Watch for</div>';
        html += c.abnormalHints.map(esc).join(' &nbsp;·&nbsp; ');
        html += '</div>';
      }

      html += '</div>';
    });

    content.innerHTML = html;

    content.querySelectorAll('[data-pe-status]').forEach(function (btn) {
      btn.addEventListener('click', function () { handleStatus(btn); });
    });
    content.querySelectorAll('.pe-note').forEach(function (inp) {
      inp.addEventListener('input', function () {
        var key = inp.dataset.peKey;
        if (state[key]) state[key].note = inp.value;
      });
    });
    // Single-playback policy: when any <audio> starts, pause every other one.
    content.querySelectorAll('.pe-audio').forEach(function (a) {
      a.addEventListener('play', function () {
        content.querySelectorAll('.pe-audio').forEach(function (other) {
          if (other !== a && !other.paused) other.pause();
        });
      });
    });
  }

  function handleStatus(btn) {
    var key = btn.dataset.peKey;
    var status = btn.dataset.peStatus;
    if (!state[key]) return;
    state[key].status = (status === 'skip') ? null : status;
    var row = btn.closest('.pe-step');
    if (row) {
      var s = state[key].status;
      row.style.background     = s === 'normal' ? '#ecfdf5'  : s === 'abnormal' ? '#fef2f2'  : 'transparent';
      row.style.borderColor    = s === 'normal' ? '#a7f3d0'  : s === 'abnormal' ? '#fecaca'  : 'var(--g200)';
      row.querySelectorAll('[data-pe-status]').forEach(function (b) {
        b.classList.remove('done', 'refused', 'not-due');
        if (b.dataset.peStatus === 'normal'   && state[key].status === 'normal')   b.classList.add('done');
        if (b.dataset.peStatus === 'abnormal' && state[key].status === 'abnormal') b.classList.add('refused');
        if (b.dataset.peStatus === 'skip'     && state[key].status === null)      b.classList.add('not-due');
      });
      var detail = row.querySelector('.pe-abnormal-detail');
      if (detail) detail.style.display = (state[key].status === 'abnormal') ? '' : 'none';
    }
  }

  function setAllNormal() {
    Object.keys(state).forEach(function (k) { if (k.indexOf(currentSystem + '-') === 0) state[k].status = 'normal'; });
    renderSystem();
  }
  function clearAll() {
    Object.keys(state).forEach(function (k) { if (k.indexOf(currentSystem + '-') === 0) { state[k].status = null; state[k].note = ''; } });
    renderSystem();
  }

  function generate() {
    if (!currentAgeGroup || !PE_DATA[currentAgeGroup]) return;
    var steps = Object.keys(state)
      .filter(function (k) { return k.indexOf(currentSystem + '-') === 0; })
      .map(function (k) { return state[k]; });

    var assessed = steps.filter(function (s) { return s.status !== null; });
    if (assessed.length === 0) { showToast('Mark at least one step Normal or Abnormal', 'error'); return; }

    var btn = document.getElementById('pe-generate-btn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';

    var modelSel = document.querySelector('#peguide-tab .tab-model-select');
    var model = modelSel ? modelSel.value : '';
    var format = document.getElementById('pe-format').value;

    fetch('/api/generate-pe-narrative', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        steps:         steps,
        ageGroup:      PE_DATA[currentAgeGroup].label,
        system:        currentSystem,
        patientAge:    document.getElementById('pe-age').value,
        patientGender: document.getElementById('pe-gender').value,
        model:         model,
        format:        format
      })
    })
    .then(function (r) { return r.json(); })
    .then(function (data) {
      if (!data.success) { showToast(data.error || 'Generation failed', 'error'); return; }
      var out = document.getElementById('pe-output');
      out.classList.remove('hidden');
      document.getElementById('pe-narrative-text').textContent = data.narrative;
      var tag = document.getElementById('pe-model-tag');
      if (tag) tag.textContent = data.model || '';
      var bar = document.getElementById('pe-summary-bar');
      if (bar && data.summary) {
        bar.classList.remove('hidden');
        bar.innerHTML = '<span style="color:#10b981;">' + data.summary.normal + ' normal</span> · <span style="color:#ef4444;">' + data.summary.abnormal + ' abnormal</span> · <span style="color:#9ca3af;">' + data.summary.notAssessed + ' skipped</span>';
      }
    })
    .catch(function (err) { console.error('[PEGuide] generate error', err); showToast('Request failed', 'error'); })
    .finally(function () {
      btn.disabled = false; btn.innerHTML = '<i class="fas fa-wand-magic-sparkles"></i> Generate Exam Report';
    });
  }

  function esc(s) {
    if (s == null) return '';
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  }

})();
