// ============================================================
// bedside/sub-nav.js
// EMERGENCIES SUB-NAV — data-em pill switching.
// Persists the active pill so reloads / sign-out-sign-in land on the
// same sub-section the user was last looking at.
// ============================================================

var SECTIONS = ['neonatal','airway','cardiac','respiratory','ventilation','seizure','sepsis','anaphylaxis','sedation','agitation','antiemetics','antimicrobials','burns','toxicology','trauma','sutures'];

function activate(emKey) {
  var pill = document.querySelector('[data-em="' + emKey + '"]');
  if (!pill) return false;
  document.querySelectorAll('[data-em]').forEach(function(p) { p.classList.remove('active'); });
  pill.classList.add('active');
  SECTIONS.forEach(function(s) {
    var el = document.getElementById('em-' + s);
    if (el) el.style.display = emKey === s ? '' : 'none';
  });
  return true;
}

export function init() {
  document.addEventListener('click', function(e) {
    var pill = e.target.closest('[data-em]');
    if (!pill) return;
    activate(pill.dataset.em);
    if (window.UIState) window.UIState.set('bedside.pill', pill.dataset.em);
  });
  // Restore on load. The bedside component is lazily injected the first time
  // the tab is activated, so try both an immediate pass (harness where the
  // DOM is synchronously ready) and a tabChanged listener (live app where
  // the component HTML arrives async). Either path reaches the same
  // activate(saved) call — whichever fires first wins; the other is a noop.
  function applySaved() {
    if (!window.UIState) return;
    var saved = window.UIState.get('bedside.pill');
    if (saved) activate(saved);
  }
  applySaved();
  document.addEventListener('tabChanged', function(e) {
    if (e.detail && e.detail.tab === 'bedside') applySaved();
  });
}
