(() => {
  const numberValue = field => {
    if (!field || String(field.value).trim() === '') return null;
    const value = Number(field.value);
    return Number.isFinite(value) ? value : null;
  };

  const setStatus = (panel, label, message, state) => {
    if (!panel) return;
    panel.classList.remove('neutral', 'success', 'info', 'warning', 'danger');
    panel.classList.add(state);
    const title = panel.querySelector('[data-bp-status-label]');
    const copy = panel.querySelector('[data-bp-status-message]');
    if (title) title.textContent = label;
    if (copy) copy.textContent = message;
  };

  const bpAssessment = (sys, dia, age, symptomsSelected) => {
    if (sys === null || dia === null) return ['Not recorded', 'Record both systolic and diastolic values.', 'neutral'];
    if (sys <= dia) return ['Recheck values', 'Systolic pressure must be higher than diastolic pressure.', 'danger'];
    if (sys >= 180 || dia >= 120) {
      return symptomsSelected
        ? ['Emergency symptoms recorded', 'Stop routine workflow and follow the clinic emergency-response protocol.', 'danger']
        : ['Urgent review', 'Repeat after at least one minute and obtain immediate clinician review.', 'danger'];
    }
    if (age <= 0) return ['Clinical review', 'Patient age is unavailable; interpret the screening reading clinically.', 'info'];
    if (age < 18) return ['Pediatric review', 'Interpret using age-, sex-, and height-appropriate clinical references.', 'info'];
    if (sys >= 140 || dia >= 90) return ['High reading — stage 2 range', 'Repeat and have the treating clinician review before proceeding.', 'warning'];
    if (sys >= 130 || dia >= 80) return ['High reading — stage 1 range', 'Document and have the treating clinician review the screening result.', 'warning'];
    if (sys >= 120 && dia < 80) return ['Elevated reading', 'Document the result and continue clinical review.', 'info'];
    return ['Routine adult range', 'Screening reading is below 120/80 mmHg.', 'success'];
  };

  const attachForm = form => {
    const age = Number(form.dataset.patientAge || 0);
    const sys = form.querySelector('[data-bp-systolic], [name="bp_systolic"], [name="blood_pressure_systolic"]');
    const dia = form.querySelector('[data-bp-diastolic], [name="bp_diastolic"], [name="blood_pressure_diastolic"]');
    const repeatSys = form.querySelector('[data-bp-repeat-systolic], [name="bp_repeat_systolic"]');
    const repeatDia = form.querySelector('[data-bp-repeat-diastolic], [name="bp_repeat_diastolic"]');
    const panel = form.querySelector('[data-bp-status]');
    const symptomPanel = form.querySelector('[data-bp-symptoms]');
    const symptomReview = form.querySelector('[name="bp_symptoms_reviewed"]');
    const measurementConfirmed = form.querySelector('[name="bp_measurement_confirmed"]');
    const repeatShell = form.querySelector('[data-bp-repeat-shell]');
    const showRepeat = form.querySelector('[data-show-bp-repeat]');
    const hideRepeat = form.querySelector('[data-hide-bp-repeat]');
    const weight = form.querySelector('[data-vital-weight], [name="weight_kg"]');
    const height = form.querySelector('[data-vital-height], [name="height_cm"]');
    const bmiOutput = form.querySelector('[data-vital-bmi]');

    const symptomsSelected = () => [...form.querySelectorAll('[name="bp_symptoms[]"]')].some(field => field.checked);
    const currentBp = () => {
      const rs = numberValue(repeatSys);
      const rd = numberValue(repeatDia);
      if (rs !== null && rd !== null) return [rs, rd, true];
      return [numberValue(sys), numberValue(dia), false];
    };
    const refreshBp = () => {
      const firstSystolic = numberValue(sys);
      const firstDiastolic = numberValue(dia);
      const repeatSystolic = numberValue(repeatSys);
      const repeatDiastolic = numberValue(repeatDia);
      const firstExtreme = firstSystolic !== null && firstDiastolic !== null && (firstSystolic >= 180 || firstDiastolic >= 120);
      const repeatExtreme = repeatSystolic !== null && repeatDiastolic !== null && (repeatSystolic >= 180 || repeatDiastolic >= 120);
      const anyExtreme = firstExtreme || repeatExtreme;
      const [s, d] = currentBp();
      let assessment = bpAssessment(s, d, age, symptomsSelected());
      if (firstExtreme && repeatSystolic !== null && repeatDiastolic !== null && !repeatExtreme) {
        assessment = symptomsSelected()
          ? ['Emergency symptoms recorded', 'Stop routine workflow and follow the clinic emergency-response protocol.', 'danger']
          : ['Very high initial reading — repeat lower', 'Keep both readings documented and obtain immediate clinician review.', 'danger'];
      }
      setStatus(panel, ...assessment);
      const extreme = s !== null && d !== null && (s >= 180 || d >= 120);
      if (symptomPanel) symptomPanel.hidden = !anyExtreme;
      if (measurementConfirmed) measurementConfirmed.required = firstSystolic !== null || firstDiastolic !== null || repeatSystolic !== null || repeatDiastolic !== null;
      if (symptomReview) symptomReview.required = anyExtreme;
      if (extreme && repeatShell && repeatShell.hidden && !repeatSys?.value && !repeatDia?.value) {
        if (showRepeat) showRepeat.classList.add('attention');
      } else if (showRepeat) showRepeat.classList.remove('attention');
    };
    const refreshBmi = () => {
      if (!bmiOutput) return;
      const kg = numberValue(weight);
      const cm = numberValue(height);
      bmiOutput.textContent = kg !== null && cm !== null && cm > 0 ? (kg / ((cm / 100) ** 2)).toFixed(2) : '—';
    };

    [sys, dia, repeatSys, repeatDia].forEach(field => field?.addEventListener('input', refreshBp));
    form.querySelectorAll('[name="bp_symptoms[]"]').forEach(field => field.addEventListener('change', refreshBp));
    weight?.addEventListener('input', refreshBmi);
    height?.addEventListener('input', refreshBmi);

    showRepeat?.addEventListener('click', () => {
      if (repeatShell) repeatShell.hidden = false;
      showRepeat.hidden = true;
      repeatSys?.focus();
    });
    hideRepeat?.addEventListener('click', () => {
      if (repeatSys) repeatSys.value = '';
      if (repeatDia) repeatDia.value = '';
      const minutes = form.querySelector('[name="bp_repeat_after_minutes"]');
      if (minutes) minutes.value = '1';
      if (repeatShell) repeatShell.hidden = true;
      if (showRepeat) showRepeat.hidden = false;
      refreshBp();
    });

    form.querySelector('[data-copy-previous-vitals]')?.addEventListener('click', event => {
      const button = event.currentTarget;
      const mapping = {
        bpSystolic: 'bp_systolic',
        bpDiastolic: 'bp_diastolic',
        pulseRate: 'pulse_rate',
        temperatureC: 'temperature_c',
        respiratoryRate: 'respiratory_rate',
        oxygenSaturation: 'oxygen_saturation',
        weightKg: 'weight_kg',
        heightCm: 'height_cm',
      };
      Object.entries(mapping).forEach(([datasetKey, name]) => {
        const field = form.querySelector(`[name="${name}"]`);
        const value = button.dataset[datasetKey] || '';
        if (field && value !== '') field.value = value;
      });
      refreshBp();
      refreshBmi();
      sys?.focus();
    });

    form.addEventListener('submit', event => {
      const firstSys = numberValue(sys);
      const firstDia = numberValue(dia);
      const secondSys = numberValue(repeatSys);
      const secondDia = numberValue(repeatDia);
      let message = '';
      let target = null;
      if ((firstSys === null) !== (firstDia === null)) {
        message = 'Enter both systolic and diastolic values for the first reading.';
        target = firstSys === null ? sys : dia;
      } else if (firstSys !== null && firstSys <= firstDia) {
        message = 'Systolic pressure must be higher than diastolic pressure.';
        target = sys;
      } else if (secondSys !== null && firstSys === null) {
        message = 'Enter the first blood-pressure reading before adding a repeat reading.';
        target = sys;
      } else if ((secondSys === null) !== (secondDia === null)) {
        message = 'Enter both systolic and diastolic values for the repeat reading.';
        target = secondSys === null ? repeatSys : repeatDia;
      } else if (secondSys !== null && secondSys <= secondDia) {
        message = 'Repeat systolic pressure must be higher than repeat diastolic pressure.';
        target = repeatSys;
      } else if ((firstSys !== null || secondSys !== null) && measurementConfirmed && !measurementConfirmed.checked) {
        message = 'Confirm the blood-pressure measurement setup.';
        target = measurementConfirmed;
      } else {
        const anyVeryHigh = (firstSys !== null && firstDia !== null && (firstSys >= 180 || firstDia >= 120))
          || (secondSys !== null && secondDia !== null && (secondSys >= 180 || secondDia >= 120));
        if (anyVeryHigh && symptomReview && !symptomReview.checked) {
          message = 'Complete the concerning-symptom review for the very high reading.';
          target = symptomReview;
        }
      }
      if (!message) return;
      event.preventDefault();
      if (repeatShell && target && repeatShell.contains(target)) repeatShell.hidden = false;
      target?.focus();
      target?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      if (typeof target?.setCustomValidity === 'function') {
        target.setCustomValidity(message);
        target.reportValidity();
        window.setTimeout(() => target.setCustomValidity(''), 50);
      } else window.alert(message);
    });

    if (sys && dia) {
      sys.addEventListener('keydown', event => {
        if (event.key === 'Enter') { event.preventDefault(); dia.focus(); }
      });
      dia.addEventListener('keydown', event => {
        if (event.key === 'Enter') { event.preventDefault(); form.querySelector('[name="pulse_rate"]')?.focus(); }
      });
    }

    refreshBp();
    refreshBmi();
  };

  document.querySelectorAll('[data-vitals-form]').forEach(attachForm);
})();
