// ── Veritee · Environment Status tab ──────────────────────────────────────────
// Home of the ledger-wide numbers and the production artifacts: the
// attestation smart contract, source repos, and the Veritee Base OS image.
// Loads after Explorer.jsx and reuses its globals (StatCard, explorerContractUrl,
// fmtCount, fmtDate, shortHash, OsAcceptancePill).

/* One key/value row inside a status column. */
const StatusField = ({ label, children, mono = true, copyable }) => (
  <div className="tem-status-field" style={{ display: "grid", gridTemplateColumns: "150px 1fr", gap: 14, padding: "10px 0", borderBottom: "1px solid rgba(0,48,88,0.15)", alignItems: "start" }}>
    <div style={{ fontSize: 11.5, fontFamily: "var(--font-mono)", color: "var(--v-teal)", paddingTop: 2 }}>{label}</div>
    <div style={{ fontSize: 12.5, fontFamily: "var(--font-mono)", minWidth: 0, wordBreak: "break-all" }}>
      {mono && copyable ? <Mono copyable size={12.5}>{children}</Mono> : children}
    </div>
  </div>
);

const StatusColumn = ({ title, children }) => (
  <div style={{ padding: "18px 22px 10px", borderRight: "1px solid var(--v-hair)", borderBottom: "1px solid var(--v-hair)", minWidth: 0 }}>
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
      <span style={{ fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1, whiteSpace: "nowrap" }}>{title}</span>
      <DottedRule opacity={0.5} />
    </div>
    {children}
  </div>
);

/* One shared artifact: glyph, name, what it is, where it lives. `url: null`
   renders `note` (default "coming soon") as a chip instead of a link. */
const ArtifactRow = ({ glyph, name, desc, url, urlLabel, note, first }) => (
  <div className="tem-artifact-row v-wash" style={{ display: "grid", gridTemplateColumns: "44px 1fr auto", gap: 16, padding: "14px 22px", borderTop: first ? "none" : "1px solid var(--v-hair)", alignItems: "center" }}>
    <GlyphTile glyph={glyph} />
    <div style={{ minWidth: 0 }}>
      <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 3 }}>{name}</div>
      <div style={{ fontSize: 12.5, lineHeight: 1.55, opacity: 0.75 }}>{desc}</div>
    </div>
    {url ? (
      <a href={url} target="_blank" rel="noopener noreferrer" className="v-press-sm v-tint" style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--v-ink)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6, whiteSpace: "nowrap", border: "var(--v-border)", padding: "5px 12px", background: "var(--v-surface)", boxShadow: "2px 2px 0 var(--v-ink)" }}>
        {urlLabel || "Open"} <Icon.ArrowUpRight size={10} />
      </a>
    ) : (
      <Chip>{note || "coming soon"}</Chip>
    )}
  </div>
);

// Use the same layout and empty states for both environments.
const StatusContractLink = ({ address }) => address && address !== "n/a" ? (
  <div style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: 0 }}>
    <Mono copyable full={address} size={12.5}>{shortHash(address, 18)}</Mono>
    <a href={explorerContractUrl(address)} target="_blank" rel="noopener noreferrer" className="v-link" style={{ fontSize: 11.5, display: "inline-flex", alignItems: "center", gap: 5, whiteSpace: "nowrap", alignSelf: "flex-start" }}>
      View on explorer <Icon.ArrowUpRight size={10} />
    </a>
  </div>
) : <span style={{ opacity: 0.7 }}>Not configured</span>;

/* On-chain OS release registry entries for one environment (os_releases). */
const OS_COLS = "minmax(160px,1fr) 170px 110px 170px 170px 80px";
const OsReleaseList = ({ releases }) => (
  <div style={{ border: "var(--v-border)", background: "var(--v-surface)", overflowX: "auto" }}>
    <div style={{ ...vLabel, display: "grid", gridTemplateColumns: OS_COLS, gap: 14, padding: "9px 20px", background: "var(--v-canvas)", borderBottom: "var(--v-border)", minWidth: 900 }}>
      <span>release</span><span>acceptance</span><span>mode</span><span>raw disk sha256</span><span>pcr4</span><span style={{ textAlign: "right" }}>images</span>
    </div>
    {releases.map((rel, i) => (
      <div key={rel.os_key} className="v-wash" style={{ display: "grid", gridTemplateColumns: OS_COLS, gap: 14, padding: "11px 20px", borderTop: i === 0 ? "none" : "1px solid var(--v-hair)", alignItems: "center", fontFamily: "var(--font-mono)", fontSize: 12, minWidth: 900 }}>
        <span style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
          <span style={{ fontSize: 13, fontWeight: 500 }}>{rel.release_version}</span>
          <Mono copyable full={rel.os_key} color="var(--v-teal)" size={11}>os_key {shortHash(rel.os_key)}</Mono>
        </span>
        <span><OsAcceptancePill acceptance={rel.acceptance} /></span>
        <span>{rel.attestation_mode}</span>
        <Mono copyable full={rel.raw_disk_sha256} size={12}>{shortHash(rel.raw_disk_sha256, 12)}</Mono>
        <Mono copyable full={rel.pcr4} size={12}>{shortHash(rel.pcr4, 12)}</Mono>
        <span style={{ textAlign: "right" }}>{fmtCount(rel.registration_ids.length)}</span>
      </div>
    ))}
  </div>
);

