const stateLicense = document.getElementById("state-license");
const stateAuthority = document.getElementById("state-authority");
const stateContext = document.getElementById("state-context");
const stateRegistry = document.getElementById("state-registry");
const stateNetwork = document.getElementById("state-network");
const nextActionCta = document.getElementById("next-action-cta");
const modeChip = document.getElementById("license-mode");
const modeChipValue = document.getElementById("license-mode-value");
const contextPin = document.getElementById("context-pin");
const contextPinValue = document.getElementById("context-pin-value");
const contextTitle = document.getElementById("context-title");
const contextSubtitle = document.getElementById("context-subtitle");
const contextDisabled = document.getElementById("context-disabled");
const contextLocked = document.getElementById("context-locked");
const contextLockedNote = document.getElementById("context-locked-note");
const contextResetButton = document.getElementById("context-reset");
const contextForm = document.getElementById("context-form");
const contextEnvironment = document.getElementById("context-environment");
const contextRegulatoryScope = document.getElementById("context-regulatory-scope");
const contextBusinessCriticality = document.getElementById("context-business-criticality");
const contextStatus = document.getElementById("context-status");
const uploadForm = document.getElementById("upload-form");
const uploadFile = document.getElementById("upload-file");
const uploadEncoding = document.getElementById("upload-encoding");
const uploadFormat = document.getElementById("upload-format");
const uploadRun = document.getElementById("upload-run");
const uploadStatus = document.getElementById("upload-status");
const uploadProgressList = document.getElementById("upload-progress-list");
const bundleList = document.getElementById("bundle-list");
const bundleIdEl = document.getElementById("bundle-id");
const bundleTimestampEl = document.getElementById("bundle-timestamp");
const bundleContextEl = document.getElementById("bundle-context");
const bundleRegistryEl = document.getElementById("bundle-registry");
const bundleDeterminismEl = document.getElementById("bundle-determinism");
const coverageMetricsEl = document.getElementById("coverage-metrics");
const tierMetricsEl = document.getElementById("tier-metrics");
const bundleHashRootEl = document.getElementById("bundle-hash-root");
const bundleHashFindingsEl = document.getElementById("bundle-hash-findings");
const bundleHashDiscardsEl = document.getElementById("bundle-hash-discards");
const reportLinksEl = document.getElementById("report-links");
const decisionDisabled = document.getElementById("decision-disabled");
const decisionDisabledTitle = document.getElementById("decision-disabled-title");
const decisionDisabledSubtitle = document.getElementById("decision-disabled-subtitle");
const decisionDisabledNote = document.getElementById("decision-disabled-note");
const decisionPanel = document.getElementById("decision-panel");
const decisionValueEl = document.getElementById("decision-value");
const decisionTimeEl = document.getElementById("decision-time");
const decisionContextStatusEl = document.getElementById("decision-context-status");
const decisionContextEnvironmentEl = document.getElementById("decision-context-environment");
const decisionContextRegulatoryEl = document.getElementById("decision-context-regulatory");
const decisionContextCriticalityEl = document.getElementById("decision-context-criticality");
const decisionBoundaryPanel = document.getElementById("decision-boundary-panel");
const decisionBoundaryStatusEl = document.getElementById("decision-boundary-status");
const decisionBoundaryTier2El = document.getElementById("decision-boundary-tier2");
const decisionBoundaryNotProvableEl = document.getElementById("decision-boundary-notprovable");
const decisionBoundaryRulesEl = document.getElementById("decision-boundary-rules");
const decisionBoundaryImpactEl = document.getElementById("decision-boundary-impact");
const decisionBoundaryInterpretationEl = document.getElementById("decision-boundary-interpretation");
const evidenceModeBanner = document.getElementById("evidence-mode-banner");
const licenseErrorBanner = document.getElementById("license-error-banner");
const footerEvidenceEl = document.getElementById("footer-evidence");
const footerGovernanceEl = document.getElementById("footer-governance");
const artifactSummaryEl = document.getElementById("artifact-summary");
const artifactNoteEl = document.getElementById("artifact-note");
const findingsDownloadForm = document.getElementById("findings-download-form");
const findingsDownloadFormat = document.getElementById("findings-download-format");
const findingsDownloadButton = document.getElementById("findings-download-button");
const findingsCountEl = document.getElementById("findings-count");
const findingsNoteEl = document.getElementById("findings-note");
const discardsListEl = document.getElementById("discards-list");
const discardsCountEl = document.getElementById("discards-count");
const discardsNoteEl = document.getElementById("discards-note");
const licenseValidityEl = document.getElementById("license-validity");
const licenseExpiryEl = document.getElementById("license-expiry");
const licenseAuthorityEl = document.getElementById("license-authority");
const licenseVerificationEl = document.getElementById("license-verification");

const STORAGE_KEY = "legacy_lens_context";

const state = {
  license: null,
  registry: null,
  context: null,
  bundles: [],
  summaries: new Map(),
  currentBundleId: null,
  currentBundleContext: null,
  currentAuthorityNotice: null,
};

let showAllBundles = false;

function licenseModeValue() {
  if (!isLicenseValid()) {
    return "UNLICENSED";
  }
  const mode = String(state.license.mode || "").toUpperCase();
  if (mode === "EVIDENCE" || mode === "EVIDENCE_ONLY") {
    return "EVIDENCE";
  }
  if (mode === "AUTHORITY") {
    return "AUTHORITY";
  }
  return "AUTHORITY";
}

function isEvidenceMode() {
  return licenseModeValue() === "EVIDENCE";
}

function isLicenseValid() {
  return !!(state.license && state.license.valid === true);
}

function permissionFlag(key, fallback) {
  if (state.license?.permissions && typeof state.license.permissions[key] === "boolean") {
    return state.license.permissions[key];
  }
  return fallback;
}

function canDeclareContext() {
  if (!isLicenseValid()) {
    return false;
  }
  return permissionFlag("declare_context", !isEvidenceMode());
}

function canIssueDecisions() {
  if (!isLicenseValid()) {
    return false;
  }
  return permissionFlag("issue_decisions", !isEvidenceMode());
}

