"use strict";

const dashboardStatus = document.getElementById("dashboard-status");
const officialGvlLocalVersion = document.getElementById(
  "official-gvl-local-version"
);
const officialGvlLastCheck = document.getElementById("official-gvl-last-check");
const officialGvlLastRealCheck = document.getElementById(
  "official-gvl-last-real-check"
);
const officialGvlNextAllowedCheck = document.getElementById(
  "official-gvl-next-allowed-check"
);
const officialGvlResult = document.getElementById("official-gvl-result");
const officialGvlVersionChange = document.getElementById(
  "official-gvl-version-change"
);

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

document.addEventListener("DOMContentLoaded", async () => {
  await renderEvidenceStatus();
  await renderOfficialGvlStatus();
});

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

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

    renderStoreCounts(status.storeCounts ?? {});
    renderStatusMessage("Evidence status loaded");
  } catch (error) {
    renderStatusMessage("Evidence status could not be loaded");
    console.warn("VendorGet-IV dashboard status failed", error);
  }
}

function renderStoreCounts(storeCounts) {
  for (const [storeName, cell] of Object.entries(storeCells)) {
    cell.textContent = String(storeCounts[storeName] ?? 0);
  }
}

async function renderOfficialGvlStatus() {
  try {
    const result = await browser.runtime.sendMessage({
      type: "get_latest_gvl_update_status"
    });

    if (!result?.success) {
      throw new Error(result?.error ?? "get_latest_gvl_update_status_failed");
    }

    const status = result.status ?? {};

    officialGvlLocalVersion.textContent = formatNullable(
      status.latestLocalVendorListVersion ?? status.currentVendorListVersion
    );
    officialGvlLastCheck.textContent = formatNullable(status.checkedAt);
    officialGvlLastRealCheck.textContent = formatNullable(
      status.lastAutoGvlCheckAt
    );
    officialGvlNextAllowedCheck.textContent = formatNullable(
      status.nextAllowedAutoCheckAt
    );
    officialGvlResult.textContent = formatGvlUpdateResult(status);
    officialGvlVersionChange.textContent = formatGvlVersionChange(status);
  } catch (error) {
    officialGvlLocalVersion.textContent = "-";
    officialGvlLastCheck.textContent = "-";
    officialGvlLastRealCheck.textContent = "-";
    officialGvlNextAllowedCheck.textContent = "-";
    officialGvlResult.textContent = "Auto-Check fehlgeschlagen";
    officialGvlVersionChange.textContent = "-";
    console.warn("VendorGet-IV official GVL status failed", error);
  }
}

function formatGvlUpdateResult(status) {
  const result = status?.result ?? null;

  if (result === "stored") {
    return "Neue offizielle Vendorliste gespeichert";
  }

  if (result === "no_change") {
    return "Keine neuere offizielle Vendorliste gefunden";
  }

  if (result === "already_known") {
    return "Offizielle Vendorliste war bereits lokal bekannt";
  }

  if (result === "error") {
    return "Auto-Check fehlgeschlagen";
  }

  if (result === "throttled") {
    return "Übersprungen wegen 24h-Throttling";
  }

  if (result === "started") {
    return "Auto-Check läuft";
  }

  if (result === "not_checked_since_background_start") {
    return "Noch kein Auto-Check seit Background-Start";
  }

  return formatNullable(status?.message ?? result);
}

function formatGvlVersionChange(status) {
  const previousVersion = formatNullable(status?.previousVendorListVersion);
  const currentVersion = formatNullable(status?.currentVendorListVersion);

  if (previousVersion === "-" && currentVersion === "-") {
    return "-";
  }

  return `${previousVersion} -> ${currentVersion}`;
}

function renderStatusMessage(message) {
  dashboardStatus.textContent = message;
}

function formatNullable(value) {
  if (value === null || value === undefined || value === "") {
    return "-";
  }

  return String(value);
}