const EnvironmentStatus = ({ name, status, network }) => {
  const chain = status.chainInfo;
  const archiveReady = ["azure-table", "fixture"].includes(status.verificationSource);
  const count = (value) => typeof value === "number" ? fmtCount(value) : "Unavailable";
  const noAnchor = status.anchorCount === 0 ? "No anchors yet" : "Unavailable";
  const registry = status.registrySchema === 1 ? "v1 · OS release registry"
    : typeof status.registrySchema === "number" ? "v" + status.registrySchema
    : status.syncedAt ? "Legacy · no OS release registry" : "Unavailable";

  return (
    <section aria-label={name + " status"} style={{ ...vCard, marginBottom: 32 }}>
      <WindowBar label={name + " · " + network} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 340px), 1fr))" }}>
        <StatusColumn title="Veritee ledger">
          <StatusField label="Network" mono={false}>{network}</StatusField>
          <StatusField label="Contract address"><StatusContractLink address={status.contractAddress} /></StatusField>
          <StatusField label="Measurements">{count(status.attestationCount)}</StatusField>
          <StatusField label="Registry schema">{registry}</StatusField>
          <StatusField label="Approved OS releases">{status.registrySchema ? count(status.osReleaseCount) : status.syncedAt ? "n/a" : "Unavailable"}</StatusField>
          <StatusField label="Latest block">{chain ? count(chain.blockHeight) + (chain.blockTimestamp ? " · " + fmtDate(Date.parse(chain.blockTimestamp)) : "") : "Unavailable"}</StatusField>
          <StatusField label="Latest transaction" copyable={Boolean(chain && chain.txHash)}>{chain && chain.txHash ? chain.txHash : "Unavailable"}</StatusField>
          <StatusField label="Last synced">{status.syncedAt ? fmtDate(Date.parse(status.syncedAt)) : "Awaiting first sync"}</StatusField>
          <StatusField label="Poll interval">{status.pollIntervalMs ? Math.round(status.pollIntervalMs / 1000) + "s" : "Unavailable"}</StatusField>
        </StatusColumn>

        <StatusColumn title="Verification archive & anchoring">
          <StatusField label="Record archive" mono={false}>
            <span style={{ display: "inline-flex", alignItems: "flex-start", gap: 8, opacity: archiveReady ? 1 : 0.7 }}>
              <PixelSquare size={7} color={archiveReady ? "var(--v-teal)" : "var(--v-ink-40)"} style={{ marginTop: 5 }} />
              {status.verificationSource === "azure-table" ? "Connected: write-once blob archive with a queryable index"
                : status.verificationSource === "fixture" ? "Local fixture"
                : "Not configured: verification records unavailable"}
            </span>
          </StatusField>
          <StatusField label="Verification records">{archiveReady ? count(status.verificationCount) : "Unavailable"}</StatusField>
          <StatusField label="Anchor batches on-chain">{count(status.anchorCount)}</StatusField>
          <StatusField label="Records covered by anchors">{count(status.anchoredRecordCount)}</StatusField>
          <StatusField label="Latest anchored window ends">{status.lastAnchoredAt ? fmtDate(Date.parse(status.lastAnchoredAt)) : noAnchor}</StatusField>
          <StatusField label="Latest anchor root" copyable={Boolean(status.lastAnchorRoot)}>{status.lastAnchorRoot || noAnchor}</StatusField>
        </StatusColumn>

        <StatusColumn title="Ledger discovery">
          <StatusField label="Pointer contract"><StatusContractLink address={status.pointer && status.pointer.address} /></StatusField>
          {status.pointer && <>
            <StatusField label="Points to ledger contract" copyable>{status.pointer.current}</StatusField>
            <StatusField label="Ledger contracts to date">{count(status.pointer.updateCount)}</StatusField>
          </>}
        </StatusColumn>
      </div>
    </section>
  );
};

