(() => {
  const workspace = document.querySelector('[data-clinical-workspace]');
  const form = document.querySelector('[data-clinical-record-form]');
  if (!workspace || !form) return;

  const debounce = (fn, delay = 220) => {
    let timer = 0;
    return (...args) => {
      window.clearTimeout(timer);
      timer = window.setTimeout(() => fn(...args), delay);
    };
  };

  const setComplete = (key, complete, message = '') => {
    const item = document.querySelector(`[data-check-item="${key}"]`);
    if (!item) return;
    item.classList.toggle('complete', complete);
    item.classList.toggle('missing', !complete);
    const mark = item.querySelector(':scope > span');
    if (mark) mark.textContent = complete ? '✓' : '!';
    if (message) {
      const copy = item.querySelector('small');
      if (copy) copy.textContent = message;
    }
  };

  const visibleValue = (name) => String(form.querySelector(`[name="${name}"]`)?.value || '').trim();
  const diagnosisValues = () => [...form.querySelectorAll('[name="diagnosis_name[]"]')].map(input => input.value.trim()).filter(Boolean);
  const assessmentDomainComplete = () => [...form.querySelectorAll('[data-exam-status]')].some(select => !['', 'not_examined'].includes(select.value));
  const assessmentComplete = () => assessmentDomainComplete() && visibleValue('examination_summary') !== '';
  const examinationSummaryField = form.querySelector('[data-examination-summary]');
  const generatedExaminationSummary = () => [...form.querySelectorAll('[data-exam-domain]')].map(domain => {
    const label = domain.querySelector('strong')?.textContent?.trim() || 'Examination';
    const state = domain.querySelector('[data-exam-status]')?.value || 'not_examined';
    if (!state || state === 'not_examined') return '';
    const stateLabel = state.replaceAll('_', ' ').replace(/\b\w/g, character => character.toUpperCase());
    const finding = domain.querySelector('[data-exam-detail]')?.value.trim() || '';
    return `${label}: ${stateLabel}${finding ? ` — ${finding}` : ''}.`;
  }).filter(Boolean).join(' ');
  const refreshGeneratedExaminationSummary = () => {
    if (!examinationSummaryField) return;
    const generated = generatedExaminationSummary();
    if (examinationSummaryField.dataset.generatedSummary === '1' || examinationSummaryField.value.trim() === '') {
      examinationSummaryField.value = generated;
      examinationSummaryField.dataset.generatedSummary = '1';
    }
  };
  const disposition = () => visibleValue('clinical_disposition');
  const recordedProcedureCount = () => document.querySelectorAll('[data-clinical-procedure]').length;
  const requiresProcedure = () => ['treatment_performed', 'emergency_stabilization'].includes(disposition());
  const requiresConsent = () => recordedProcedureCount() > 0 || ['treatment_performed', 'emergency_stabilization', 'medication_administered', 'diagnostic_procedure'].includes(disposition());
  const linkedConsent = () => document.querySelector('[data-consent-status]')?.classList.contains('ready') || false;
  const emergencyConsent = () => {
    const checked = form.querySelector('[data-emergency-consent]')?.checked;
    return checked && visibleValue('consent_exception_reason').length >= 20;
  };
  const intakeForm = document.querySelector('[data-vitals-form]');
  const valueFrom = (container, name) => String(container?.querySelector(`[name="${name}"]`)?.value || '').trim();
  const checkedFrom = (container, name) => Boolean(container?.querySelector(`[name="${name}"]`)?.checked);
  const firstEnabled = (selectors, container = document) => {
    for (const selector of selectors) {
      const field = container.querySelector(selector);
      if (field && !field.disabled && !field.readOnly && field.offsetParent !== null) return field;
    }
    return null;
  };
  const liveIntakeComplaint = () => valueFrom(intakeForm, 'intake_chief_complaint') || visibleValue('chief_complaint');
  const liveIntakeHpi = () => valueFrom(intakeForm, 'intake_hpi') || visibleValue('history_present_condition');
  const intakeConfirmationsLive = () => {
    if (workspace.dataset.intakeConfirmationsReady === '1') return true;
    return checkedFrom(intakeForm, 'allergies_confirmed')
      && checkedFrom(intakeForm, 'medications_confirmed')
      && checkedFrom(intakeForm, 'consent_acknowledged');
  };
  const hpiRequired = workspace.dataset.hpiRequired === '1';
  const assessmentRequired = workspace.dataset.assessmentRequired === '1';
  const vitalsRequired = workspace.dataset.vitalsRequired === '1';
  const vitalsSkipSelected = () => Boolean(form.querySelector('[name="vitals_not_required"]')?.checked);
  const vitalsSkipReason = () => visibleValue('vitals_skip_reason');
  const vitalsDecisionComplete = () => isChecked('vitals_review_acknowledged') || (!vitalsRequired && vitalsSkipSelected() && vitalsSkipReason().length >= 10);
  const intakeComplete = () => intakeConfirmationsLive() && liveIntakeComplaint() !== '' && (!hpiRequired || liveIntakeHpi() !== '');
  const clinicalSetStatusMessage = (kind, message) => {
    document.querySelectorAll('[data-clinical-focus-status]').forEach(node => {
      node.textContent = message || '';
      node.classList.toggle('warning', kind === 'warning');
      node.classList.toggle('success', kind === 'success');
    });
  };
  const clinicalFieldLabel = field => {
    const label = field?.closest('label');
    if (label) {
      const own = [...label.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.trim());
      if (own) return own.textContent.replace('*', '').trim();
      const span = label.querySelector('span,strong');
      if (span) return span.textContent.trim();
    }
    const name = field?.getAttribute('name') || 'This field';
    return name.replace(/\[\]$/, '').replaceAll('_', ' ').replace(/\b\w/g, c => c.toUpperCase());
  };
  const clinicalFieldWarningMessage = field => {
    if (!field || field.disabled || field.readOnly) return '';
    const value = String(field.value || '').trim();
    const type = String(field.getAttribute('type') || '').toLowerCase();
    const required = field.required || field.matches('[data-required-first]');
    if (required) {
      if ((type === 'checkbox' || type === 'radio') && !field.checked) return `${clinicalFieldLabel(field)} is required before this encounter can be completed.`;
      if (type !== 'checkbox' && type !== 'radio' && value === '') return `${clinicalFieldLabel(field)} is required before moving on.`;
    }
    if (field.minLength > 0 && value !== '' && value.length < field.minLength) return `${clinicalFieldLabel(field)} needs at least ${field.minLength} characters.`;
    if (field.name === 'bp_systolic' || field.name === 'bp_diastolic') {
      const systolic = Number(valueFrom(intakeForm, 'bp_systolic'));
      const diastolic = Number(valueFrom(intakeForm, 'bp_diastolic'));
      if ((systolic >= 160 || diastolic >= 100) && !checkedFrom(intakeForm, 'bp_symptoms_reviewed')) return 'High blood-pressure reading: review symptoms while you are still in this section.';
    }
    return '';
  };
  const clinicalWarningNode = field => {
    if (!field) return null;
    const owner = field.closest('label,fieldset,.vital-capture-block,.diagnosis-row') || field.parentElement;
    if (!owner) return null;
    let node = owner.querySelector(':scope > [data-clinical-field-warning]');
    if (!node) {
      node = document.createElement('small');
      node.dataset.clinicalFieldWarning = '1';
      node.className = 'clinical-field-warning';
      owner.appendChild(node);
    }
    return node;
  };
  const updateClinicalFieldWarning = field => {
    const message = clinicalFieldWarningMessage(field);
    const node = clinicalWarningNode(field);
    if (node) {
      node.textContent = message;
      node.hidden = message === '';
    }
    field?.classList?.toggle('clinical-field-needs-attention', message !== '');
    return message;
  };
  const focusTreatmentField = (target, message = '') => {
    if (!target) return;
    const details = target.closest('details');
    if (details) details.open = true;
    document.querySelectorAll('.clinical-focus-outline').forEach(node => node.classList.remove('clinical-focus-outline'));
    const shell = target.closest('label,fieldset,.vital-capture-block,.clinical-form-panel,.clinical-completion-panel,.module-card') || target;
    shell.classList.add('clinical-focus-outline');
    if (message) clinicalSetStatusMessage('warning', message);
    const scrollTarget = target.closest('.clinical-form-panel,.clinical-intake-vitals,.clinical-completion-panel,label,fieldset') || target;
    scrollTarget.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
    window.setTimeout(() => {
      if (target.matches?.('input,select,textarea,button,a')) {
        try { target.focus({ preventScroll: true }); } catch (_) { target.focus(); }
        if (typeof target.select === 'function' && target.matches('input:not([type="date"]):not([type="time"]):not([type="number"]),textarea')) target.select();
      }
      updateClinicalFieldWarning(target);
    }, 80);
  };
  const followDecision = () => form.querySelector('[name="follow_up_decision"]:checked')?.value || '';
  const followComplete = () => {
    if (followDecision() === 'none') return true;
    if (followDecision() !== 'recommended') return false;
    return visibleValue('follow_up_date') !== '' && visibleValue('follow_up_purpose') !== '';
  };

  const namedControls = name => [...document.querySelectorAll(`[name="${name}"]`)].filter(field => field.closest('[data-clinical-workspace]') || field.form === form);
  const isChecked = name => namedControls(name).some(field => field.checked && !field.disabled);
  const syncNamedChecks = name => {
    const controls = namedControls(name);
    controls.forEach(field => field.addEventListener('change', () => {
      controls.forEach(other => { if (other !== field && other.type === field.type && other.value === field.value) other.checked = field.checked; });
      refreshChecklist();
    }));
  };
  ['vitals_review_acknowledged', 'chart_review_acknowledged'].forEach(syncNamedChecks);
  const refreshVitalsSkipReason = () => {
    const checkbox = form.querySelector('[name="vitals_not_required"]');
    const shell = form.querySelector('[data-vitals-skip-reason]');
    const reason = form.querySelector('[name="vitals_skip_reason"]');
    const selected = Boolean(checkbox?.checked) && !vitalsRequired;
    if (shell) shell.hidden = !selected;
    if (reason) reason.required = selected;
    if (selected) namedControls('vitals_review_acknowledged').forEach(control => { control.checked = false; });
  };
  form.querySelector('[name="vitals_not_required"]')?.addEventListener('change', () => {
    refreshVitalsSkipReason();
    refreshChecklist();
  });
  form.querySelector('[name="vitals_skip_reason"]')?.addEventListener('input', refreshChecklist);
  document.querySelectorAll('[data-chart-review-mode-option]').forEach(field => field.addEventListener('change', () => {
    if (field.checked) workspace.dataset.chartReviewMode = field.value;
    namedControls('chart_review_acknowledged').forEach(control => { control.checked = true; });
    refreshChecklist();
  }));
  const prescriptionDecision = () => form.querySelector('[name="prescription_decision"]:checked')?.value || '';
  const prescriptionItemCount = () => [...form.querySelectorAll('[data-medicine-row]')].filter(row => {
    const input = row.querySelector('[name="medication_name[]"]');
    return input && input.value.trim() !== '';
  }).length;
  const chartReviewMode = () => namedControls('chart_review_mode').find(field => field.checked)?.value || workspace.dataset.chartReviewMode || '';
  const refreshCompletionDestination = () => {
    const destination = form.querySelector('[name="completion_destination"]:checked')?.value || 'cashier';
    const reason = form.querySelector('[data-no-payment-reason]');
    if (reason) {
      reason.hidden = destination !== 'no_payment';
      const field = reason.querySelector('textarea');
      if (field) field.required = destination === 'no_payment';
    }
    const button = form.querySelector('[data-finalize-treatment]');
    const sideButton = document.querySelector('[data-checklist-finalize]');
    const label = destination === 'no_payment' ? 'Complete—no payment required' : 'Complete and send to Cashier';
    if (button) button.textContent = label;
    if (sideButton) sideButton.textContent = label;
  };

  const refreshChecklist = () => {
    const intakeOkay = intakeComplete() && vitalsDecisionComplete();
    const intakeMessage = intakeOkay
      ? (vitalsSkipSelected() ? 'Focused safety review complete; routine vital signs documented as not required' : 'Intake and vital signs reviewed')
      : (!intakeComplete()
        ? (hpiRequired ? 'Complete intake, chief complaint, and history of present condition' : 'Complete the focused safety review and chief complaint')
        : (vitalsRequired ? 'Review the required vital signs' : 'Review available vital signs or document why routine vital signs are not required'));
    setComplete('intake', intakeOkay, intakeMessage);

    const alertsOkay = workspace.dataset.hasMedicalAlerts !== '1' || isChecked('medical_alert_review_acknowledged');
    setComplete('alerts', alertsOkay, alertsOkay ? (workspace.dataset.hasMedicalAlerts === '1' ? 'Active alerts acknowledged' : 'No active alert recorded') : 'Acknowledge active medical alerts');

    const examReady = !assessmentRequired || assessmentComplete();
    setComplete('assessment', examReady, examReady
      ? (assessmentRequired ? 'Domain status and examination summary recorded' : 'Full general examination skipped by the selected focused care path')
      : (!assessmentDomainComplete() ? 'Record at least one examination domain status' : 'Add the examination summary'));

    const chartOkay = isChecked('chart_review_acknowledged') && chartReviewMode() !== '';
    setComplete('charting', chartOkay, chartOkay ? `Dental chart reviewed: ${chartReviewMode().replaceAll('_', ' ')}` : (isChecked('chart_review_acknowledged') ? 'Choose today’s odontogram result' : 'Review the odontogram and choose no changes or update findings'));
    setComplete('diagnosis', diagnosisValues().length > 0 || visibleValue('diagnosis_summary') !== '');

    const treatmentReady = disposition() !== '' && (!requiresProcedure() || recordedProcedureCount() > 0);
    setComplete('disposition', treatmentReady, treatmentReady ? 'Outcome and required procedures recorded' : (disposition() === '' ? 'Select what happened during this visit' : 'Add each performed procedure'));

    const consentOkay = !requiresConsent() || linkedConsent() || emergencyConsent();
    setComplete('consent', consentOkay, consentOkay ? 'Not required or validly linked' : 'Obtain and link consent before finalizing');

    const rxDecision = prescriptionDecision();
    const rxCount = prescriptionItemCount();
    const prescriptionOkay = (rxDecision === 'not_required' && rxCount === 0) || (rxDecision === 'issued' && rxCount > 0);
    setComplete('prescription', prescriptionOkay, prescriptionOkay ? (rxDecision === 'issued' ? 'Prescription completed' : 'Marked not required') : 'Issue the prescription or mark it not required');

    setComplete('soap', visibleValue('soap_note') !== '');

    const instructionsOkay = isChecked('instructions_review_acknowledged') && (!requiresProcedure() || visibleValue('patient_advice') !== '');
    setComplete('instructions', instructionsOkay, instructionsOkay ? 'Patient advice and discharge instructions confirmed' : 'Complete and acknowledge patient instructions');

    const followReady = followComplete();
    setComplete('followup', followReady, followReady ? (followDecision() === 'none' ? 'No clinical follow-up required' : 'Recommendation ready for staff booking') : (followDecision() === '' ? 'Choose a follow-up decision' : 'Enter the purpose and recommended date'));

    const billingOkay = isChecked('billing_review_acknowledged') && Number(workspace.dataset.billingBlocked || '0') === 0;
    setComplete('billing', billingOkay, Number(workspace.dataset.billingBlocked || '0') > 0 ? 'Correct blocked procedure fee sources' : (billingOkay ? 'Billing handoff reviewed' : 'Review and acknowledge the billing handoff'));

    const items = [...document.querySelectorAll('[data-clinical-checklist] [data-check-item]')];
    const complete = items.filter(item => item.classList.contains('complete')).length;
    const count = document.querySelector('[data-completion-count]');
    if (count) count.textContent = `${complete} / ${items.length}`;
    const missingItems = items.filter(item => !item.classList.contains('complete'));
    const missing = missingItems.map(item => item.querySelector('strong')?.textContent || 'Required item');
    const nextMissingItem = missingItems[0] || null;
    const nextTitle = nextMissingItem?.querySelector('strong')?.textContent?.trim() || 'Ready to complete';
    const nextCopy = nextMissingItem?.querySelector('small')?.textContent?.trim() || 'All required clinical steps are complete. Select the completion outcome and finalize.';
    document.querySelectorAll('[data-next-required-label]').forEach(node => { node.textContent = nextTitle; });
    document.querySelectorAll('[data-next-required-copy]').forEach(node => { node.textContent = nextCopy; });
    document.querySelectorAll('[data-next-required-chip]').forEach(node => {
      node.textContent = missingItems.length ? `${missingItems.length} required item${missingItems.length === 1 ? '' : 's'} left` : 'Ready to complete';
      node.classList.toggle('success', missingItems.length === 0);
      node.classList.toggle('warning', missingItems.length > 0);
    });
    const blocker = document.querySelector('[data-completion-blockers]');
    if (blocker) {
      blocker.textContent = missing.length ? `Before completing: ${missing.join(', ')}.` : 'All completion requirements are ready.';
      blocker.className = `completion-blockers ${missing.length ? 'warning' : 'ready'}`;
    }
    document.querySelectorAll('[data-checklist-finalize],[data-finalize-treatment]').forEach(finalButton => {
      finalButton.disabled = missing.length > 0;
      finalButton.title = missing.length ? blocker?.textContent || 'Complete required items first.' : 'Finalize signed clinical record';
      finalButton.setAttribute('aria-disabled', missing.length > 0 ? 'true' : 'false');
    });
    document.querySelectorAll('[data-cockpit-step]').forEach(step => {
      const item = document.querySelector(`[data-check-item="${step.dataset.cockpitStep}"]`);
      const done = item?.classList.contains('complete') || false;
      step.classList.toggle('complete', done);
      step.classList.toggle('missing', !done);
      const mark = step.querySelector('span');
      if (mark) mark.textContent = done ? '✓' : mark.textContent.replace('✓', '') || '!';
    });
    const stageStatus = { intake: 'intake', alerts: 'completion', assessment: 'examination', charting: 'charting', diagnosis: 'diagnosis', disposition: 'treatment', consent: 'treatment', prescription: 'prescription', soap: 'notes', instructions: 'completion', followup: 'followup', billing: 'completion' };
    document.querySelectorAll('[data-clinical-target]').forEach(button => {
      const related = items.filter(item => stageStatus[item.dataset.checkItem] === button.dataset.clinicalTarget);
      const stageComplete = related.length > 0 && related.every(item => item.classList.contains('complete'));
      const stageMissing = related.some(item => item.classList.contains('missing'));
      button.classList.toggle('stage-complete', stageComplete);
      button.classList.toggle('stage-missing', stageMissing);
      button.setAttribute('aria-label', `${button.textContent.trim()}${stageComplete ? ', complete' : stageMissing ? ', incomplete' : ''}`);
    });
    const phaseRequirements = {
      review: ['intake', 'alerts'],
      assess: ['assessment', 'charting', 'diagnosis'],
      treat: ['disposition', 'consent', 'prescription'],
      close: ['soap', 'instructions', 'followup', 'billing'],
    };
    document.querySelectorAll('[data-clinical-phase-target]').forEach(button => {
      const required = phaseRequirements[button.dataset.clinicalPhaseTarget] || [];
      const related = items.filter(item => required.includes(item.dataset.checkItem));
      const completeCount = related.filter(item => item.classList.contains('complete')).length;
      const phaseComplete = related.length > 0 && completeCount === related.length;
      const phaseMissing = related.some(item => item.classList.contains('missing'));
      button.classList.toggle('phase-complete', phaseComplete);
      button.classList.toggle('phase-missing', phaseMissing);
      const state = button.querySelector('[data-phase-state]');
      if (state) state.textContent = phaseComplete ? 'Complete' : `${completeCount} of ${related.length} required items`;
      button.setAttribute('aria-label', `${button.querySelector('strong')?.textContent || 'Clinical phase'}${phaseComplete ? ', complete' : phaseMissing ? ', incomplete' : ''}`);
    });
    refreshCompletionDestination();
    return missingItems;
  };

  const refreshExamDomain = domain => {
    const state = domain.querySelector('[data-exam-status]')?.value || 'not_examined';
    const detail = domain.querySelector('[data-exam-detail]');
    if (!detail) return;
    const relevant = state === 'abnormal';
    detail.hidden = !relevant && detail.value.trim() === '';
    detail.required = relevant;
    domain.classList.toggle('abnormal', relevant);
    domain.classList.toggle('complete', !['', 'not_examined'].includes(state));
  };
  document.querySelectorAll('[data-exam-domain]').forEach(domain => {
    const select = domain.querySelector('[data-exam-status]');
    select?.addEventListener('change', () => { refreshExamDomain(domain); refreshGeneratedExaminationSummary(); refreshChecklist(); });
    domain.querySelector('[data-exam-detail]')?.addEventListener('input', () => { refreshGeneratedExaminationSummary(); refreshChecklist(); });
    refreshExamDomain(domain);
  });
  examinationSummaryField?.addEventListener('input', () => { examinationSummaryField.dataset.generatedSummary = '0'; refreshChecklist(); });

  const diagnosisTemplate = document.getElementById('diagnosis-row-template');
  const diagnosisList = document.querySelector('[data-diagnosis-list]');
  const renumberDiagnoses = () => {
    [...document.querySelectorAll('[data-diagnosis-row]')].forEach((row, index) => {
      const label = row.querySelector('[data-diagnosis-label]');
      if (label) label.textContent = index === 0 ? 'Primary diagnosis' : `Additional diagnosis ${index + 1}`;
      const remove = row.querySelector('[data-remove-diagnosis]');
      if (remove) remove.hidden = index === 0 && document.querySelectorAll('[data-diagnosis-row]').length === 1;
    });
  };
  const attachDiagnosisRow = row => {
    row.querySelector('[data-remove-diagnosis]')?.addEventListener('click', () => {
      const rows = document.querySelectorAll('[data-diagnosis-row]');
      if (rows.length === 1) {
        row.querySelectorAll('input,textarea').forEach(field => { if (field.type === 'checkbox') field.checked = false; else field.value = ''; });
        row.querySelector('[data-diagnosis-status]').value = 'provisional';
        row.querySelector('[data-diagnosis-surface-control]')?.setAttribute('hidden', '');
      } else row.remove();
      renumberDiagnoses();
      refreshChecklist();
    });
    const input = row.querySelector('[data-diagnosis-search]');
    const results = row.querySelector('[data-diagnosis-results]');
    const code = row.querySelector('[data-diagnosis-code]');
    const status = row.querySelector('[data-diagnosis-status]');
    const region = row.querySelector('[data-diagnosis-region]');
    const surfaceControl = row.querySelector('[data-diagnosis-surface-control]');
    const surfaceHidden = row.querySelector('[data-diagnosis-surfaces]');
    const surfaceTitle = row.querySelector('[data-diagnosis-surface-title]');
    const surfaceHelp = row.querySelector('[data-diagnosis-surface-help]');
    const surfaceOptions = [...row.querySelectorAll('[data-diagnosis-surface-option]')];
    const extractTooth = () => {
      const match = String(region?.value || '').match(/(?:^|\D)([1-8][1-8])(?:\D|$)/);
      if (!match) return '';
      const tooth = match[1];
      const quadrant = Number(tooth[0]);
      const position = Number(tooth[1]);
      return quadrant <= 4 ? (position >= 1 && position <= 8 ? tooth : '') : (position >= 1 && position <= 5 ? tooth : '');
    };
    const syncSurfaceHidden = () => {
      if (!surfaceHidden) return;
      surfaceHidden.value = surfaceOptions.filter(option => !option.hidden && option.querySelector('input')?.checked).map(option => option.querySelector('input').value).join(',');
    };
    const refreshDiagnosisSurfaces = () => {
      if (!surfaceControl) return;
      const tooth = extractTooth();
      const anterior = tooth !== '' && Number(tooth[1]) <= 3;
      surfaceControl.hidden = tooth === '';
      if (surfaceTitle) surfaceTitle.textContent = tooth ? `Tooth ${tooth} surfaces — ${anterior ? 'Anterior' : 'Posterior'}` : 'Affected tooth surface';
      surfaceOptions.forEach(option => {
        const scope = option.dataset.surfaceScope || 'all';
        option.hidden = tooth === '' || (scope === 'anterior' && !anterior) || (scope === 'posterior' && anterior);
        if (option.hidden) option.querySelector('input').checked = false;
      });
      if (surfaceHelp) {
        const caries = /\b(caries|carious|decay|cavity)\b/i.test(String(input?.value || '')) || /^K0?2/i.test(String(code?.value || ''));
        surfaceHelp.textContent = tooth === ''
          ? 'Enter a valid FDI tooth number to choose a surface.'
          : caries
            ? `For precise caries charting choose: ${anterior ? 'Mesial, Distal, Facial, or Lingual' : 'Mesial, Distal, Lingual, or Buccal'}.`
            : 'Optional for general diagnoses. Selecting a surface maps the diagnosis precisely on the dental chart.';
      }
      syncSurfaceHidden();
    };
    if (surfaceHidden?.value) {
      const selected = surfaceHidden.value.split(',').map(value => value.trim()).filter(Boolean);
      surfaceOptions.forEach(option => { option.querySelector('input').checked = selected.includes(option.querySelector('input').value); });
    }
    surfaceOptions.forEach(option => option.querySelector('input')?.addEventListener('change', syncSurfaceHidden));
    region?.addEventListener('input', refreshDiagnosisSurfaces);
    input?.addEventListener('input', refreshDiagnosisSurfaces);
    code?.addEventListener('input', refreshDiagnosisSurfaces);
    refreshDiagnosisSurfaces();
    if (!input || !results) return;
    const search = debounce(async () => {
      const q = input.value.trim();
      if (q.length < 2) { results.hidden = true; results.replaceChildren(); return; }
      try {
        const response = await fetch(`api/diagnosis_search.php?q=${encodeURIComponent(q)}`, { headers: { Accept: 'application/json' } });
        const data = await response.json();
        const rows = Array.isArray(data.results) ? data.results : [];
        results.replaceChildren(...rows.map(item => {
          const button = document.createElement('button');
          button.type = 'button';
          const title = document.createElement('strong');
          title.textContent = String(item.name || '');
          const meta = document.createElement('small');
          meta.textContent = `${String(item.code || 'No code')}${item.category ? ` · ${String(item.category)}` : ''}`;
          button.append(title, meta);
          button.addEventListener('click', () => {
            input.value = item.name || '';
            if (code) code.value = item.code || '';
            if (status && item.default_status) status.value = item.default_status;
            results.hidden = true;
            results.replaceChildren();
            input.dispatchEvent(new Event('input', { bubbles: true }));
          });
          return button;
        }));
        results.hidden = rows.length === 0;
      } catch (_) {
        results.hidden = true;
      }
    });
    input.addEventListener('input', () => { search(); refreshChecklist(); });
    input.addEventListener('blur', () => window.setTimeout(() => { results.hidden = true; }, 180));
  };
  document.querySelectorAll('[data-diagnosis-row]').forEach(attachDiagnosisRow);
  document.querySelector('[data-add-diagnosis]')?.addEventListener('click', () => {
    if (!diagnosisTemplate || !diagnosisList) return;
    const row = diagnosisTemplate.content.firstElementChild.cloneNode(true);
    diagnosisList.append(row);
    attachDiagnosisRow(row);
    renumberDiagnoses();
    row.querySelector('[data-diagnosis-search]')?.focus();
  });
  renumberDiagnoses();


  const applyHealthyDentitionShortcut = () => {
    namedControls('chart_review_mode').forEach(field => { field.checked = field.value === 'no_changes'; });
    workspace.dataset.chartReviewMode = 'no_changes';
    namedControls('chart_review_acknowledged').forEach(field => { field.checked = true; });
    const diagnosisName = form.querySelector('[name="diagnosis_name[]"]');
    const diagnosisCode = form.querySelector('[name="diagnosis_code[]"]');
    const diagnosisStatus = form.querySelector('[name="diagnosis_status[]"]');
    const diagnosisRegion = form.querySelector('[name="diagnosis_region[]"]');
    const diagnosisNotes = form.querySelector('[name="diagnosis_notes[]"]');
    if (diagnosisName && !diagnosisName.value.trim()) diagnosisName.value = 'Healthy dentition / no active dental disease';
    if (diagnosisCode && !diagnosisCode.value.trim()) diagnosisCode.value = 'HEALTHY';
    if (diagnosisStatus) diagnosisStatus.value = 'confirmed';
    if (diagnosisRegion && !diagnosisRegion.value.trim()) diagnosisRegion.value = 'General dentition';
    if (diagnosisNotes && !diagnosisNotes.value.trim()) diagnosisNotes.value = 'Odontogram reviewed today. No abnormal tooth findings recorded.';
    const diagnosisSummary = form.querySelector('[name="diagnosis_summary"]');
    if (diagnosisSummary && !diagnosisSummary.value.trim()) diagnosisSummary.value = 'Healthy dentition / no active dental disease';
    const dispositionSelect = form.querySelector('[name="clinical_disposition"]');
    if (dispositionSelect && !dispositionSelect.value) dispositionSelect.value = 'no_treatment_required';
    const dispositionReason = form.querySelector('[name="disposition_reason"]');
    if (dispositionReason && !dispositionReason.value.trim()) dispositionReason.value = 'Oral examination and odontogram reviewed. No active treatment required today.';
    const rxNotRequired = form.querySelector('[name="prescription_decision"][value="not_required"]');
    if (rxNotRequired && prescriptionItemCount() === 0) rxNotRequired.checked = true;
    refreshDisposition();
    refreshChecklist();
    focusTreatmentField(diagnosisName || diagnosisSummary || dispositionSelect, 'Healthy/no findings path applied. Review the diagnosis and continue to SOAP/follow-up.');
  };
  document.querySelectorAll('[data-healthy-dentition-shortcut]').forEach(button => button.addEventListener('click', event => {
    event.preventDefault();
    applyHealthyDentitionShortcut();
  }));

  const usageTemplate = document.getElementById('usage-row-template');
  const usageList = document.querySelector('[data-usage-list]');
  const refreshUsageRow = row => {
    const type = row.querySelector('[data-usage-type]')?.value || '';
    const inventory = row.querySelector('[data-usage-inventory]');
    const description = row.querySelector('[data-usage-description]');
    const unit = row.querySelector('[data-usage-unit]');
    const billing = row.querySelector('[data-usage-billing]');
    const price = row.querySelector('[data-usage-price]');
    const inventoryRequired = ['medication_administered', 'medicine_dispense', 'consumable'].includes(type);
    if (inventory) inventory.required = inventoryRequired;
    if (price) {
      const billable = billing?.value === 'bill_separately';
      price.disabled = !billable;
      price.required = billable;
    }
    row.classList.toggle('inventory-required', inventoryRequired);
    row.querySelector('.usage-row-head strong').textContent = ({
      medication_administered: 'Medication administered', medicine_dispense: 'Medicine to dispense', consumable: 'Consumable material', equipment: 'Equipment utilization', diagnostic_service: 'Diagnostic service'
    })[type] || 'Clinical usage';
    if (inventory?.value) {
      const option = inventory.selectedOptions?.[0];
      if (description && (!description.value.trim() || description.dataset.autofilled === '1')) { description.value = option?.dataset.name || ''; description.dataset.autofilled = '1'; }
      if (unit && (!unit.value.trim() || unit.dataset.autofilled === '1')) { unit.value = option?.dataset.unit || ''; unit.dataset.autofilled = '1'; }
      if (price && Number(price.value || 0) === 0 && billing?.value === 'bill_separately') price.value = option?.dataset.price || '0';
    }
  };
  const attachUsageRow = row => {
    row.querySelector('[data-remove-usage]')?.addEventListener('click', () => { row.remove(); refreshChecklist(); });
    row.querySelector('[data-usage-type]')?.addEventListener('change', () => refreshUsageRow(row));
    row.querySelector('[data-usage-inventory]')?.addEventListener('change', () => refreshUsageRow(row));
    row.querySelector('[data-usage-billing]')?.addEventListener('change', () => refreshUsageRow(row));
    refreshUsageRow(row);
  };
  document.querySelectorAll('[data-usage-row]').forEach(attachUsageRow);
  const addUsageRow = (defaults = {}) => {
    if (!usageTemplate || !usageList) return null;
    const row = usageTemplate.content.firstElementChild.cloneNode(true);
    usageList.append(row);
    attachUsageRow(row);
    if (defaults.type) row.querySelector('[data-usage-type]').value = defaults.type;
    if (defaults.description) row.querySelector('[data-usage-description]').value = defaults.description;
    const quantity = row.querySelector('[name="usage_quantity[]"]');
    if (quantity && Number(defaults.quantity) > 0) quantity.value = String(defaults.quantity);
    const billing = row.querySelector('[data-usage-billing]');
    if (billing && defaults.billing) billing.value = defaults.billing;
    const inventory = row.querySelector('[data-usage-inventory]');
    if (inventory && defaults.match) {
      const needle = String(defaults.match).toLocaleLowerCase();
      const option = [...inventory.options].find(candidate => candidate.value && String(candidate.dataset.name || candidate.textContent || '').toLocaleLowerCase().includes(needle));
      if (option) inventory.value = option.value;
    }
    refreshUsageRow(row);
    return row;
  };
  document.querySelector('[data-add-usage]')?.addEventListener('click', () => {
    const row = addUsageRow();
    row?.querySelector('[data-usage-type]')?.focus();
  });
  document.addEventListener('dental:request-clinic-dispense', event => {
    const detail = event.detail || {};
    const description = [detail.medicineName || detail.genericName, detail.strength].filter(Boolean).join(' · ');
    const match = detail.medicineName || detail.genericName || '';
    const numericQuantity = Number.parseFloat(String(detail.quantity || '').replace(/[^0-9.]/g, ''));
    const row = addUsageRow({ type: 'medicine_dispense', description, quantity: Number.isFinite(numericQuantity) && numericQuantity > 0 ? numericQuantity : 1, billing: 'bill_separately', match });
    document.querySelector('[data-clinical-target="treatment"]')?.click();
    row?.scrollIntoView({ behavior: 'smooth', block: 'center' });
    row?.querySelector('[data-usage-inventory]')?.focus();
  });

  const refreshDisposition = () => {
    const value = disposition();
    const procedurePanel = document.querySelector('[data-procedure-panel]');
    if (procedurePanel) {
      const show = ['treatment_performed', 'emergency_stabilization', 'diagnostic_procedure', 'medication_administered'].includes(value) || recordedProcedureCount() > 0;
      procedurePanel.hidden = !show;
    }
    refreshChecklist();
  };
  form.querySelector('[data-clinical-disposition]')?.addEventListener('change', refreshDisposition);
  form.querySelector('[data-emergency-consent]')?.addEventListener('change', event => {
    const field = form.querySelector('[data-emergency-reason]');
    if (field) field.hidden = !event.target.checked;
    refreshChecklist();
  });
  form.querySelector('[name="consent_exception_reason"]')?.addEventListener('input', refreshChecklist);
  const refreshFollowupDecision = () => {
    const none = followDecision() === 'none';
    const recommended = followDecision() === 'recommended';
    ['follow_up_purpose', 'follow_up_date', 'follow_up_time', 'follow_up_urgency', 'follow_up_service_id', 'follow_up_duration', 'follow_up_instructions'].forEach(name => {
      const field = form.querySelector(`[name="${name}"]`);
      if (field) field.disabled = none;
    });
    const fields = form.querySelector('[data-follow-up-fields]');
    if (fields) {
      fields.classList.toggle('is-disabled', none);
      fields.classList.toggle('is-required', recommended);
    }
    refreshChecklist();
  };
  form.querySelectorAll('[data-follow-up-decision]').forEach(field => field.addEventListener('change', refreshFollowupDecision));

  const focusClinicalRequirement = key => {
    const stageFor = requirementKey => {
      if (requirementKey === 'intake') {
        return 'intake';
      }
      return ({ alerts: 'completion', assessment: 'examination', charting: 'charting', diagnosis: 'diagnosis', disposition: 'treatment', consent: 'treatment', prescription: 'prescription', soap: 'notes', instructions: 'completion', followup: 'followup', billing: 'completion' }[requirementKey] || 'intake');
    };
    const stage = stageFor(key);
    document.querySelector(`[data-clinical-target="${stage}"]`)?.click();
    window.setTimeout(() => {
      let target = null;
      let message = '';
      if (key === 'intake') {
        const panel = document.querySelector('[data-clinical-panel="intake"]');
        const details = panel?.querySelector('details');
        if (details) details.open = true;
        const complaint = intakeForm?.querySelector('[name="intake_chief_complaint"]');
        const hpi = intakeForm?.querySelector('[name="intake_hpi"]');
        const allergies = intakeForm?.querySelector('[name="allergies_confirmed"]');
        const medicines = intakeForm?.querySelector('[name="medications_confirmed"]');
        const acknowledged = intakeForm?.querySelector('[name="consent_acknowledged"]');
        const vitalsReview = namedControls('vitals_review_acknowledged')[0];
        const save = intakeForm?.querySelector('button[type="submit"],button:not([type])');
        if (!complaint?.value.trim()) { target = complaint; message = 'Next: type the patient’s chief complaint.'; }
        else if (hpiRequired && !hpi?.value.trim()) { target = hpi; message = 'Next: enter the history of present condition.'; }
        else if (!allergies?.checked && workspace.dataset.intakeConfirmationsReady !== '1') { target = allergies; message = 'Next: confirm allergies while still in intake.'; }
        else if (!medicines?.checked && workspace.dataset.intakeConfirmationsReady !== '1') { target = medicines; message = 'Next: confirm current medicines.'; }
        else if (!acknowledged?.checked && workspace.dataset.intakeConfirmationsReady !== '1') { target = acknowledged; message = 'Next: confirm the patient or guardian intake acknowledgement.'; }
        else if (!intakeComplete() && save) { target = save; message = hpiRequired ? 'Next: save the completed intake and vital signs.' : 'Next: save the focused safety review.'; }
        else if (!vitalsDecisionComplete()) {
          if (vitalsRequired) {
            target = vitalsReview;
            message = 'Next: review the required vital signs.';
          } else {
            target = form.querySelector('[name="vitals_not_required"]') || vitalsReview;
            message = 'Next: review available vital signs or document why routine vital signs are not required.';
          }
        }
        else { target = save || vitalsReview; message = vitalsSkipSelected() ? 'Focused safety review is complete.' : 'Intake and vital signs are complete.'; }
      } else if (key === 'alerts') {
        target = form.querySelector('[name="medical_alert_review_acknowledged"]');
        message = 'Next: acknowledge active medical alerts before treatment release.';
      } else if (key === 'assessment') {
        if (!assessmentRequired) {
          target = document.querySelector('[data-clinical-panel="charting"]');
          message = 'The selected focused care path skips the full general examination. Continue with the tooth chart.';
        } else {
          target = !assessmentDomainComplete() ? [...form.querySelectorAll('[data-exam-status]')].find(field => field.value === 'not_examined') : (!visibleValue('examination_summary') ? form.querySelector('[name="examination_summary"]') : null);
          message = !assessmentDomainComplete() ? 'Next: choose the first examination domain status.' : 'Next: confirm or edit the examination summary.';
        }
      } else if (key === 'charting') {
        const modeField = namedControls('chart_review_mode').find(field => !field.checked) || namedControls('chart_review_mode')[0];
        target = !chartReviewMode() ? modeField : (namedControls('chart_review_acknowledged').find(field => !field.checked) || document.querySelector('[data-clinical-panel="charting"] a'));
        message = !chartReviewMode() ? 'Next: choose today’s odontogram result. Healthy teeth can use Reviewed today — no changes.' : 'Next: acknowledge that the odontogram was reviewed for this visit.';
      } else if (key === 'diagnosis') {
        target = [...form.querySelectorAll('[name="diagnosis_name[]"]')].find(field => !field.value.trim()) || form.querySelector('[name="diagnosis_name[]"]') || form.querySelector('[name="diagnosis_summary"]') || document.querySelector('[data-add-diagnosis]');
        message = 'Next: enter at least one diagnosis.';
      } else if (key === 'disposition') {
        target = !disposition() ? form.querySelector('[name="clinical_disposition"]') : (requiresProcedure() && recordedProcedureCount() === 0 ? document.querySelector('[data-open="procedure-add-form"]') : form.querySelector('[name="disposition_reason"]'));
        message = !disposition() ? 'Next: select what happened during this visit.' : 'Next: add the performed procedure or document the outcome.';
      } else if (key === 'procedure') {
        target = document.querySelector('[data-open="procedure-add-form"]') || document.querySelector('[data-clinical-procedure]');
        message = 'Next: add or review the performed procedure.';
      } else if (key === 'consent') {
        target = document.querySelector('[data-consent-status] a') || form.querySelector('[data-emergency-consent]') || form.querySelector('[name="consent_exception_reason"]');
        message = 'Next: link treatment consent or document a valid emergency exception.';
      } else if (key === 'prescription') {
        target = firstEnabled(['[data-prescription-decision-primary] [name="prescription_decision"]', '[name="prescription_decision"]', '[name="medication_name[]"]'], form);
        message = 'Next: choose Prescription issued or No prescription required. If no medicine is needed, select No prescription required.';
      } else if (key === 'soap') {
        target = form.querySelector('[name="soap_note"]');
        message = 'Next: complete the signed SOAP narrative.';
      } else if (key === 'instructions') {
        target = !visibleValue('patient_advice') && requiresProcedure() ? form.querySelector('[name="patient_advice"]') : form.querySelector('[name="instructions_review_acknowledged"]');
        message = 'Next: confirm patient advice and discharge instructions.';
      } else if (key === 'billing') {
        target = form.querySelector('[name="billing_review_acknowledged"]');
        message = 'Next: verify the billing or no-payment handoff.';
      } else if (key === 'followup') {
        target = followDecision() === '' ? form.querySelector('[name="follow_up_decision"]') : followDecision() === 'recommended' && !visibleValue('follow_up_purpose') ? form.querySelector('[name="follow_up_purpose"]') : followDecision() === 'recommended' && !visibleValue('follow_up_date') ? form.querySelector('[name="follow_up_date"]') : form.querySelector('[name="follow_up_decision"]:checked');
        message = followDecision() === '' ? 'Next: choose a follow-up decision.' : 'Next: complete the follow-up details.';
      }
      if (target && !target.disabled) {
        focusTreatmentField(target, message);
      } else {
        const panel = document.querySelector(`[data-clinical-panel="${stage}"]`);
        if (panel) focusTreatmentField(panel, 'Continue in this treatment section.');
      }
    }, 40);
  };
  const focusNextClinicalRequirement = () => {
    refreshChecklist();
    const missing = [...document.querySelectorAll('[data-clinical-checklist] [data-check-item].missing')][0];
    if (!missing) {
      const finalizeButton = form.querySelector('[data-finalize-treatment]') || document.querySelector('[data-checklist-finalize]');
      if (finalizeButton) focusTreatmentField(finalizeButton, 'All treatment requirements are ready. Choose the completion outcome and finalize.');
      return;
    }
    focusClinicalRequirement(missing.dataset.checkItem || 'intake');
  };
  document.querySelectorAll('[data-clinical-checklist] [data-check-item]').forEach(item => {
    item.tabIndex = 0;
    item.setAttribute('role', 'button');
    item.addEventListener('click', () => focusClinicalRequirement(item.dataset.checkItem || 'intake'));
    item.addEventListener('keydown', event => {
      if (event.key !== 'Enter' && event.key !== ' ') return;
      event.preventDefault();
      focusClinicalRequirement(item.dataset.checkItem || 'intake');
    });
  });
  document.querySelectorAll('[data-clinical-jump]').forEach(button => button.addEventListener('click', () => {
    const target = button.dataset.clinicalJump || 'charting';
    document.querySelector(`[data-clinical-target="${target}"]`)?.click();
  }));
  refreshVitalsSkipReason();
  if (!window.location.hash && !workspace.dataset.focusRequirement && ['charting', 'treatment'].includes(workspace.dataset.defaultClinicalTarget || '')) {
    window.setTimeout(() => document.querySelector(`[data-clinical-target="${workspace.dataset.defaultClinicalTarget}"]`)?.click(), 120);
  }

  window.DentalClinicalFocusRequirement = focusClinicalRequirement;
  window.DentalClinicalFocusNext = focusNextClinicalRequirement;
  window.DentalClinicalRefreshChecklist = refreshChecklist;
  document.querySelectorAll('[data-next-clinical-required]').forEach(button => button.addEventListener('click', event => {
    event.preventDefault();
    event.stopImmediatePropagation();
    focusNextClinicalRequirement();
  }));
  document.addEventListener('keydown', event => {
    if (event.altKey && event.key.toLowerCase() === 'n') {
      event.preventDefault();
      event.stopImmediatePropagation();
      focusNextClinicalRequirement();
    }
  }, true);

  const clinicalValidateTarget = event => {
    const target = event.target;
    if (!(target instanceof HTMLElement) || !target.matches('input,select,textarea')) return;
    if (!target.closest('[data-clinical-workspace]')) return;
    updateClinicalFieldWarning(target);
    refreshChecklist();
  };
  document.addEventListener('input', clinicalValidateTarget);
  document.addEventListener('change', clinicalValidateTarget);
  document.addEventListener('blur', clinicalValidateTarget, true);
  document.querySelectorAll('[data-clinical-workspace] [required], [data-clinical-workspace] [data-required-first]').forEach(updateClinicalFieldWarning);

  document.querySelectorAll('[data-clinical-workspace] form').forEach(clinicalForm => {
    clinicalForm.addEventListener('keydown', event => {
      if (event.defaultPrevented || event.isComposing || event.altKey || event.ctrlKey || event.metaKey) return;
      if (event.key !== 'Enter') return;
      const target = event.target;
      if (!(target instanceof HTMLElement)) return;
      if (target.matches('button,[type="submit"],[type="button"],[type="checkbox"],[type="radio"],[type="file"]')) return;
      if (target.tagName.toLowerCase() === 'textarea') return;
      const fields = [...clinicalForm.querySelectorAll('input:not([type="hidden"]),select,textarea,button[type="submit"],button:not([type])')].filter(field => !field.disabled && !field.hidden && field.offsetParent !== null);
      const missing = fields.find(field => field !== target && (field.required || field.matches?.('[data-required-first]')) && ((field.matches?.('[type="checkbox"],[type="radio"]') && !field.checked) || (!field.matches?.('[type="checkbox"],[type="radio"],button') && String(field.value || '').trim() === '')));
      const index = fields.indexOf(target);
      const next = missing || fields[index + 1];
      if (next) {
        event.preventDefault();
        focusTreatmentField(next, missing ? 'Next missing required field.' : 'Next field.');
      }
    });
  });

  form.addEventListener('input', refreshChecklist);
  form.addEventListener('change', refreshChecklist);
  form.addEventListener('submit', event => {
    if (!event.submitter?.matches('[data-finalize-treatment]')) return;
    const missing = refreshChecklist();
    if (missing.length) {
      event.preventDefault();
      focusClinicalRequirement(missing[0].dataset.checkItem || 'intake');
    }
  });
  document.querySelector('[data-checklist-save]')?.addEventListener('click', () => form.querySelector('[data-save-draft]')?.click());
  document.querySelector('[data-checklist-finalize]')?.addEventListener('click', () => {
    const missing = refreshChecklist();
    if (missing.length) { focusClinicalRequirement(missing[0].dataset.checkItem || 'intake'); return; }
    form.querySelector('[data-finalize-treatment]')?.click();
  });
  form.querySelectorAll('[data-completion-destination]').forEach(field => field.addEventListener('change', refreshCompletionDestination));
  refreshGeneratedExaminationSummary();
  refreshDisposition();
  refreshFollowupDecision();
  refreshChecklist();
  const requestedFocus = workspace.dataset.focusRequirement || '';
  const hasHash = Boolean(window.location.hash && window.location.hash.length > 1);
  if (workspace.dataset.canWrite === '1' && requestedFocus) window.setTimeout(() => focusClinicalRequirement(requestedFocus), 180);
  else if (workspace.dataset.canWrite === '1' && workspace.dataset.autoFocusFirstMissing === '1' && !hasHash) window.setTimeout(() => focusNextClinicalRequirement(), 320);
})();