function canViewBoardReports() {
  if (!isLicenseValid()) {
    return false;
  }
  return permissionFlag("board_reports", canIssueDecisions());
}

function canViewExecutiveReports() {
  if (!isLicenseValid()) {
    return false;
  }
  return permissionFlag("exec_reports", canIssueDecisions());
}

const DecisionState = Object.freeze({
  EvidenceOnly: "EVIDENCE",
  ContextUndeclared: "CONTEXT_UNDECLARED",
  ContextDeclared: "CONTEXT_DECLARED",
  BundleNoContext: "BUNDLE_NO_CONTEXT",
  DecisionIssued: "DECISION_ISSUED",
});

function getDecisionState() {
  if (isEvidenceMode()) {
    return DecisionState.EvidenceOnly;
  }
  if (!contextDeclared(state.context)) {
    return DecisionState.ContextUndeclared;
  }
  if (!state.currentBundleId) {
    return DecisionState.ContextDeclared;
  }
  if (!contextDeclared(state.currentBundleContext)) {
    return DecisionState.BundleNoContext;
  }
  return DecisionState.DecisionIssued;
}

function fetchJson(path) {
  return fetch(path, { cache: "no-store" })
    .then((res) => (res.ok ? res.json() : null))
    .catch(() => null);
}

function normalizeLicenseStatus(data) {
  if (!data || typeof data !== "object") {
    return null;
  }
  const valid = data.valid === true || data.valid === "true";
  const normalized = { ...data, valid };
  if (valid) {
    delete normalized.error;
    delete normalized.reason;
  }
  return normalized;
}

function formatEpoch(epoch) {
  if (!epoch) {
    return "--";
  }
  const date = new Date(Number(epoch) * 1000);
  if (Number.isNaN(date.getTime())) {
    return "--";
  }
  return date.toISOString().slice(0, 10);
}

function formatTimestamp({ generated_at, created_at_epoch } = {}) {
  if (created_at_epoch) {
    const date = new Date(Number(created_at_epoch) * 1000);
    if (!Number.isNaN(date.getTime())) {
      return date.toISOString();
    }
  }
  if (generated_at) {
    return generated_at;
  }
  return "--";
}

function normalizeValue(value) {
  if (value === null || value === undefined) {
    return "--";
  }
  const text = String(value).trim();
  return text ? text : "--";
}

function normalizeDecision(value) {
  if (!value) {
    return "--";
  }
  const raw = String(value).trim();
  const upper = raw.toUpperCase();
  if (upper.includes("NO-GO") || upper.includes("NO GO")) {
    return "NO-GO";
  }
  if (upper.includes("REFUSE") || upper.includes("REFUSAL")) {
    return "REFUSE";
  }
  if (upper.includes("BLOCK") || upper.includes("CANNOT")) {
    return "NO-GO";
  }
  if (upper === "PASS" || upper.includes("GO")) {
    return "GO";
  }
  return "NO-GO";
}

function formatEvidenceTier(tier) {
  const key = String(tier || "").toUpperCase();
  const map = {
    TIER_0_SOURCE_PROVEN: { label: "Tier 0", className: "tier-0" },
    TIER_1_ARTIFACT_PROVEN: { label: "Tier 1", className: "tier-1" },
    TIER_2_BOUNDARY_EVIDENCE: { label: "Tier 2", className: "tier-2" },
    NOT_PROVABLE: { label: "Not Provable", className: "tier-x" },
  };
  return map[key] || { label: normalizeValue(tier), className: "" };
}

function tierCount(tiers, key) {
  if (!tiers || !tiers.counts) {
    return 0;
  }
  const value = tiers.counts[key];
  return typeof value === "number" ? value : Number(value || 0);
}

function contextDeclared(context) {
  if (!context) {
    return false;
  }
  return (
    !!context.environment &&
    !!context.regulatory_scope &&
    !!context.business_criticality
  );
}

function formatContext(context) {
  if (!contextDeclared(context)) {
    return "Not Declared";
  }
  return `${formatContextValue(context.environment)} · ${formatContextValue(context.regulatory_scope)} · ${formatContextValue(context.business_criticality)}`;
}

function formatContextValue(value) {
  const raw = String(value || "").trim();
  if (!raw) {
    return "--";
  }
  const lower = raw.toLowerCase();
  switch (lower) {
    case "production":
      return "Production";
    case "development":
      return "Development";
    case "sample":
      return "Sample";
    case "regulated":
      return "Regulated";
    case "internal":
      return "Internal";
    case "none":
      return "None";
    case "high":
      return "High";
    case "medium":
      return "Medium";
    case "low":
      return "Low";
    default:
      return raw;
  }
}

function isStrictContext(context) {
  if (!contextDeclared(context)) {
    return false;
  }
  const env = String(context.environment || "").toLowerCase();
  const scope = String(context.regulatory_scope || "").toLowerCase();
  const criticality = String(context.business_criticality || "").toLowerCase();
  return env === "production" && scope === "regulated" && criticality === "high";
}

function loadContext() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) {
      return null;
    }
    const parsed = JSON.parse(raw);
    return parsed && typeof parsed === "object" ? parsed : null;
  } catch (err) {
    return null;
  }
}

function saveContext(context) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(context));
}

function setContextFields(context) {
  if (!contextEnvironment || !contextRegulatoryScope || !contextBusinessCriticality) {
    return;
  }
  if (contextDeclared(context)) {
    contextEnvironment.value = context.environment;
    contextRegulatoryScope.value = context.regulatory_scope;
    contextBusinessCriticality.value = context.business_criticality;
    contextEnvironment.disabled = true;
    contextRegulatoryScope.disabled = true;
    contextBusinessCriticality.disabled = true;
    if (contextForm) {
      const saveButton = contextForm.querySelector("#context-save");
      if (saveButton) {
        saveButton.disabled = true;
      }
    }
  }
}

function resetContextFields() {
  if (!contextEnvironment || !contextRegulatoryScope || !contextBusinessCriticality) {
    return;
  }
  contextEnvironment.value = "";
  contextRegulatoryScope.value = "";
  contextBusinessCriticality.value = "";
  contextEnvironment.disabled = false;
  contextRegulatoryScope.disabled = false;
  contextBusinessCriticality.disabled = false;
  if (contextForm) {
    const saveButton = contextForm.querySelector("#context-save");
    if (saveButton) {
      saveButton.disabled = false;
    }
  }
}

