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

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

document.getElementById('btnCsv').addEventListener('click', async () => {
  const res = await api('/api/reports/fleet.csv');
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    showFlash(data.error || 'Export fehlgeschlagen', false);
    return;
  }
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'sensorpulse-fleet.csv';
  a.click();
  URL.revokeObjectURL(url);
  showFlash('CSV heruntergeladen.', true);
});

async function loadWeeklySettings() {
  const res = await api('/api/reports/weekly/settings');
  if (!res.ok) return; // e.g. Viewer/Operator without AdminOnly rights
  const s = await res.json();
  document.getElementById('wrEnabled').checked = !!s.enabled;
  document.getElementById('wrDay').value = String(s.dayOfWeek ?? 1);
  document.getElementById('wrHour').value = s.hourUtc ?? 6;
  document.getElementById('wrRecipients').value = s.recipients || '';
  document.getElementById('wrLastSent').textContent = s.lastSentUtc
    ? 'Zuletzt gesendet: ' + new Date(s.lastSentUtc).toLocaleString()
    : 'Noch nicht gesendet.';
}

document.getElementById('btnSaveWeekly').addEventListener('click', async () => {
  const body = {
    enabled: document.getElementById('wrEnabled').checked,
    dayOfWeek: Number(document.getElementById('wrDay').value),
    hourUtc: Number(document.getElementById('wrHour').value),
    recipients: document.getElementById('wrRecipients').value.trim()
  };
  const res = await api('/api/reports/weekly/settings', { method: 'PUT', body: JSON.stringify(body) });
  const data = await res.json().catch(() => ({}));
  showFlash(res.ok ? 'Zeitplan gespeichert.' : (data.error || 'Speichern fehlgeschlagen'), res.ok);
  if (res.ok) await loadWeeklySettings();
});

document.getElementById('btnSendNow').addEventListener('click', async () => {
  const res = await api('/api/reports/weekly/send-now', { method: 'POST' });
  const data = await res.json().catch(() => ({}));
  showFlash(res.ok ? (data.message || 'Wochenreport gesendet.') : (data.error || 'Versand fehlgeschlagen'), res.ok);
  if (res.ok) await loadWeeklySettings();
});

async function init() {
  await initLocale();
  document.getElementById('btnLogout').addEventListener('click', logout);
  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);
  if (me?.role && me.role !== 'Administrator') {
    const panel = document.getElementById('weeklyPanel');
    if (panel) panel.style.display = 'none';
  } else {
    await loadWeeklySettings();
  }
}

init();
