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

const flash = document.getElementById('flash');

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

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

function featureRow(name, on) {
  return `<li class="${on ? 'ok' : 'muted'}"><span class="pill ${on ? 'ok' : 'warn'}">${on ? 'an' : 'aus'}</span> ${escapeHtml(name)}</li>`;
}

function statusLabel(state) {
  if (state.isTrial) return `Testversion (${state.trialDaysRemaining ?? 0} Tage)`;
  if (state.isLicensed) return state.isExpired ? 'Abgelaufen' : 'Aktiv (SPEL)';
  if (state.isTrialExpired) return 'Testversion abgelaufen';
  return state.isExpired ? 'Lizenz abgelaufen' : 'Nicht lizenziert';
}

function render(state) {
  const trialCard = state.isTrial || state.isTrialExpired
    ? card('Testversion', `${state.trialDaysRemaining ?? 0} / ${state.trialDaysTotal || 30} Tage` +
        (state.trialExpiresUtc ? ` · bis ${new Date(state.trialExpiresUtc).toLocaleDateString()}` : ''))
    : card('Testversion', '—');

  document.getElementById('statusCards').innerHTML =
    card('Status', statusLabel(state)) +
    card('Geräte', state.unlimitedDevices ? `${state.usedDevices ?? 0} / ∞` : `${state.usedDevices ?? 0} / ${state.maxDevices || '—'}`) +
    card('SKU / Preis', `${state.productSku || 'SPEL-ENT-599'} · ${state.listPriceEur || '599'} €`) +
    trialCard +
    card('SPEL-Ablauf', state.isTrial ? '—' : (state.expiresUtc ? new Date(state.expiresUtc).toLocaleDateString() : 'Unbegrenzt'));

  document.getElementById('statusText').textContent = state.statusMessage || '';
  renderLicenseBanner(state);

  document.getElementById('features').innerHTML =
    featureRow('Remote-Datenbank (SQL Server / Oracle)', !!state.canUseSqlServer) +
    featureRow('Alert-Webhooks', !!state.canUseAlertWebhooks) +
    featureRow('Reporting / CSV-Export', !!state.canUseReporting) +
    featureRow('Remote-Aktionen', !!state.canUseRemoteActions) +
    featureRow('Mehrbenutzer / RBAC', !!state.canUseMultiUser) +
    featureRow('SQL-Admin (Schema, Abfragen, Backup)', !!state.canUseSqlAdmin);

  if (state.licenseKeyMasked)
    document.getElementById('licenseKey').placeholder = state.licenseKeyMasked;
}

async function refresh() {
  const res = await api('/api/license');
  if (!res.ok) throw new Error('Lizenzstatus nicht ladbar');
  render(await res.json());
}

document.getElementById('activateForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const licenseKey = document.getElementById('licenseKey').value.trim();
  const res = await api('/api/license', { method: 'PUT', body: JSON.stringify({ licenseKey }) });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    showFlash(data.error || 'Aktivierung fehlgeschlagen', false);
    if (data.license) render(data.license);
    return;
  }
  showFlash(data.message || 'Lizenz aktiviert', true);
  document.getElementById('licenseKey').value = '';
  render(data.license);
});

document.getElementById('btnClear').addEventListener('click', async () => {
  const ok = await confirmDialog({
    title: 'Lizenz entfernen',
    message: 'Enterprise-Lizenz wirklich entfernen?\nDanach gilt ggf. nur noch die Testversion (falls noch aktiv).',
    confirmLabel: 'Lizenz entfernen',
    danger: true
  });
  if (!ok) return;
  const res = await api('/api/license', { method: 'DELETE' });
  const data = await res.json().catch(() => ({}));
  showFlash('Lizenz entfernt.', true);
  render(data.license || {});
});

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?.role) applyRoleNav(me.role);
  await refresh();
}

init();