function updateContextUi() {
  const declared = contextDeclared(state.context);
  const authority = canDeclareContext();
  if (contextTitle) {
    if (!authority) {
      contextTitle.textContent = "Governance Context - Authority Required";
    } else {
      contextTitle.textContent = declared
        ? "Governance Context - Pinned"
        : "Declare Governance Context";
    }
  }
  if (contextSubtitle) {
    if (!authority) {
      contextSubtitle.textContent = "Evidence Mode does not allow context declaration.";
    } else {
      contextSubtitle.textContent = declared
        ? "Context is recorded with evidence and cannot be modified."
        : "Context enables decisions and is recorded with evidence.";
    }
  }
  if (contextForm) {
    contextForm.hidden = declared || !authority;
  }
  if (contextDisabled) {
    contextDisabled.hidden = authority;
  }
  if (contextLocked) {
    contextLocked.hidden = !declared || !authority;
  }
  if (contextLockedNote) {
    contextLockedNote.textContent =
      declared && authority
        ? "This context is recorded as part of the evidence bundle and cannot be modified. To change it, create a new analysis."
        : "";
  }
}

function updateContextPin() {
  if (!contextPin || !contextPinValue) {
    return;
  }
  if (canDeclareContext() && contextDeclared(state.context)) {
    contextPin.hidden = false;
    contextPinValue.textContent = formatContext(state.context);
  } else {
    contextPin.hidden = true;
    contextPinValue.textContent = "Not Declared";
  }
}

function updateSystemState() {
  const licenseValid = isLicenseValid();
  if (stateLicense) {
    if (licenseValid) {
      const expires = formatEpoch(state.license.expires_at_epoch);
      stateLicense.textContent = `Valid (expires ${expires})`;
    } else if (state.license?.reason === "unlicensed") {
      stateLicense.textContent = "Missing";
    } else if (state.license) {
      stateLicense.textContent = "Invalid";
    } else {
      stateLicense.textContent = "--";
    }
  }
  if (stateContext) {
    stateContext.textContent = canDeclareContext()
      ? formatContext(state.context)
      : "Authority Required";
  }
  if (stateAuthority) {
    const enabled = canIssueDecisions();
    stateAuthority.textContent = enabled ? "Enabled" : "Disabled";
  }
  if (stateRegistry) {
    const version = state.registry?.registry_version || "--";
    stateRegistry.textContent = `Locked (v${version})`;
  }
  if (stateNetwork) {
    stateNetwork.textContent = "Offline";
  }
}

function updateModeChip() {
  if (!modeChip || !modeChipValue) {
    return;
  }
  modeChip.classList.remove("authority", "evidence");
  if (!isLicenseValid()) {
    modeChipValue.textContent = "Unlicensed";
    return;
  }
  if (isEvidenceMode()) {
    modeChipValue.textContent = "Evidence Mode";
    modeChip.classList.add("evidence");
    return;
  }
  modeChipValue.textContent = "Authority Mode";
  modeChip.classList.add("authority");
}

function updateEvidenceBanner(noticeText) {
  if (!evidenceModeBanner) {
    return;
  }
  const evidenceTitle = "Authority disabled — Evidence Mode active.";
  const evidenceDetail =
    "Tier 2 findings indicate guarantee boundaries detected from source analysis. " +
    "No governance interpretation or risk posture is applied in Evidence Mode.";
  const contextTitle = "Authority disabled — Governance context not declared.";
  const contextDetail = "Declare governance context to enable decision issuance.";
  const bundleTitle = "Authority disabled — Selected bundle has no governance context.";
  const bundleDetail =
    "Re-run analysis with a declared governance context to issue decisions.";
  const licenseTitle = "Authority disabled — License does not permit decisions.";
  const licenseDetail = "Decision Authority license required to issue decision records.";

  let titleText = "";
  let detailText = "";
  const notice = typeof noticeText === "string" ? noticeText.trim() : "";
  const hasNotice = notice.length > 0;
  const decisionState = getDecisionState();
  if (!isLicenseValid()) {
    titleText = "";
    detailText = "";
  } else if (!canIssueDecisions()) {
    titleText = isEvidenceMode() ? evidenceTitle : licenseTitle;
    detailText = isEvidenceMode() ? evidenceDetail : licenseDetail;
  } else if (decisionState === DecisionState.ContextUndeclared) {
    titleText = contextTitle;
    detailText = contextDetail;
  } else if (decisionState === DecisionState.BundleNoContext) {
    titleText = bundleTitle;
    detailText = hasNotice ? notice : bundleDetail;
  }

  evidenceModeBanner.hidden = !titleText;
  if (!titleText) {
    return;
  }
  const title = evidenceModeBanner.querySelector("strong");
  if (title) {
    title.textContent = titleText;
  }
  const detail = evidenceModeBanner.querySelector("span");
  if (detail) {
    detail.textContent = detailText;
    detail.hidden = !detailText;
  }
}

function normalizeLicenseErrorMessage(reason) {
  const text = String(reason || "").trim();
  if (!text) {
    return "";
  }
  const lower = text.toLowerCase();
  if (lower.includes("verification equation") || lower.includes("signature")) {
    return "License signature invalid — modified license detected.";
  }
  if (lower.includes("expired")) {
    return "License expired — authority disabled.";
  }
  if (lower.includes("public key") || lower.includes("pubkey") || lower.includes("pub key")) {
    return "License public key mismatch — authority disabled.";
  }
  return text;
}