(() => {
  // DentalCare 0.7.4: compact clinical guide text into contextual hover/click popouts.
  const workspace = document.querySelector('[data-clinical-workspace]');
  if (!workspace || document.body.dataset.compactClinicalGuidesApplied === '1') return;
  document.body.dataset.compactClinicalGuidesApplied = '1';
  document.body.classList.add('clinical-compact-guides-active');
  const selectors = [
    '.clinical-workspace-main .card-head p',
    '.clinical-workspace-main .section-heading p',
    '.clinical-workspace-main .clinical-command-strip small',
    '.clinical-workspace-main .check-label small',
    '.clinical-workspace-main label small',
    '.clinical-workspace-main .bp-measurement-guide p',
    '.clinical-workspace-main .bp-screening-panel small',
    '.clinical-workspace-main .muted:not(.keep-inline-help)',
    '.clinical-workspace-main .hint:not(.keep-inline-help)'
  ];
  const makeHelp = text => {
    const wrap = document.createElement('span');
    wrap.className = 'context-help auto-context-help';
    wrap.tabIndex = 0;
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'context-help-trigger';
    btn.setAttribute('aria-expanded', 'false');
    btn.textContent = '?';
    const pop = document.createElement('span');
    pop.className = 'context-help-popover';
    pop.setAttribute('role', 'tooltip');
    pop.textContent = text;
    wrap.append(btn, pop);
    return wrap;
  };
  document.querySelectorAll(selectors.join(',')).forEach(node => {
    if (!(node instanceof HTMLElement)) return;
    if (node.dataset.contextHelpified === '1' || node.closest('.context-help,.context-help-popover,.alert,.flash,.badge,.table-responsive,.status-actions,.clinical-treatment-cockpit')) return;
    const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
    if (text.length < 12) return;
    node.dataset.contextHelpified = '1';
    node.classList.add('context-help-source');
    node.insertAdjacentElement('afterend', makeHelp(text));
  });
  document.addEventListener('click', event => {
    const trigger = event.target instanceof Element ? event.target.closest('[data-context-help-toggle], .context-help-trigger') : null;
    if (!trigger) return;
    const help = trigger.closest('.context-help, .clinical-flow-reference-popout');
    if (!help) return;
    event.preventDefault();
    const isOpen = help.classList.toggle('open');
    trigger.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    document.querySelectorAll('.context-help.open, .clinical-flow-reference-popout.open').forEach(other => {
      if (other === help) return;
      other.classList.remove('open');
      other.querySelector('.context-help-trigger')?.setAttribute('aria-expanded', 'false');
    });
  }, true);
})();
