'use strict';

// ── Hash-based URL routing ────────────────────────────────────────────
function initRouter() {
  var hash = location.hash.replace('#', '') || 'home';
  // Map common aliases
  if (hash === 'threats') hash = 'investigate';
  showView(hash);
}
window.addEventListener('hashchange', function() {
  var hash = location.hash.replace('#', '') || 'home';
  if (hash === 'threats') hash = 'investigate';
  showView(hash);
});

// ── Mobile panel toggle ────────────────────────────────────────────────
let leftPanelOpen = true;
function toggleLeftPanel() {
  const panel = document.querySelector('.left-panel');
  const icon  = document.getElementById('panelToggleIcon');
  leftPanelOpen = !leftPanelOpen;
  panel.classList.toggle('collapsed', !leftPanelOpen);
  if (icon) icon.textContent = leftPanelOpen ? '▲' : '▼';
}

// ── D10 - View switcher ──────────────────────────────────────────────────
// 2026-05-15: the standalone `responses` tab was removed. Per-attacker
// enforcement detail now renders on the journey panel (Enforcement
// block); the cross-attacker audit view is a modal opened from the
// Cases sidebar; lifetime stats and orphan diagnostics moved to the
// Health tab. The `/api/responses` endpoint stays (consumed by the
// modal, Health tab, and Home strip).
// 2026-05-16 PR-F: Honeypot route dropped from the More menu — per-IP
// honeypot session detail (creds + commands + IOCs) lives in the
// shared Attacker Dossier modal (PR-A).
// 2026-05-16 PR-G: `monthly` dropped from the More menu — Briefings
// carries the Day/Month period switcher.
const _secondaryTabs = ['sensors','report','compliance','graph'];
const _secondaryLabels = { sensors:'Sensors', report:'Report', compliance:'Compliance', graph:'Graph' };

function toggleMoreMenu() {
  const m = document.getElementById('moreMenu');
  if (m) m.style.display = m.style.display === 'none' ? '' : 'none';
}

function showView(name) {
  // 2026-05-16 PR-F: Honeypot route dropped — per-IP honeypot intel
  // lives in the shared Attacker Dossier modal (PR-A).
  // 2026-05-16 PR-G: `monthly` route dropped — Briefings carries the
  // Day/Month period switcher; the month threat report renders inside
  // the same `viewReport` mount via `loadMonthly`.
  const views = { home: 'viewHome', sensors: 'viewSensors', investigate: 'viewInvestigate', report: 'viewReport', status: 'viewStatus', compliance: 'viewCompliance', intel: 'viewIntel', fleet: 'viewFleet', graph: 'viewGraph' };
  const btns  = { home: 'navHome', sensors: 'navSensors', investigate: 'navInvestigate', report: 'navReport', status: 'navStatus', compliance: 'navCompliance', intel: 'navIntel', fleet: 'navFleet', graph: 'navGraph' };
  // Update URL hash (use friendly name for threats)
  var hashName = name === 'investigate' ? 'threats' : name;
  if (location.hash !== '#' + hashName) {
    history.replaceState(null, '', '#' + hashName);
  }
  Object.keys(views).forEach(k => {
    const el = document.getElementById(views[k]);
    const btn = document.getElementById(btns[k]);
    if (el) el.style.display = k === name ? 'flex' : 'none';
    if (btn) btn.classList.toggle('active', k === name);
  });
  const toggleBtn = document.getElementById('panelToggleBtn');
  if (toggleBtn) toggleBtn.classList.toggle('hidden', name !== 'investigate');
  // More dropdown: update label + highlight active item
  const moreLabel = document.getElementById('moreLabel');
  const navMore = document.getElementById('navMore');
  if (_secondaryTabs.includes(name)) {
    if (moreLabel) moreLabel.textContent = _secondaryLabels[name] || 'More';
    if (navMore) navMore.classList.add('active');
  } else {
    if (moreLabel) moreLabel.textContent = 'More';
    if (navMore) navMore.classList.remove('active');
  }
  // Close dropdown on any tab switch
  const moreMenu = document.getElementById('moreMenu');
  if (moreMenu) moreMenu.style.display = 'none';
  // Mark active item inside dropdown
  document.querySelectorAll('.nav-more-item').forEach(item => {
    item.classList.toggle('active', item.id === btns[name]);
  });

  // Clear outcome filter when leaving investigate
  if (name !== 'investigate') state.filterOutcome = null;

  // 2026-05-02 audit fix (P2): the persistent header pill drifted to
  // PROTECTED on tabs other than Home/Threats because only those two
  // loaders called syncModeBadgeFromHealth. Re-sync from the cached
  // overview on every view switch so OPERATIONAL DEBT / CATCHING UP /
  // AI NOT RESPONDING paint the same value across the whole nav.
  if (typeof syncModeBadgeFromHealth === 'function') {
    var cachedCfg = (typeof actionCfg !== 'undefined') ? actionCfg : null;
    if (window._lastOverview) {
      syncModeBadgeFromHealth(window._lastOverview, cachedCfg);
    } else {
      // First view-switch before Home/Threats has populated the cache:
      // fetch overview once so the badge does not paint a stale
      // PROTECTED label from actionCfg alone. Result is cached for
      // subsequent switches.
      loadJson('/api/overview').then(function(ov) {
        window._lastOverview = ov;
        syncModeBadgeFromHealth(ov, cachedCfg);
      }).catch(function() { /* swallow — not critical for navigation */ });
    }
  }

  if (name === 'home') loadHome();
  // 2026-05-15: the standalone Sensors view + its `loadSensors`
  // entrypoint were deleted. The per-collector breakdown + Event
  // Timeline render on Home itself via `renderHomeSensorsPanel`, so
  // the dispatcher has no `sensors` arm anymore.
  // 2026-05-16 PR-G: `report` view is now period-aware (Day/Month
  // switcher). `loadReportForActivePeriod()` dispatches to the
  // matching loader (loadReport for Day, loadMonthly for Month).
  if (name === 'report') loadReportForActivePeriod();
  if (name === 'status') loadStatus();
  // 2026-05-16 PR-F: `honeypot` route deleted. Per-IP honeypot detail
  // is on the Attacker Dossier modal (PR-A).
  if (name === 'compliance') loadCompliance();
  if (name === 'intel') loadIntel();
  // 2026-05-16 PR-G: `monthly` route deleted. The month threat report
  // is now a sub-period of the Briefings view.
  if (name === 'fleet') loadFleet();
  // Graph tab was removed and stats moved to Health; the old loadGraph()
  // module is no longer bundled so we stop dispatching here too.
}

// Click-outside handler for More dropdown
document.addEventListener('click', function(e) {
  var wrap = document.querySelector('.nav-more-wrap');
  if (wrap && !wrap.contains(e.target)) {
    var m = document.getElementById('moreMenu');
    if (m) m.style.display = 'none';
  }
});