function updateLicenseErrorBanner() {
  if (!licenseErrorBanner) {
    return;
  }
  if (!state.license || state.license.valid !== false) {
    licenseErrorBanner.hidden = true;
    licenseErrorBanner.style.display = "none";
    return;
  }
  const reason = state.license?.error || state.license?.reason || "";
  if (!reason || state.license?.reason === "unlicensed") {
    licenseErrorBanner.hidden = true;
    licenseErrorBanner.style.display = "none";
    return;
  }
  const detailText = normalizeLicenseErrorMessage(reason);
  const title = licenseErrorBanner.querySelector("strong");
  if (title) {
    title.textContent = "License error — authority disabled.";
  }
  const detail = licenseErrorBanner.querySelector("span");
  if (detail) {
    detail.textContent = detailText || "License invalid.";
  }
  licenseErrorBanner.hidden = false;
  licenseErrorBanner.style.display = "flex";
}

function updateFooter() {
  if (!footerEvidenceEl && !footerGovernanceEl) {
    return;
  }
  let evidenceText = "Offline only. Evidence recorded.";
  let governanceText = "Governance enforced under declared context.";
  if (!isLicenseValid()) {
    evidenceText = "Offline only. License required for evidence.";
    governanceText = "Governance disabled.";
  } else if (isEvidenceMode()) {
    evidenceText = "Offline only. Evidence recorded.";
    governanceText = "Evidence enforced. Governance disabled.";
  } else if (!canIssueDecisions()) {
    evidenceText = "Offline only. Evidence recorded.";
    governanceText = "Governance disabled.";
  } else if (!contextDeclared(state.context)) {
    evidenceText = "Offline only. Evidence recorded.";
    governanceText = "Governance enabled. Context required for decisions.";
  }
  if (footerEvidenceEl) {
    footerEvidenceEl.textContent = evidenceText;
  }
  if (footerGovernanceEl) {
    footerGovernanceEl.textContent = governanceText;
  }
}

function updateNextAction() {
  if (!nextActionCta) {
    return;
  }
  const hasLicense = isLicenseValid();
  const hasContext = contextDeclared(state.context);
  const hasBundles = state.bundles.length > 0;
  let text = "Declare governance context to enable decisions.";
  let href = "#context";
  let bundleTarget = null;

  if (!hasLicense) {
    text = "Place signed license files to enable evidence generation.";
    href = "/license.html";
  } else if (!canDeclareContext()) {
    text = "Evidence Mode active. Decision authority required to declare governance context.";
    href = "/license.html";
  } else if (!hasContext) {
    text = "Declare governance context to enable decisions.";
    href = "#context";
  } else if (!hasBundles) {
    text = "Upload COBOL source to generate evidence.";
    href = "#upload";
  } else {
    text = "View authority outputs from the latest evidence bundle.";
    href = "#bundles";
    bundleTarget = state.bundles[0]?.path || null;
  }

  nextActionCta.textContent = text;
  nextActionCta.setAttribute("href", href);
  if (bundleTarget) {
    nextActionCta.dataset.bundleTarget = bundleTarget;
  } else {
    delete nextActionCta.dataset.bundleTarget;
  }
}

function updateUploadState() {
  if (!uploadRun) {
    return;
  }
  const enabled = !!state.license?.valid;
  uploadRun.disabled = !enabled;
  if (!enabled && uploadStatus) {
    uploadStatus.textContent = "License required to generate evidence.";
  } else if (enabled && uploadStatus && uploadStatus.textContent === "License required to generate evidence.") {
    uploadStatus.textContent = "";
  }
}

function buildReportLinks(container, bundleId) {
  if (!container || !bundleId) {
    return;
  }
  const normalized = bundleId.startsWith("evidence-bundle-") ? bundleId : `evidence-bundle-${bundleId}`;
  container.innerHTML = "";
  const labels = {
    executive: "Executive Decision Summary",
    board: "Board Decision Record",
    engineering: "Engineering Evidence Record",
    regulatory: "Regulatory Evidence Packet",
  };
  const reportTypes = [
    { type: "executive", allow: canViewExecutiveReports() },
    { type: "board", allow: canViewBoardReports() },
    { type: "engineering", allow: true },
    { type: "regulatory", allow: true },
  ];
  reportTypes.forEach(({ type, allow }) => {
    if (!allow) {
      return;
    }
    const link = document.createElement("a");
    link.href = `/api/bundles/${normalized}/report/${type}/pdf?download=true`;
    link.textContent = `Download ${labels[type]} (PDF)`;
    link.setAttribute("download", "");
    link.addEventListener("click", (event) => event.stopPropagation());
    container.appendChild(link);
  });
}

function renderBundles() {
  if (!bundleList) {
    return;
  }
  bundleList.innerHTML = "";
  if (state.bundles.length === 0) {
    const empty = document.createElement("div");
    empty.className = "panel";
    empty.textContent = "No evidence bundles recorded.";
    bundleList.appendChild(empty);
    return;
  }

  const visibleBundles = showAllBundles ? state.bundles : state.bundles.slice(0, 2);
  visibleBundles.forEach((bundle, index) => {
    const card = document.createElement("div");
    card.className = "bundle-card";
    if (index === 0) {
      card.classList.add("newest");
    } else {
      card.classList.add("older");
    }
    if (bundle.path === state.currentBundleId) {
      card.classList.add("active");
    }

    const summary = state.summaries.get(bundle.path) || {};
    const context = summary.manifest?.governance_context || null;
    const contextText = formatContext(context);
    const timestamp = formatTimestamp({
      generated_at: bundle.generated_at,
      created_at_epoch: bundle.created_at_epoch,
    });
    const registryVersion = state.registry?.registry_version || "--";

    const meta = document.createElement("div");
    meta.innerHTML = `
      <h4>${bundle.scan_id || bundle.path || "Bundle"}</h4>
      <p>Timestamp: ${timestamp}</p>
      <p>Context: ${contextText}</p>
      <p>Registry: v${registryVersion}</p>
    `;
    card.appendChild(meta);

    const links = document.createElement("div");
    links.className = "report-links";
    buildReportLinks(links, bundle.path);
    card.appendChild(links);

    if (state.license?.license_id) {
      const details = document.createElement("details");
      details.className = "bundle-license";
      details.innerHTML = `<summary>License ID</summary><span>${state.license.license_id}</span>`;
      card.appendChild(details);
    }

    card.addEventListener("click", () => selectBundle(bundle.path));
    bundleList.appendChild(card);
  });

  if (state.bundles.length > 2) {
    const hiddenCount = state.bundles.length - visibleBundles.length;
    const toggle = document.createElement("div");
    toggle.className = "bundle-toggle";
    const button = document.createElement("button");
    button.className = "ghost";
    button.type = "button";
    button.textContent = showAllBundles
      ? "Show latest 2"
      : `Show all ${state.bundles.length} bundles`;
    if (hiddenCount > 0 && !showAllBundles) {
      const hidden = document.createElement("span");
      hidden.className = "bundle-hidden-count";
      hidden.textContent = `${hiddenCount} hidden`;
      toggle.appendChild(hidden);
    }
    button.addEventListener("click", (event) => {
      event.stopPropagation();
      showAllBundles = !showAllBundles;
      renderBundles();
    });
    toggle.appendChild(button);
    bundleList.appendChild(toggle);
  }
}

