"use strict";

const requestMonitoringToggle = document.getElementById(
  "request-monitoring-toggle"
);
const requestMonitoringStatus = document.getElementById(
  "request-monitoring-status"
);
const consentCaptureToggle = document.getElementById("consent-capture-toggle");
const consentCaptureStatus = document.getElementById("consent-capture-status");
const maintenanceWarning = document.getElementById("maintenance-warning");
const evidenceLockedCount = document.getElementById("evidence-locked-count");
const evidenceDashboardButton = document.getElementById(
  "evidence-dashboard-button"
);
const evidenceRetentionStatus = document.getElementById(
  "evidence-retention-status"
);

const evidenceStoreCountCells = {
  consent_states: document.getElementById("evidence-consent-states-count"),
  consent_events: document.getElementById("evidence-consent-events-count"),
  observed_requests: document.getElementById("evidence-observed-requests-count"),
  gvl_snapshots: document.getElementById("evidence-gvl-snapshots-count"),
  gvl_snapshot_events: document.getElementById(
    "evidence-gvl-snapshot-events-count"
  )
};

document.addEventListener("DOMContentLoaded", async () => {
  await renderSettings();
  await renderEvidenceMaintenanceStatus();
  await renderEvidenceRetentionStatus();

  consentCaptureToggle.addEventListener("change", async () => {
    consentCaptureToggle.disabled = true;

    await setVendorGetSetting(
      "consentCaptureEnabled",
      consentCaptureToggle.checked
    );
    await renderSettings();

    consentCaptureToggle.disabled = false;
  });

  requestMonitoringToggle.addEventListener("change", async () => {
    requestMonitoringToggle.disabled = true;

    await setVendorGetSetting(
      "requestMonitoringEnabled",
      requestMonitoringToggle.checked
    );
    await renderSettings();

    requestMonitoringToggle.disabled = false;
  });

  evidenceDashboardButton.addEventListener("click", async () => {
    await browser.tabs.create({
      url: browser.runtime.getURL("src/dashboard/dashboard.html")
    });
  });
});

async function renderSettings() {
  const settings = await getVendorGetSettings();
  const consentCaptureEnabled = settings.consentCaptureEnabled;
  const requestMonitoringEnabled = settings.requestMonitoringEnabled;

  consentCaptureToggle.checked = consentCaptureEnabled;
  consentCaptureStatus.textContent = consentCaptureEnabled ? "aktiv" : "aus";

  requestMonitoringToggle.checked = requestMonitoringEnabled;
  requestMonitoringStatus.textContent = requestMonitoringEnabled
    ? "aktiv"
    : "aus";
}

async function renderEvidenceRetentionStatus() {
  try {
    const status = await getEvidenceRetentionStatus();

    renderEvidenceStoreCounts(status.storeCounts ?? {});
    evidenceLockedCount.textContent = formatStatusValue(status.lockedCount);
    renderEvidenceRetentionMessage("Bereit");
  } catch (error) {
    renderEvidenceStoreCounts({});
    evidenceLockedCount.textContent = "-";
    renderEvidenceRetentionMessage("Status konnte nicht geladen werden");
    console.warn("VendorGet-IV evidence retention status failed", error);
  }
}

async function renderEvidenceMaintenanceStatus() {
  try {
    const status = await browser.runtime.sendMessage({
      type: "get_evidence_maintenance_status"
    });

    if (!status?.success) {
      throw new Error(status?.error ?? "get_evidence_maintenance_status_failed");
    }

    maintenanceWarning.hidden = !status.evidenceWriteSuspended;
  } catch (error) {
    maintenanceWarning.hidden = true;
    console.warn("VendorGet-IV maintenance status failed", error);
  }
}

async function getEvidenceRetentionStatus() {
  const status = await browser.runtime.sendMessage({
    type: "get_evidence_retention_status"
  });

  if (!status?.success) {
    throw new Error(status?.error ?? "get_evidence_retention_status_failed");
  }

  return status;
}

function renderEvidenceStoreCounts(storeCounts) {
  for (const [storeName, cell] of Object.entries(evidenceStoreCountCells)) {
    cell.textContent = formatStatusValue(storeCounts[storeName]);
  }
}

function formatStatusValue(value) {
  return Number.isFinite(value) ? String(value) : "-";
}

function renderEvidenceRetentionMessage(message) {
  evidenceRetentionStatus.textContent = message;
}
