document.getElementById('mainNav').innerHTML = chromeNav('alerts');

const flash = document.getElementById('flash');
function showFlash(message, ok) {
  flash.hidden = false;
  flash.className = 'flash ' + (ok ? 'ok' : 'error');
  flash.textContent = message;
}

async function loadSettings() {
  const res = await api('/api/alerts/settings');
  const data = await res.json();
  if (data.license) renderLicenseBanner(data.license);
  const s = data.settings || data;
  document.getElementById('enabled').checked = !!s.enabled;
  document.getElementById('webhookUrl').value = s.webhookUrl || '';
  document.getElementById('emailTo').value = s.emailTo || '';
  document.getElementById('notifyOnOutage').checked = s.notifyOnOutage !== false;
  document.getElementById('notifyOnCritical').checked = s.notifyOnCritical !== false;
}

async function loadThresholds() {
  const res = await api('/api/alerts/thresholds');
  if (!res.ok) return;
  const s = await res.json();
  document.getElementById('thEnabled').checked = !!s.enabled;
  document.getElementById('thNotify').checked = s.notify !== false;
  document.getElementById('thCpu').value = s.cpuPercent ?? 90;
  document.getElementById('thTemp').value = s.tempCelsius ?? 85;
  document.getElementById('thDisk').value = s.diskPercent ?? 90;
}

document.getElementById('thresholdForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const body = {
    enabled: document.getElementById('thEnabled').checked,
    notify: document.getElementById('thNotify').checked,
    cpuPercent: Number(document.getElementById('thCpu').value) || 90,
    tempCelsius: Number(document.getElementById('thTemp').value) || 85,
    diskPercent: Number(document.getElementById('thDisk').value) || 90
  };
  const res = await api('/api/alerts/thresholds', { method: 'PUT', body: JSON.stringify(body) });
  const data = await res.json().catch(() => ({}));
  showFlash(res.ok ? 'Schwellwert-Einstellungen gespeichert.' : (data.error || 'Fehler'), res.ok);
});

let timelineDays = 7;

async function loadTimeline() {
  const list = document.getElementById('timelineList');
  const res = await api('/api/alerts/timeline?days=' + timelineDays);
  if (!res.ok) {
    list.innerHTML = '<li class="muted">Timeline nicht verfügbar</li>';
    return;
  }
  const events = await res.json();
  if (!events.length) {
    list.innerHTML = '<li class="muted">Keine Ereignisse im gewählten Zeitraum</li>';
    return;
  }
  list.innerHTML = events.map(e => {
    const open = !e.resolvedUtc;
    const range = e.resolvedUtc
      ? `${new Date(e.raisedUtc).toLocaleString()} → ${new Date(e.resolvedUtc).toLocaleString()}`
      : `seit ${new Date(e.raisedUtc).toLocaleString()} · offen`;
    return `<li class="${open ? 'open' : ''}">
      <strong>${escapeHtml(e.kind)} · ${escapeHtml(e.displayName)}</strong>
      <div class="muted">${escapeHtml(e.message)}</div>
      <div class="muted">${range}</div>
    </li>`;
  }).join('');
}

document.querySelectorAll('.btn-range').forEach(btn => {
  btn.addEventListener('click', () => {
    timelineDays = Number(btn.getAttribute('data-days')) || 7;
    document.querySelectorAll('.btn-range').forEach(b => b.classList.toggle('active', b === btn));
    loadTimeline();
  });
});

async function loadAlerts() {
  const res = await api('/api/alerts');
  const list = await res.json();
  const el = document.getElementById('alertList');
  if (!list.length) {
    el.innerHTML = '<li class="muted">Keine Alerts</li>';
    return;
  }
  el.innerHTML = list.map(a =>
    `<li class="crit"><strong>${escapeHtml(a.title)}</strong><div class="muted">${escapeHtml(a.message)} · ${a.raisedUtc ? new Date(a.raisedUtc).toLocaleString() : ''}</div></li>`
  ).join('');
}

document.getElementById('alertForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const body = {
    enabled: document.getElementById('enabled').checked,
    webhookUrl: document.getElementById('webhookUrl').value.trim() || null,
    emailTo: document.getElementById('emailTo').value.trim() || null,
    notifyOnOutage: document.getElementById('notifyOnOutage').checked,
    notifyOnCritical: document.getElementById('notifyOnCritical').checked
  };
  const res = await api('/api/alerts/settings', { method: 'PUT', body: JSON.stringify(body) });
  const data = await res.json().catch(() => ({}));
  showFlash(res.ok ? 'Alert-Einstellungen gespeichert.' : (data.error || 'Fehler'), res.ok);
});

async function init() {
  await initLocale();
  document.getElementById('btnLogout').addEventListener('click', logout);
  document.getElementById('btnRefresh').addEventListener('click', loadAlerts);
  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);
  await loadSettings();
  await loadAlerts();
  await loadThresholds();
  await loadTimeline();
}

init();