async function loadBundleSummary(bundleId) {
  if (state.summaries.has(bundleId)) {
    return state.summaries.get(bundleId);
  }
  const summary = await fetchJson(`/api/bundles/${bundleId}/summary`);
  if (summary) {
    state.summaries.set(bundleId, summary);
  }
  return summary;
}

function setCoverageMetrics(scanSummary, metrics, artifactInventory, evidenceTiers) {
  if (!coverageMetricsEl) {
    return;
  }
  let proofCoverage = metrics?.proof_coverage;
  if (typeof proofCoverage !== "number" || proofCoverage <= 0) {
    const tierCounts = evidenceTiers?.counts;
    const findingsTotal = scanSummary?.findings_total;
    if (tierCounts && typeof findingsTotal === "number" && findingsTotal > 0) {
      const sum = Object.values(tierCounts).reduce(
        (acc, value) => acc + (typeof value === "number" ? value : 0),
        0
      );
      proofCoverage = sum / findingsTotal;
    }
  }
  const proofCoverageLabel =
    typeof proofCoverage === "number" ? `${(proofCoverage * 100).toFixed(1)}%` : "--";
  const copybooksFromInventory = artifactInventory?.counts?.COPYBOOK;
  const copybookCount =
    copybooksFromInventory !== undefined ? copybooksFromInventory : scanSummary?.total_copybooks;
  const rows = [
    ["Programs", scanSummary?.total_programs],
    ["Copybooks", copybookCount],
    ["Lines", scanSummary?.total_lines],
    ["Findings", scanSummary?.findings_total],
    ["Discards", scanSummary?.discards_total],
    ["Proof Coverage", proofCoverageLabel],
  ];
  coverageMetricsEl.innerHTML = "";
  rows.forEach(([label, value]) => {
    const card = document.createElement("div");
    card.className = "metric-card";
    card.innerHTML = `<span>${label}</span><strong>${normalizeValue(value)}</strong>`;
    coverageMetricsEl.appendChild(card);
  });
}

function renderTierMetrics(evidenceTiers) {
  if (!tierMetricsEl) {
    return;
  }
  tierMetricsEl.innerHTML = "";
  if (!evidenceTiers || !evidenceTiers.counts) {
    tierMetricsEl.innerHTML = `<div class="metric-card"><span>Tier 0</span><strong>--</strong></div>`;
    return;
  }
  const order = [
    "TIER_0_SOURCE_PROVEN",
    "TIER_1_ARTIFACT_PROVEN",
    "TIER_2_BOUNDARY_EVIDENCE",
    "NOT_PROVABLE",
  ];
  order.forEach((key) => {
    const info = formatEvidenceTier(key);
    const card = document.createElement("div");
    card.className = "metric-card";
    card.innerHTML = `<span>${info.label}</span><strong>${tierCount(evidenceTiers, key)}</strong>`;
    tierMetricsEl.appendChild(card);
  });
}

function renderArtifactInventory(inventory) {
  if (!artifactSummaryEl || !artifactNoteEl) {
    return;
  }
  artifactSummaryEl.innerHTML = "";
  artifactNoteEl.textContent = "";
  if (!inventory || !inventory.counts) {
    artifactSummaryEl.textContent = "No artifact inventory recorded.";
    return;
  }

  const keys = Object.keys(inventory.counts).sort();
  keys.forEach((key) => {
    const card = document.createElement("div");
    card.className = "metric-card";
    card.innerHTML = `<span>${key}</span><strong>${normalizeValue(inventory.counts[key])}</strong>`;
    artifactSummaryEl.appendChild(card);
  });

  const notes = Array.isArray(inventory.notes) ? inventory.notes : [];
  if (notes.length) {
    artifactNoteEl.textContent = notes.join(" ");
  }
}

function updateFindingsPanel(bundleId, scanSummary) {
  if (!findingsDownloadForm || !findingsCountEl || !findingsNoteEl) {
    return;
  }
  const total = scanSummary?.findings_total;
  findingsCountEl.textContent = `Total ${normalizeValue(total)}`;
  const hasFindings = Number(total || 0) > 0;
  findingsNoteEl.textContent = hasFindings
    ? "Findings are available as a download to avoid rendering large lists."
    : "No findings recorded.";
  findingsDownloadForm.action = bundleId
    ? `/api/bundles/${bundleId}/findings/download`
    : "";
  if (findingsDownloadButton) {
    findingsDownloadButton.disabled = !bundleId || !hasFindings;
  }
  if (findingsDownloadFormat && !findingsDownloadFormat.value) {
    findingsDownloadFormat.value = "json";
  }
}

function renderDiscards(discards) {
  if (!discardsListEl || !discardsCountEl || !discardsNoteEl) {
    return;
  }
  const total = Array.isArray(discards) ? discards.length : 0;
  const visible = Array.isArray(discards) ? discards : [];
  discardsCountEl.textContent = `Total ${total}`;
  discardsListEl.innerHTML = "";
  if (visible.length === 0) {
    discardsListEl.textContent = "No discards recorded.";
    discardsNoteEl.textContent = "";
    return;
  }
  visible.forEach((discard) => {
    const candidate = discard.candidate || {};
    const reason = discard.discard_reason || {};
    const item = document.createElement("div");
    item.className = "evidence-snippet";
    item.innerHTML = `
      <div class="evidence-meta">${normalizeValue(candidate.file)}:${normalizeValue(candidate.line)}</div>
      <pre>${normalizeValue(candidate.snippet)}</pre>
      <div class="evidence-meta">Discarded: ${normalizeValue(reason.explanation)}</div>
    `;
    discardsListEl.appendChild(item);
  });
  discardsNoteEl.textContent = "";
}

