let refreshTimer = null;
let refreshSeconds = 30;

function card(label, value) {
  return `<div class="card"><div class="label">${escapeHtml(label)}</div><div class="value">${escapeHtml(String(value))}</div></div>`;
}

function sevClass(device) {
  if (!device.online) return 'crit';
  if (device.overallSeverity === 2 || device.overallSeverity === 'Critical') return 'crit';
  if (device.overallSeverity === 1 || device.overallSeverity === 'Warning') return 'warn';
  return 'ok';
}

function sevLabel(device) {
  if (!device.online) return 'Offline';
  if (device.overallSeverity === 2 || device.overallSeverity === 'Critical') return 'Critical';
  if (device.overallSeverity === 1 || device.overallSeverity === 'Warning') return 'Warning';
  return 'Normal';
}

function render(overview, license) {
  if (license) renderLicenseBanner(license);

  document.getElementById('cards').innerHTML =
    card('PCs gesamt', overview.totalDevices) +
    card('Online', overview.onlineDevices) +
    card('Offline', overview.offlineDevices) +
    card('Kritisch', overview.criticalDevices) +
    card('Warnung', overview.warningDevices) +
    (license ? card('Lizenz', license.unlimitedDevices ? `${license.usedDevices ?? 0} / ∞` : `${license.usedDevices ?? 0}/${license.maxDevices || '—'}`) : '');

  const outages = overview.recentOutageAlerts || [];
  const outEl = document.getElementById('outages');
  if (!outages.length) {
    outEl.innerHTML = '';
  } else {
    outEl.innerHTML = '<div class="panel"><h3>Ausfallwarnungen</h3><ul class="alerts">' +
      outages.map(a => `<li class="crit"><strong>${escapeHtml(a.title)}</strong> — ${escapeHtml(a.message)}</li>`).join('') +
      '</ul></div>';
  }

  const rows = (overview.devices || []).map(d => {
    const reboot = d.rebootRequired ? ' <span class="pill warn">Reboot</span>' : '';
    const meta = [d.site, d.groupName].filter(Boolean).join(' · ');
    const sysInfo = [d.osCaption, d.primaryIp].filter(Boolean).join(' · ');
    return `<tr>
      <td><a href="/device.html?id=${encodeURIComponent(d.deviceId)}">${escapeHtml(d.displayName)}</a>
        <div class="muted">${escapeHtml(d.hostName || '')}${meta ? ' · ' + escapeHtml(meta) : ''}</div>
        ${sysInfo ? `<div class="muted">${escapeHtml(sysInfo)}</div>` : ''}</td>
      <td class="${sevClass(d)}">${sevLabel(d)}</td>
      <td>${fmt(d.cpuLoad, '%')}</td>
      <td>${fmt(d.memoryLoad, '%')}</td>
      <td>${fmt(d.cpuTempCelsius, '°C')}</td>
      <td>${fmt(d.worstDiskUsedPercent, '%')}</td>
      <td>${fmt(d.maxSsdWearPercent, '%')}</td>
      <td>${d.pendingWindowsUpdates ?? 0}${reboot}</td>
      <td>${d.activeAlerts ?? 0}</td>
      <td class="muted">${d.lastSeenUtc ? new Date(d.lastSeenUtc).toLocaleString() : '—'}</td>
    </tr>`;
  }).join('');

  document.getElementById('rows').innerHTML = rows || '<tr><td colspan="10" class="muted">Noch keine Agents registriert.</td></tr>';
  document.getElementById('subtitle').textContent =
    `Live-Status · Auto-Refresh ${refreshSeconds}s · ${new Date().toLocaleTimeString()}`;
}

async function refresh() {
  try {
    const res = await api('/api/fleet');
    if (!res.ok) throw new Error('Fleet API ' + res.status);
    const data = await res.json();
    const overview = data.overview || data;
    render(overview, data.license);
  } catch (e) {
    console.error(e);
    document.getElementById('rows').innerHTML =
      `<tr><td colspan="10" class="crit">Fehler: ${escapeHtml(e.message)}</td></tr>`;
  }

  await loadTrend();
}