const ProductionStats = () => {
  const D = window.VERITEE_DATA;
  const prod = D.status || { contractAddress: D.contract };
  const environments = [{ name: "Production", status: prod }];
  if (D.staging && D.staging.enabled) environments.push({ name: "Staging", status: D.staging });
  const withReleases = environments
    .map((e) => ({ ...e, releases: (e.status.osReleases || []).map(D.toOsRelease) }))
    .filter((e) => e.releases.length > 0);

  const healthy = !D.loading && !D.error && Boolean(prod.syncedAt);
  const health = D.loading ? "Syncing from contract" : healthy ? "All systems nominal" : "Ledger unavailable";
  const num = (v) => typeof v === "number" ? fmtCount(v) : "—";
  const archiveReady = ["azure-table", "fixture"].includes(prod.verificationSource);

  return (
    <div className="tem-page" style={{ maxWidth: 1280, margin: "0 auto", padding: "40px 56px 96px" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24, flexWrap: "wrap", marginBottom: 32 }}>
        <div style={{ maxWidth: 760 }}>
          <Eyebrow blink={healthy} color={healthy || D.loading ? "var(--v-teal)" : "var(--v-danger)"} style={{ marginBottom: 12 }}>{health}</Eyebrow>
          <h1 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(40px,4.8vw,62px)", lineHeight: 0.98, margin: "0 0 14px" }}>Status</h1>
          <p style={{ fontSize: 15, lineHeight: 1.6, opacity: 0.86 }}>
            Each environment has its own ledger and verification archive. Runtime decisions are stored in an immutable archive;
            the contract periodically records Merkle anchors committing to batches of those records.
          </p>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, border: "var(--v-border)", background: "var(--v-surface)", padding: "8px 12px", boxShadow: "var(--v-shadow-btn)", whiteSpace: "nowrap" }}>
          last sync {prod.syncedAt ? fmtDate(Date.parse(prod.syncedAt)) : "pending"}
        </div>
      </div>

      <div className="tem-stats" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 22, marginBottom: 32 }}>
        <StatCard value={num(prod.attestationCount)} label="measurements on-chain" />
        <StatCard value={archiveReady ? num(prod.verificationCount) : "—"} label="verification records" />
        <StatCard value={num(prod.anchorCount)} label="anchor batches" />
        <StatCard value={prod.registrySchema ? num(prod.osReleaseCount) : "n/a"} label="approved OS releases" />
      </div>

      {environments.map(({ name, status }) => <EnvironmentStatus key={name} name={name} status={status} network={D.network} />)}

      {withReleases.map(({ name, releases }) => (
        <div key={name} style={{ marginBottom: 32 }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 8, flexWrap: "wrap" }}>
            <h2 style={{ fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1 }}>Base OS releases{withReleases.length > 1 ? " · " + name : ""}</h2>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--v-teal)", letterSpacing: "0.08em", textTransform: "uppercase" }}>os_releases · {releases.length}</span>
          </div>
          <p style={{ fontSize: 13.5, lineHeight: 1.6, margin: "0 0 14px", opacity: 0.78, maxWidth: 820 }}>
            Veritee base OS releases approved on this ledger. Every image registered here is admitted against one of them, and the contract enforces that the image's PCR4 matches the release.
          </p>
          <OsReleaseList releases={releases} />
        </div>
      ))}

      <div>
        <h2 style={{ fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1, margin: "0 0 14px" }}>Artifacts</h2>
        <div style={vCard}>
          {environments.map(({ name, status }, i) => (
            <ArtifactRow key={name} first={i === 0} glyph="SC" name={name + " attestation smart contract"}
              desc={status.registrySchema
                ? "On-chain measurement registrations, OS release registry, revocations, and Merkle anchors on Midnight preprod."
                : "On-chain measurement registrations, revocations, and Merkle anchors on Midnight preprod."}
              url={status.contractAddress && status.contractAddress !== "n/a" ? explorerContractUrl(status.contractAddress) : null} urlLabel="Midnight explorer" />
          ))}
          <ArtifactRow glyph="OS" name="Veritee Base OS image"
            desc="The reproducible confidential-VM base image every Veritee TEE application builds on, published to Azure Container Registry. Approved releases are recorded on chain; see Base OS releases above."
            url={null /* the image reference lives in the off-chain signed manifest, not on chain */} note="Azure Container Registry" />
          <ArtifactRow glyph="SRC" name="Smart contract source"
            desc="Compact contract source, CLI tooling, and the compiled bindings this site decodes the ledger with."
            url="https://github.com/input-output-hk/veritee-smart-contracts" urlLabel="GitHub" />
          <ArtifactRow glyph="DOC" name="Veritee protocol"
            desc="Protocol documentation and the Warden attestation service."
            url="https://github.com/input-output-hk/veritee-vm" urlLabel="GitHub" />
        </div>
      </div>
    </div>
  );
};
window.ProductionStats = ProductionStats;