function renderDecision(summary, boardReport) {
  if (!decisionPanel || !decisionValueEl || !decisionTimeEl) {
    return;
  }
  const decisionState = getDecisionState();
  if (decisionState !== DecisionState.DecisionIssued) {
    decisionPanel.hidden = true;
    if (decisionDisabled) {
      decisionDisabled.hidden = false;
    }
    if (decisionDisabledTitle && decisionDisabledSubtitle && decisionDisabledNote) {
      if (decisionState === DecisionState.EvidenceOnly) {
        decisionDisabledTitle.textContent = "Decision Records Disabled";
        decisionDisabledSubtitle.textContent =
          "Evidence Mode does not issue decision records or board/executive summaries.";
        decisionDisabledNote.textContent =
          "To issue decision records, use a Decision Authority License and declare context.";
      } else if (decisionState === DecisionState.ContextUndeclared) {
        decisionDisabledTitle.textContent = "Governance Context Not Declared";
        decisionDisabledSubtitle.textContent =
          "Declare governance context before issuing decision records.";
        decisionDisabledNote.textContent =
          "Context declaration is required for decision issuance.";
      } else if (decisionState === DecisionState.ContextDeclared) {
        decisionDisabledTitle.textContent = "No Evidence Bundle Selected";
        decisionDisabledSubtitle.textContent =
          "Upload source artifacts to generate a new evidence bundle.";
        decisionDisabledNote.textContent =
          "Decision records are issued only after evidence is generated under the declared context.";
      } else if (decisionState === DecisionState.BundleNoContext) {
        decisionDisabledTitle.textContent = "Bundle Missing Governance Context";
        decisionDisabledSubtitle.textContent =
          "Selected bundle has no governance context.";
        decisionDisabledNote.textContent =
          "Re-run analysis with a declared governance context to issue decision records.";
      } else {
        decisionDisabledTitle.textContent = "Decision Record Unavailable";
        decisionDisabledSubtitle.textContent = "Decision issuance is unavailable.";
        decisionDisabledNote.textContent = "Verify license and governance context.";
      }
    }
    return;
  }
  if (decisionDisabled) {
    decisionDisabled.hidden = true;
  }
  const manifest = summary?.manifest || {};
  const context = manifest.governance_context || {};
  if (!contextDeclared(context)) {
    decisionPanel.hidden = true;
    return;
  }

  decisionPanel.hidden = false;
  const decisionValue = boardReport?.decision_required || summary?.decision?.decision || "--";
  decisionValueEl.textContent = normalizeDecision(decisionValue);
  decisionTimeEl.textContent = normalizeValue(boardReport?.evidence?.generated_at || manifest.generated_at);
  if (decisionContextStatusEl) {
    decisionContextStatusEl.textContent = "Recorded";
  }
  if (decisionContextEnvironmentEl) {
    decisionContextEnvironmentEl.textContent = normalizeValue(context.environment);
  }
  if (decisionContextRegulatoryEl) {
    decisionContextRegulatoryEl.textContent = normalizeValue(context.regulatory_scope);
  }
  if (decisionContextCriticalityEl) {
    decisionContextCriticalityEl.textContent = normalizeValue(context.business_criticality);
  }

  if (decisionBoundaryPanel) {
    const boundary = summary?.decision?.boundary || {};
    const tiers = summary?.evidence_tiers || {};
    const tier2Count =
      typeof boundary.tier2_count === "number"
        ? boundary.tier2_count
        : tierCount(tiers, "TIER_2_BOUNDARY_EVIDENCE");
    const notProvableCount =
      typeof boundary.not_provable_count === "number"
        ? boundary.not_provable_count
        : tierCount(tiers, "NOT_PROVABLE");
    const rules = Array.isArray(boundary.boundary_rules)
      ? boundary.boundary_rules
      : Array.isArray(tiers.boundary_rules)
      ? tiers.boundary_rules
      : [];
    const present = tier2Count + notProvableCount > 0;
    const blocked = typeof boundary.blocked === "boolean" ? boundary.blocked : present;
    let impact = boundary.decision_impact;
    if (!impact) {
      if (present) {
        impact = isStrictContext(context)
          ? "Boundary evidence terminates deterministic guarantees. Authority cannot be issued under this context."
          : "Boundary evidence detected. A decision record may be issued in this context; however, Tier-2 boundaries terminate deterministic migration guarantees and require a NO-GO determination.";
      } else {
        impact = "No boundary evidence detected in the analyzed scope.";
      }
    }

    decisionBoundaryPanel.hidden = false;
    if (decisionBoundaryStatusEl) {
      decisionBoundaryStatusEl.textContent = present ? "PRESENT" : "ABSENT";
      decisionBoundaryStatusEl.classList.toggle("warn", present);
      decisionBoundaryStatusEl.classList.toggle("ok", !present);
    }
    if (decisionBoundaryTier2El) {
      decisionBoundaryTier2El.textContent = String(tier2Count);
    }
    if (decisionBoundaryNotProvableEl) {
      decisionBoundaryNotProvableEl.textContent = String(notProvableCount);
    }
    if (decisionBoundaryRulesEl) {
      decisionBoundaryRulesEl.textContent = rules.length ? rules.join(", ") : "None";
    }
    if (decisionBoundaryImpactEl) {
      decisionBoundaryImpactEl.textContent = impact;
    }
  }

}

