// ============================================================
// bedside/age-weight.js
// BEDSIDE — AGE → WEIGHT (single source for all sub-sections).
// Top estimator wiring: #bedside-age, #bedside-formula,
// #bedside-weight, #btn-bedside-clear.
// ============================================================

export function init() {
  document.addEventListener('input', function(e) {
    if (e.target && e.target.id === 'bedside-age') recomputeFromAge();
    if (e.target && e.target.id === 'bedside-weight') {
      e.target.dataset.userTyped = '1';
    }
  });
  document.addEventListener('change', function(e) {
    if (e.target && e.target.id === 'bedside-formula') recomputeFromAge(true);
  });
  document.addEventListener('click', function(e) {
    if (e.target.closest && e.target.closest('#btn-bedside-clear')) {
      document.getElementById('bedside-age').value = '';
      var wtField = document.getElementById('bedside-weight');
      wtField.value = '';
      delete wtField.dataset.userTyped;
      var note = document.getElementById('bedside-estimate-note');
      if (note) note.innerHTML = '';
    }
  });

  // Recompute weight from age using the currently selected formula.
  // If forceFromFormula is true (formula dropdown changed), overwrite even user-typed weight.
  function recomputeFromAge(forceFromFormula) {
    var raw = document.getElementById('bedside-age').value;
    var note = document.getElementById('bedside-estimate-note');
    if (!raw || !raw.trim()) { if (note) note.innerHTML = ''; return; }
    var months = window._parseAgeMonths ? window._parseAgeMonths(raw) : null;
    if (months == null || isNaN(months) || months < 0) {
      if (note) note.innerHTML = '<span style="color:var(--red);">Could not parse age. Try "3y", "18 months", "15 days".</span>';
      return;
    }
    var formula = document.getElementById('bedside-formula').value;
    var est = window._PED_MATH.estimateWeightFromAgeMonths(months);
    var pickedWeight = formula === 'bestguess' ? est.all.bestGuess : est.all.apls;
    var pickedLabel = formula === 'bestguess' ? bestGuessBand(months) : aplsBand(months);

    var wtField = document.getElementById('bedside-weight');
    if (forceFromFormula || !wtField.dataset.userTyped) {
      wtField.value = pickedWeight;
      delete wtField.dataset.userTyped;  // treat as computed again
    }
    var ageTxt = months < 12
      ? (Math.round(months * 10) / 10) + ' months'
      : (Math.round(months / 12 * 10) / 10) + ' years';
    if (note) note.innerHTML = '<strong>' + pickedWeight + ' kg</strong> ' +
      '<span style="color:var(--g500);">(' + ageTxt + ', ' + pickedLabel + ')</span> · ' +
      'APLS: ' + est.all.apls + ' kg · Best Guess: ' + est.all.bestGuess + ' kg. <em>You can override the weight field.</em>';
  }

  function aplsBand(m) {
    if (m < 12) return 'APLS 0-12 mo';
    var y = m / 12;
    if (y <= 5) return 'APLS 1-5 yr';
    return 'APLS 6-12 yr';
  }
  function bestGuessBand(m) {
    if (m < 12) return 'Best Guess 1-11 mo';
    var y = m / 12;
    if (y <= 5) return 'Best Guess 1-4 yr';
    return 'Best Guess 5-14 yr';
  }

  // Top bedside weight is estimator-only. Sections have their own weight fields and
  // read them directly (no auto-propagation). Expose the reader on window for
  // safety (some older code paths may look it up).
  if (typeof window !== 'undefined') {
    window._getBedsideWeight = function() {
      var el = document.getElementById('bedside-weight');
      return el ? parseFloat(el.value) || null : null;
    };
  }
}