async function loadTrend() {
  try {
    const res = await api('/api/fleet/trend?hours=24');
    if (!res.ok) return;
    const points = await res.json();
    const labels = points.map(p => new Date(p.utc).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }));

    SpCharts.drawLineChart(document.getElementById('trendOnlineChart'), [
      { label: 'Online', color: SpCharts.cssVar('--ok', '#3ecf8e'), values: points.map(p => p.online) },
      { label: 'Offline', color: SpCharts.cssVar('--crit', '#ef6b6b'), values: points.map(p => p.offline) }
    ], { labels, points: false });

    SpCharts.drawStackedArea(document.getElementById('trendSeverityChart'), [
      { label: 'Kritisch', color: SpCharts.cssVar('--crit', '#ef6b6b'), values: points.map(p => p.critical) },
      { label: 'Warnung', color: SpCharts.cssVar('--warn', '#e6a23c'), values: points.map(p => p.warning) }
    ], { labels });
  } catch (e) {
    console.error(e);
  }
}

function scheduleRefresh() {
  if (refreshTimer) clearInterval(refreshTimer);
  refreshTimer = setInterval(refresh, refreshSeconds * 1000);
}

function showManualFlash(message, ok) {
  const el = document.getElementById('manualFlash');
  if (!el) return;
  el.hidden = false;
  el.className = 'flash ' + (ok ? 'ok' : 'error');
  el.textContent = message;
}

function bindManualEnroll() {
  const form = document.getElementById('manualDeviceForm');
  if (!form) return;
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const body = {
      displayName: document.getElementById('manualDisplayName').value.trim(),
      hostName: document.getElementById('manualHostName').value.trim() || null,
      deviceId: document.getElementById('manualDeviceId').value.trim() || null,
      site: document.getElementById('manualSite').value.trim() || null,
      groupName: document.getElementById('manualGroup').value.trim() || null,
      tags: document.getElementById('manualTags').value.trim() || null
    };
    const res = await api('/api/devices/manual', { method: 'POST', body: JSON.stringify(body) });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      showManualFlash(data.error || 'Hinzufügen fehlgeschlagen', false);
      return;
    }
    showManualFlash((data.message || 'Gerät vorbereitet.') + ' ID: ' + data.deviceId, true);
    form.reset();
    await refresh();
  });
}

async function init() {
  await initLocale();
  const nav = document.querySelector('.nav');
  if (nav) {
    const refreshBtn = document.getElementById('btnRefresh');
    const logoutBtn = document.getElementById('btnLogout');
    nav.innerHTML = chromeNav('fleet');
    if (refreshBtn) nav.appendChild(refreshBtn);
    if (logoutBtn) /* logout via chromeNav */
  }
  setActiveNav('fleet');
  document.getElementById('btnLogout').addEventListener('click', logout);
  document.getElementById('btnRefresh').addEventListener('click', refresh);
  bindManualEnroll();

  try {
    const me = await loadMe();
    if (me?.organizationName)
      document.getElementById('orgName').textContent = me.organizationName;
    if (me?.license) renderLicenseBanner(me.license);
    if (me?.role) applyRoleNav(me.role);

    // Operator+ may prepare devices manually
    const role = me?.role || 'Viewer';
    const canEnroll = role === 'Operator' || role === 'Administrator';
    const panel = document.getElementById('manualEnrollPanel');
    if (panel) panel.hidden = !canEnroll;

    refreshSeconds = me?.uiRefreshSeconds || 30;
    if (me?.organizationName)
      document.getElementById('orgName').textContent = me.organizationName;
  } catch (_) { /* redirect handled in api() */ }

  await refresh();
  scheduleRefresh();
}

init();