async function selectBundle(bundleId) {
  state.currentBundleId = bundleId;
  renderBundles();

  const summary = await loadBundleSummary(bundleId);
  if (!summary) {
    return;
  }

  const manifest = summary.manifest || {};
  const context = manifest.governance_context || {};
  state.currentAuthorityNotice = manifest.authority_notice || null;
  state.currentBundleContext = context;

  if (bundleIdEl) {
    bundleIdEl.textContent = manifest.scan_id || bundleId;
  }
  if (bundleTimestampEl) {
    bundleTimestampEl.textContent = normalizeValue(manifest.generated_at);
  }
  if (bundleContextEl) {
    bundleContextEl.textContent = formatContext(context);
  }
  if (bundleRegistryEl) {
    const version = state.registry?.registry_version || "--";
    bundleRegistryEl.textContent = `v${version}`;
  }
  if (bundleDeterminismEl) {
    bundleDeterminismEl.textContent = summary.integrity?.bundle_root_hash
      ? "Confirmed"
      : "Unverified";
  }
  if (bundleHashRootEl) {
    bundleHashRootEl.textContent = normalizeValue(summary.integrity?.bundle_root_hash);
  }
  if (bundleHashFindingsEl) {
    bundleHashFindingsEl.textContent = normalizeValue(
      summary.integrity?.findings_integrity?.findings_hash
    );
  }
  if (bundleHashDiscardsEl) {
    bundleHashDiscardsEl.textContent = normalizeValue(
      summary.integrity?.discards_integrity?.discards_hash
    );
  }

  setCoverageMetrics(
    summary.scan_summary || null,
    summary.metrics || null,
    summary.artifact_inventory || null,
    summary.evidence_tiers || null
  );
  renderTierMetrics(summary.evidence_tiers || null);
  renderArtifactInventory(summary.artifact_inventory || null);
  buildReportLinks(reportLinksEl, bundleId);
  updateFindingsPanel(bundleId, summary.scan_summary || null);
  updateEvidenceBanner(state.currentAuthorityNotice);

  const [discards, boardReport] = await Promise.all([
    fetchJson(`/api/bundles/${bundleId}/discards`),
    canViewBoardReports()
      ? fetchJson(`/api/bundles/${bundleId}/report/board/json`)
      : Promise.resolve(null),
  ]);

  renderDiscards(discards || []);
  renderDecision(summary, boardReport || null);
}

async function loadBundles() {
  const data = await fetchJson("/api/bundles");
  const bundles = Array.isArray(data?.bundles) ? data.bundles : [];
  bundles.sort((a, b) => {
    const aKey = Number(a.created_at_epoch || 0);
    const bKey = Number(b.created_at_epoch || 0);
    return bKey - aKey;
  });
  state.bundles = bundles;
  showAllBundles = false;
  renderBundles();
  if (bundles.length === 0) {
    state.currentBundleId = null;
    state.currentAuthorityNotice = null;
    state.currentBundleContext = null;
    updateLicenseErrorBanner();
    updateEvidenceBanner(null);
    updateNextAction();
    return;
  }
  await Promise.all(bundles.map((bundle) => loadBundleSummary(bundle.path)));
  renderBundles();

  if (!state.currentBundleId && bundles.length > 0) {
    selectBundle(bundles[0].path);
  }
  updateNextAction();
}

async function loadRegistry() {
  const data = await fetchJson("/api/registry");
  if (data) {
    state.registry = data;
  }
  updateSystemState();
  renderBundles();
}

async function loadLicenseStatus() {
  const data = await fetchJson("/api/license/status");
  const normalized = normalizeLicenseStatus(data);
  if (normalized) {
    state.license = normalized;
  }
  if (!canDeclareContext()) {
    state.context = null;
    localStorage.removeItem(STORAGE_KEY);
    resetContextFields();
    if (contextStatus) {
      contextStatus.textContent = "Authority license required to declare governance context.";
    }
  }
  updateContextUi();
  updateContextPin();
  updateSystemState();
  updateNextAction();
  updateUploadState();
  updateLicensePanel();
  updateModeChip();
  updateLicenseErrorBanner();
  updateEvidenceBanner(state.currentAuthorityNotice);
  updateFooter();
  renderBundles();
}

function updateLicensePanel() {
  if (!licenseValidityEl && !licenseExpiryEl && !licenseAuthorityEl && !licenseVerificationEl) {
    return;
  }
  if (!state.license) {
    if (licenseValidityEl) {
      licenseValidityEl.textContent = "--";
    }
    if (licenseExpiryEl) {
      licenseExpiryEl.textContent = "--";
    }
    if (licenseAuthorityEl) {
      licenseAuthorityEl.textContent = "--";
    }
    if (licenseVerificationEl) {
      licenseVerificationEl.textContent = "--";
    }
    return;
  }
  const valid = isLicenseValid();
  if (licenseValidityEl) {
    if (valid) {
      licenseValidityEl.textContent = "Valid";
    } else if (state.license.reason === "unlicensed") {
      licenseValidityEl.textContent = "Missing";
    } else {
      licenseValidityEl.textContent = "Invalid";
    }
  }
  if (licenseExpiryEl) {
    licenseExpiryEl.textContent = valid ? formatEpoch(state.license.expires_at_epoch) : "--";
  }
  if (licenseAuthorityEl) {
    const enabled = canIssueDecisions();
    licenseAuthorityEl.textContent = enabled ? "Enabled" : "Disabled";
  }
  if (licenseVerificationEl) {
    licenseVerificationEl.textContent = valid ? "Verified" : "Unverified";
  }
}

function bootContext() {
  state.context = loadContext();
  if (state.license && !canDeclareContext()) {
    state.context = null;
    localStorage.removeItem(STORAGE_KEY);
  }
  if (contextDeclared(state.context)) {
    setContextFields(state.context);
    if (contextStatus) {
      contextStatus.textContent = "Context pinned. Re-analysis required to change.";
    }
  } else if (contextStatus) {
    contextStatus.textContent = "Context not declared.";
  }
  updateContextUi();
  updateContextPin();
  updateSystemState();
  updateNextAction();
  updateUploadState();
  updateEvidenceBanner(state.currentAuthorityNotice);
  updateFooter();
}

if (contextForm) {
  contextForm.addEventListener("submit", (event) => {
    event.preventDefault();
    if (!canDeclareContext()) {
      if (contextStatus) {
        contextStatus.textContent = "Authority license required to declare governance context.";
      }
      return;
    }
    if (!contextEnvironment || !contextRegulatoryScope || !contextBusinessCriticality) {
      return;
    }
    const environment = contextEnvironment.value;
    const regulatoryScope = contextRegulatoryScope.value;
    const businessCriticality = contextBusinessCriticality.value;
    if (!environment || !regulatoryScope || !businessCriticality) {
      if (contextStatus) {
        contextStatus.textContent = "Select all context fields before saving.";
      }
      return;
    }
    const context = {
      environment,
      regulatory_scope: regulatoryScope,
      business_criticality: businessCriticality,
      declared_at: new Date().toISOString(),
    };
    state.context = context;
    saveContext(context);
    setContextFields(context);
    updateContextPin();
    updateContextUi();
    updateSystemState();
    updateNextAction();
    updateUploadState();
    updateFooter();
    if (contextStatus) {
      contextStatus.textContent = "Context pinned. Re-analysis required to change.";
    }
  });
}

if (contextResetButton) {
  contextResetButton.addEventListener("click", () => {
    const confirmed = window.confirm(
      "This will start a new analysis with a different governance context. Existing evidence bundles will remain unchanged. Continue?"
    );
    if (!confirmed) {
      return;
    }
    state.context = null;
    localStorage.removeItem(STORAGE_KEY);
    resetContextFields();
    updateContextUi();
    updateContextPin();
    updateSystemState();
    updateNextAction();
    updateUploadState();
    updateFooter();
    if (contextStatus) {
      contextStatus.textContent = "Context cleared. Re-analysis required.";
    }
  });
}

if (uploadForm) {
  uploadForm.addEventListener("submit", async (event) => {
    event.preventDefault();
    if (!uploadFile || !uploadFile.files || uploadFile.files.length === 0) {
      if (uploadStatus) {
        uploadStatus.textContent = "Select a file to upload.";
      }
      return;
    }
    if (!state.license?.valid) {
      if (uploadStatus) {
        uploadStatus.textContent = "License required to generate evidence.";
      }
      return;
    }

    const files = Array.from(uploadFile.files);
    const progressEntries = [];
    if (uploadProgressList) {
      uploadProgressList.innerHTML = "";
      files.forEach((file) => {
        const item = document.createElement("div");
        item.className = "upload-progress-item";
        item.dataset.state = "queued";

        const nameEl = document.createElement("strong");
        nameEl.textContent = file.name;

        const statusEl = document.createElement("span");
        statusEl.className = "status";
        statusEl.textContent = "Queued";

        item.appendChild(nameEl);
        item.appendChild(statusEl);
        uploadProgressList.appendChild(item);
        progressEntries.push({ item, statusEl });
      });
    }

    const updateEntry = (index, stateLabel, message) => {
      const entry = progressEntries[index];
      if (!entry) {
        return;
      }
      entry.item.dataset.state = stateLabel;
      entry.statusEl.textContent = message;
    };

    const maxParallel = Math.max(1, files.length);
    let nextIndex = 0;
    let completed = 0;
    let failures = 0;
    const completedIds = [];

    const updateSummary = () => {
      if (!uploadStatus) {
        return;
      }
      const label = files.length === 1 ? "codebase" : "codebases";
      if (completed < files.length) {
        uploadStatus.textContent = `Processing ${completed}/${files.length} ${label}...`;
      } else {
        const summary = failures > 0 ? ` (${failures} failed)` : "";
        uploadStatus.textContent = `Processing complete. ${files.length} ${label} processed${summary}.`;
      }
    };

    const runUpload = async (index) => {
      const form = new FormData();
      form.append("file", files[index]);
      if (uploadEncoding) {
        form.append("encoding", uploadEncoding.value);
      }
      if (uploadFormat) {
        form.append("format", uploadFormat.value);
      }
      if (canDeclareContext() && contextDeclared(state.context)) {
        form.append("context_environment", state.context.environment);
        form.append("context_regulatory_scope", state.context.regulatory_scope);
        form.append("context_business_criticality", state.context.business_criticality);
      }

      updateEntry(index, "uploading", "Uploading");
      try {
        const res = await fetch("/api/upload", { method: "POST", body: form });
        const data = await res.json();
        if (!res.ok || data.error) {
          failures += 1;
          updateEntry(index, "error", `Failed: ${data.error || "error"}`);
          return;
        }
        const scanId =
          data.scan_id ||
          (Array.isArray(data.bundles) && data.bundles.length > 0
            ? data.bundles[0].scan_id
            : null);
        if (scanId) {
          completedIds.push(scanId);
          updateEntry(index, "done", `Bundle ${scanId}`);
        } else {
          updateEntry(index, "done", "Complete");
        }
      } catch (err) {
        failures += 1;
        updateEntry(index, "error", "Failed: network error");
      } finally {
        completed += 1;
        updateSummary();
      }
    };

    const worker = async () => {
      while (true) {
        const index = nextIndex;
        nextIndex += 1;
        if (index >= files.length) {
          break;
        }
        await runUpload(index);
      }
    };

    if (uploadRun) {
      uploadRun.disabled = true;
    }
    if (uploadFile) {
      uploadFile.disabled = true;
    }
    updateSummary();
    try {
      const workers = Array.from({ length: maxParallel }, () => worker());
      await Promise.all(workers);
      await loadBundles();
      if (completedIds.length > 0) {
        const bundleId = `evidence-bundle-${completedIds[0]}`;
        selectBundle(bundleId);
      }
    } finally {
      if (uploadRun) {
        uploadRun.disabled = false;
      }
      if (uploadFile) {
        uploadFile.disabled = false;
      }
    }
  });
}

if (nextActionCta) {
  nextActionCta.addEventListener("click", (event) => {
    const target = nextActionCta.dataset.bundleTarget;
    if (target) {
      event.preventDefault();
      selectBundle(target);
      const anchor = document.getElementById("bundles");
      if (anchor) {
        anchor.scrollIntoView({ behavior: "smooth" });
      }
    }
  });
}


bootContext();
loadLicenseStatus();
loadRegistry();
loadBundles();

setInterval(() => {
  loadLicenseStatus();
  loadRegistry();
  loadBundles();
}, 15000);
