<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><%= service.name %> Admin</title>
    <link rel="stylesheet" href="/css/admin.css">
  </head>
  <body>
    <main class="shell">
      <%
        function fmtNumber(value, digits) {
          const num = Number(value || 0);
          if (!Number.isFinite(num)) return '0';
          const options = typeof digits === 'number'
            ? { minimumFractionDigits: digits, maximumFractionDigits: digits }
            : { maximumFractionDigits: 6 };
          return num.toLocaleString('en-US', options);
        }
      %>
      <header class="topbar">
        <div>
          <p class="eyebrow"><%= service.mode %></p>
          <h1><%= service.name %></h1>
        </div>
        <div class="top-actions">
          <a class="nav-button" href="https://aisfor.kr/chain-wallet?next=/wallet">Wallet</a>
          <a class="nav-button" href="/explorer">Explorer</a>
          <a class="nav-button" href="/admin/rewards">Rewards</a>
          <a class="nav-button" href="/admin/ledger-migration">Ledger Migration / 롤백</a>
          <a class="nav-button subtle" href="/admin/logout">Logout</a>
          <div class="status"><span></span>Port <%= service.port %></div>
        </div>
      </header>

      <section class="grid metrics" aria-label="Ledger metrics">
        <article><strong><%= proofs.length %></strong><span>Proofs</span></article>
        <article><strong><%= transactions.length %></strong><span>Transactions</span></article>
        <article><strong><%= nodes.length %></strong><span>Participants</span></article>
        <article><strong><%= backupIndexes.length %></strong><span>Backup Indexes</span></article>
        <article><strong><%= distributedChunks.length %></strong><span>Distributed Chunks</span></article>
        <article><strong><%= pointEntries.length %></strong><span>Point Entries</span></article>
        <article><strong><%= blocks.length %></strong><span>Blocks</span></article>
        <article><strong><%= callbacks.length %></strong><span>Callbacks</span></article>
      </section>



                  <section class="panel">
        <div class="panel-title">
          <h2>Ledger Storage</h2>
          <span><%= ledgerMigration.mode %> / <%= ledgerMigration.currentBackend %> → <%= ledgerMigration.targetBackend %></span>
        </div>
        <div class="chain-strip">
          <div><span>Readiness</span><strong><%= ledgerMigration.readinessScore %>%</strong></div>
          <div><span>Total Rows</span><strong><%= ledgerMigration.totalRows %></strong></div>
          <div><span>DB Config</span><strong><%= ledgerMigration.db.configured ? 'ready' : 'missing' %></strong></div>
          <div><span>Switch</span><strong><%= ledgerMigration.canSwitchBackend ? 'enabled' : 'locked' %></strong></div>
        </div>
        <a class="nav-button" href="/admin/ledger-migration">Ledger Migration / 롤백 상태</a>
      </section>
<section class="panel">
        <div class="panel-title">
          <h2>PLAI Wallet / Coin</h2>
          <span><%= walletStats.coin.symbol %> / <%= walletStats.coin.issuance %></span>
        </div>
        <div class="chain-strip">
          <div><span>Total Supply</span><strong><%= fmtNumber(walletStats.totalSupply) %> <%= walletStats.coin.symbol %></strong></div>
          <div><span>Wallets</span><strong><%= walletStats.walletCount %></strong></div>
          <div><span>Circulating</span><strong><%= fmtNumber(walletStats.circulatingSupply, 6) %></strong></div>
          <div><span>Treasury</span><strong><%= fmtNumber(walletStats.treasuryBalance, 6) %></strong></div>
        </div>

        <form class="inline-form" method="post" action="/admin/wallet/create">
          <input name="label" placeholder="Wallet label" value="Admin Test Wallet">
          <input name="ownerId" placeholder="Owner ID" value="admin-test">
          <input name="faucetAmount" type="number" step="0.000001" min="0" value="1000">
          <button type="submit">Create Test Wallet</button>
        </form>

        <form class="inline-form" method="post" action="/admin/wallet/service-sync">
          <button type="submit">Sync Service Wallets</button>
          <span class="muted">AISFOR / AISTALK / AISGROUP / AISMALL / AISFOR_CHAIN</span>
        </form>

        <form class="inline-form" method="post" action="/admin/wallet/user">
          <input name="userId" placeholder="User _id" value="">
          <input name="label" placeholder="Wallet label" value="PLAI User Wallet">
          <input name="faucetAmount" type="number" step="0.000001" min="0" value="0">
          <input name="note" placeholder="Note" value="Admin user wallet link">
          <button type="submit">Create PLAI User Wallet</button>
        </form>

        <% if ((wallets || []).length >= 2) { %>
          <form class="inline-form" method="post" action="/admin/wallet/transfer">
            <select name="fromAddress">
              <% wallets.forEach(function(wallet) { %>
                <option value="<%= wallet.address %>"><%= wallet.label %> / <%= wallet.balance %> <%= walletStats.coin.symbol %></option>
              <% }) %>
            </select>
            <select name="toAddress">
              <% wallets.forEach(function(wallet) { %>
                <option value="<%= wallet.address %>"><%= wallet.label %> / <%= wallet.address %></option>
              <% }) %>
            </select>
            <input name="amount" type="number" step="0.000001" min="0" value="1">
            <input name="memo" placeholder="Memo" value="Admin transfer test">
            <button type="submit">Transfer <%= walletStats.coin.symbol %></button>
          </form>
        <% } %>

        <div class="grid explorer-grid">
          <article>
            <h2>Service Wallets</h2>
            <% (serviceWallets || []).forEach(function(wallet) { %>
              <div class="item">
                <strong><%= wallet.label %></strong>
                <span><%= wallet.balance %> <%= walletStats.coin.symbol %> / <%= wallet.ownerId %></span>
                <a href="/explorer/address/<%= encodeURIComponent(wallet.address) %>"><code><%= wallet.address %></code></a>
              </div>
            <% }) %>
          </article>
          <article>
            <h2>PLAI User Wallets</h2>
            <% if ((userWallets || []).length === 0) { %><p class="empty">No PLAI user wallets yet.</p><% } %>
            <% (userWallets || []).slice(0, 6).forEach(function(wallet) { %>
              <div class="item">
                <strong><%= wallet.label %></strong>
                <span><%= wallet.balance %> <%= walletStats.coin.symbol %> / user <%= wallet.ownerId %></span>
                <a href="/explorer/address/<%= encodeURIComponent(wallet.address) %>"><code><%= wallet.address %></code></a>
              </div>
            <% }) %>
          </article>
          <article>
            <h2>Latest Wallet</h2>
            <% if ((wallets || []).length > 0) { %>
              <div class="item">
                <strong><%= wallets[0].label %></strong>
                <span><%= wallets[0].balance %> <%= walletStats.coin.symbol %> / <%= wallets[0].ownerType %></span>
                <a href="/explorer/address/<%= encodeURIComponent(wallets[0].address) %>"><code><%= wallets[0].address %></code></a>
              </div>
            <% } else { %>
              <p class="empty">No wallets yet.</p>
            <% } %>
          </article>
        </div>
      </section>

      <section class="panel">
        <div class="panel-title">
          <h2>TRX Temporary Collateral</h2>
          <span><%= trxCollateralStats.config.network %> / <%= trxCollateralStats.config.mode %></span>
        </div>
        <div class="chain-strip">
          <div><span>Confirmed</span><strong><%= fmtNumber(trxCollateralStats.confirmedAmount, 6) %> TRX</strong></div>
          <div><span>Pending</span><strong><%= fmtNumber(trxCollateralStats.pendingAmount, 6) %> TRX</strong></div>
          <div><span>Accounts</span><strong><%= trxCollateralStats.accountCount %></strong></div>
          <div><span>Pending Reviews</span><strong><%= trxCollateralStats.pendingEvents %></strong></div>
          <div><span>TRX / TB</span><strong><%= fmtNumber(trxCollateralStats.config.trxPerTb, 6) %> TRX</strong></div>
          <div><span>Base Capacity</span><strong><%= fmtNumber(trxCollateralStats.config.minimumCapacityTb, 6) %> TB</strong></div>
          <div><span>Node Minimum</span><strong><%= fmtNumber(trxCollateralStats.config.minNodeCollateral, 6) %> TRX</strong></div>
        </div>
        <form class="inline-form" method="post" action="/admin/collateral/trx/config">
          <input name="trxPerTb" type="number" step="0.000001" min="0.000001" value="<%= trxCollateralStats.config.trxPerTb || 100 %>" placeholder="TRX per 1TB">
          <input name="minimumCapacityTb" type="number" step="0.000001" min="0.000001" value="<%= trxCollateralStats.config.minimumCapacityTb || 1 %>" placeholder="Base TB">
          <button type="submit">Update TRX/TB Policy</button>
          <span class="muted">Current: 1TB = <%= fmtNumber(trxCollateralStats.config.trxPerTb || 100, 6) %> TRX</span>
        </form>
        <p class="muted">TRX is a temporary collateral asset before public PLAI staking/collateral is available. Confirm only after checking the real TRON transaction.</p>
        <% if (!trxCollateralStats.config.treasuryAddress) { %>
          <p class="empty">Mock TRX addresses are active because PLAI_TRX_TREASURY_ADDRESS is empty. Do not send real TRX until a real treasury address or secured TRON deposit integration is configured.</p>
        <% } %>
        <div class="grid explorer-grid">
          <article>
            <h2>Latest Collateral Requests</h2>
            <% if ((trxCollateralEvents || []).length === 0) { %><p class="empty">No TRX collateral requests yet.</p><% } %>
            <% (trxCollateralEvents || []).slice(0, 8).forEach(function(event) { %>
              <div class="item">
                <strong><%= event.amount %> TRX / <%= event.status %></strong>
                <span><%= event.ownerId %> / <%= event.createdAt %></span>
                <span>from <%= event.senderTrxAddress || '-' %> to <%= event.depositAddress || '-' %></span>
                <code><%= event.externalTxHash || event.id %></code>
                <% if (event.status === 'PENDING_REVIEW') { %>
                  <form class="inline-form" method="post" action="/admin/collateral/trx/<%= encodeURIComponent(event.id) %>/confirm">
                    <input name="externalTxHash" placeholder="TRON tx hash" value="<%= event.externalTxHash || '' %>">
                    <button type="submit">Confirm TRX</button>
                  </form>
                  <form class="inline-form" method="post" action="/admin/collateral/trx/<%= encodeURIComponent(event.id) %>/reject">
                    <input name="reason" placeholder="Reject reason" value="not verified">
                    <button type="submit">Reject</button>
                  </form>
                <% } %>
              </div>
            <% }) %>
          </article>
          <article>
            <h2>Collateral Accounts</h2>
            <% if ((trxCollateralAccounts || []).length === 0) { %><p class="empty">No TRX collateral accounts yet.</p><% } %>
            <% (trxCollateralAccounts || []).slice(0, 8).forEach(function(account) { %>
              <div class="item">
                <strong><%= account.ownerId %> / <%= account.status %></strong>
                <span><%= account.confirmedAmount %> TRX confirmed / <%= account.pendingAmount %> pending</span>
                <code><%= account.depositAddress %></code>
              </div>
            <% }) %>
          </article>
        </div>
      </section>

      <section class="panel testnet-panel">
        <div class="panel-title">
          <h2>PLAI Chain Testnet</h2>
          <span><%= testnetStatus.config.networkId %> / <%= testnetStatus.readiness.status %></span>
        </div>
        <div class="chain-strip testnet-strip">
          <div><span>Readiness</span><strong><%= testnetStatus.readiness.score %>%</strong></div>
          <div><span>Native Symbol</span><strong><%= testnetStatus.config.nativeSymbol %></strong></div>
          <div><span>Coin Issuance</span><strong><%= testnetStatus.config.coinIssuance %></strong></div>
          <div><span>Validators</span><strong><%= testnetStatus.validators.length %></strong></div>
          <div><span>Genesis Hash</span><code><%= testnetStatus.genesis.genesisHash %></code></div>
          <div><span>Latest Block</span><strong>#<%= testnetStatus.blockStats.latestHeight || 0 %></strong></div>
        </div>
        <div class="stat-list testnet-checks" aria-label="Testnet Readiness">
          <% testnetStatus.readiness.checks.forEach(function(check) { %>
            <div class="stat-row">
              <span><%= check.label %><small><%= check.detail %></small></span>
              <strong class="<%= check.ok ? 'ok-text' : 'warn-text' %>"><%= check.ok ? 'OK' : 'WAIT' %></strong>
            </div>
          <% }) %>
        </div>
      </section>
      <section class="panel">
        <div class="panel-title">
          <h2>PLAI Tokenomics v0.1</h2>
          <span><%= rewardStats.tokenomics.config.model %> / <%= rewardStats.tokenomics.config.rewardMode %></span>
        </div>
        <div class="chain-strip">
          <div><span>Reward Unit</span><strong><%= rewardStats.tokenomics.config.rewardUnitName %></strong></div>
          <div><span>Symbol</span><strong><%= rewardStats.tokenomics.config.symbol %></strong></div>
          <div><span>Max Supply</span><strong><%= fmtNumber(rewardStats.tokenomics.config.maxSupply) %></strong></div>
          <div><span>Phase</span><strong><%= rewardStats.tokenomics.config.phase %></strong></div>
          <div><span>Simulated Rewards</span><strong><%= fmtNumber(rewardStats.totalSimulatedReward, 6) %></strong></div>
          <div><span>Flagged</span><strong><%= rewardStats.flaggedCount %></strong></div>
        </div>
        <p class="muted">PoSS = Proof of Service & Storage. 현재 보상은 공개 코인 발행이 아닌 simulation ledger입니다.</p>

        <form class="inline-form" method="post" action="/admin/reward/simulate">
          <input name="actorId" placeholder="Actor ID" value="admin-simulated-user">
          <select name="sourceService">
            <option value="AISFOR_CHAIN">AISFOR_CHAIN</option>
            <option value="AISFOR">AISFOR</option>
            <option value="AISTALK">AISTALK</option>
            <option value="AISGROUP">AISGROUP</option>
            <option value="AISMALL">AISMALL</option>
          </select>
          <select name="category">
            <% rewardStats.tokenomics.categories.forEach(function(category) { %>
              <option value="<%= category %>"><%= category %></option>
            <% }) %>
          </select>
          <input name="actionType" placeholder="Action" value="ADMIN_REWARD_SIMULATION">
          <input name="serviceScore" type="number" step="0.000001" min="0" placeholder="service" value="10">
          <input name="contentScore" type="number" step="0.000001" min="0" placeholder="content" value="0">
          <input name="storageScore" type="number" step="0.000001" min="0" placeholder="storage" value="0">
          <input name="commerceScore" type="number" step="0.000001" min="0" placeholder="commerce" value="0">
          <input name="emoticonScore" type="number" step="0.000001" min="0" placeholder="emoticon" value="0">
          <input name="note" placeholder="Note" value="Admin reward simulation">
          <button type="submit">Simulate Reward</button>
        </form>

        <div class="grid explorer-grid">
          <article>
            <h2>Reward Categories</h2>
            <% Object.keys(rewardStats.totalsByCategory).forEach(function(category) { %>
              <div class="item">
                <strong><%= category %></strong>
                <span><%= fmtNumber(rewardStats.totalsByCategory[category], 6) %> <%= rewardStats.tokenomics.config.symbol %></span>
              </div>
            <% }) %>
          </article>
          <article>
            <h2>Latest Reward Simulation</h2>
            <% if ((rewardStats.latestEntries || []).length === 0) { %><p class="empty">No reward simulations yet.</p><% } %>
            <% (rewardStats.latestEntries || []).slice(0, 5).forEach(function(entry) { %>
              <div class="item">
                <strong><%= entry.category %> / <%= entry.rewardAmount %> <%= entry.symbol %></strong>
                <span><%= entry.sourceService %> / <%= entry.actionType %> / <%= entry.mode %></span>
                <code><%= entry.id %></code>
              </div>
            <% }) %>
          </article>
        </div>
      </section>
      <section class="service-filter panel">
        <div class="panel-title">
          <h2>Service Filter</h2>
          <span><%= selectedService === 'ALL' ? 'all services' : selectedService %></span>
        </div>
        <div class="filter-pills">
          <% serviceOptions.forEach(function(name) { %>
            <a class="filter-pill <%= selectedService === name ? 'active' : '' %>" href="/admin<%= name === 'ALL' ? '' : ('?service=' + name) %>"><%= name === 'ALL' ? 'ALL SERVICES' : name %></a>
          <% }) %>
        </div>
      </section>

      <section class="panel">
        <div class="panel-title">
          <h2>Service Operations</h2>
          <span>chainConfirmed / blockHeight / txHash</span>
        </div>
        <div class="table-wrap">
          <table>
            <thead><tr><th>Service</th><th>Status</th><th>Proof</th><th>Tx</th><th>Callback</th><th>Block</th><th>Latest Proof</th><th>txHash</th></tr></thead>
            <tbody>
              <% const monitorRows = selectedService === 'ALL' ? serviceMonitorRows : serviceMonitorRows.filter(function(row) { return row.serviceName === selectedService; }); %>
              <% if (monitorRows.length === 0) { %>
                <tr><td colspan="8">No service signal yet.</td></tr>
              <% } %>
              <% monitorRows.forEach(function(row) { %>
                <tr>
                  <td><strong><%= row.serviceName %></strong><br><span class="muted"><%= row.latestAt || '-' %></span></td>
                  <td><span class="badge <%= row.status === 'confirmed' ? 'badge-ok' : 'badge-warn' %>"><%= row.status %></span></td>
                  <td><%= row.proofCount %></td>
                  <td><%= row.txCount %></td>
                  <td><%= row.confirmedCallbacks %> / <%= row.callbackCount %></td>
                  <td><%= row.blockHeight %></td>
                  <td><%= row.latestProofType %></td>
                  <td><code><%= row.txHash %></code></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      </section>
      <section class="grid">
        <article class="panel">
          <div class="panel-title"><h2>Node Economy</h2></div>
          <div class="stat-list">
            <div class="stat-row"><span>Total Pledged</span><strong><%= nodeEconomyStats.totalPledged %>P</strong></div>
            <div class="stat-row"><span>Total Locked</span><strong><%= nodeEconomyStats.totalLocked %>P</strong></div>
            <div class="stat-row"><span>Total Rewarded</span><strong><%= nodeEconomyStats.totalRewarded %>P</strong></div>
            <div class="stat-row"><span>Total Slashed</span><strong><%= nodeEconomyStats.totalSlashed %>P</strong></div>
          </div>
        </article>

        <article class="panel">
          <div class="panel-title"><h2>Recent Node Economy Tx</h2></div>
          <% if (nodeEconomyEntries.length === 0) { %><p class="empty">No node economy events yet.</p><% } %>
          <% nodeEconomyEntries.slice(0, 4).forEach((entry) => { %>
            <div class="item">
              <strong><%= entry.eventType %> / <%= entry.amount %>P</strong>
              <span>node <%= entry.nodeId || '-' %> / <%= entry.reason || '-' %></span>
              <code><%= entry.txHash || entry.transactionId || entry.id %></code>
            </div>
          <% }) %>
        </article>
      </section>

      <section class="panel">
        <div class="panel-title">
          <h2>Chain Blocks</h2>
          <span class="muted">pending proofs <%= blockStats.pendingProofs %> / pending tx <%= blockStats.pendingTransactions || 0 %> / auto mine <%= blockStats.autoMineSize %></span>
        </div>
        <div class="chain-strip">
          <div><span>Latest Height</span><strong><%= blockStats.latestHeight %></strong></div>
          <div><span>Chain Verify</span><strong><%= blockChain.ok ? 'OK' : 'CHECK' %></strong></div>
          <div><span>Validators</span><strong><%= blockStats.eligibleValidators || 0 %></strong></div>
          <div><span>Finalized</span><strong><%= blockStats.finalizedBlocks || 0 %></strong></div>
          <div><span>Pending Validation</span><strong><%= blockStats.pendingValidationBlocks || 0 %></strong></div>
          <div><span>Callbacks</span><strong><%= callbackStats.deliveredCallbacks || 0 %>/<%= callbackStats.totalCallbacks || 0 %></strong></div>
          <div><span>Latest Hash</span><code><%= blockStats.latestBlockHash || '-' %></code></div>
        </div>
        <% if (blocks.length === 0) { %><p class="empty">No sealed blocks yet.</p><% } %>
        <% blocks.slice(0, 4).forEach((block) => { %>
          <div class="item">
            <strong>Block #<%= block.height %> / <%= block.status %></strong>
            <span><%= block.proofIds.length %> proofs / <%= block.transactionIds.length %> transactions / votes <%= block.validation?.approveVotes || 0 %>/<%= block.validation?.requiredVotes || 0 %></span>
            <code><%= block.blockHash %></code>
          </div>
        <% }) %>
      </section>

      <section class="panel">
        <div class="panel-title">
          <h2>Service Chain Confirmation</h2>
          <span class="muted">latest callback state per service</span>
        </div>
        <div class="table-wrap">
          <table>
            <thead>
              <tr><th>Service</th><th>Confirmed</th><th>Block</th><th>txHash</th><th>Proof</th><th>Callback</th><th>Time</th></tr>
            </thead>
            <tbody>
              <% const confirmationRows = filteredServiceConfirmations || serviceConfirmations || []; %>
              <% if (confirmationRows.length === 0) { %>
                <tr><td colspan="7" class="muted">No service confirmation rows yet.</td></tr>
              <% } %>
              <% confirmationRows.forEach((row) => { %>
                <tr>
                  <td><strong><%= row.serviceName %></strong><br><span class="muted"><%= row.sourceType || '-' %></span></td>
                  <td><span class="badge <%= row.chainConfirmed ? 'badge-ok' : 'badge-warn' %>"><%= row.chainConfirmed ? 'confirmed' : 'waiting' %></span></td>
                  <td><%= row.blockHeight || '-' %></td>
                  <td><code><%= row.txHash || '-' %></code></td>
                  <td><code><%= row.proofId || '-' %></code></td>
                  <td>
                    <span class="badge <%= row.callbackStatus === 'DELIVERED' || row.callbackStatus === 'MOCK_DELIVERED' ? 'badge-ok' : 'badge-warn' %>"><%= row.callbackStatus %></span>
                    <% if (row.lastError) { %><br><span class="muted"><%= row.lastError %></span><% } %>
                  </td>
                  <td><%= row.confirmedAt || '-' %></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      </section>
      <section class="grid">
        <article class="panel">
          <div class="panel-title"><h2>Callback Status</h2></div>
          <div class="stat-list">
            <% Object.entries(callbackStats.byStatus || {}).forEach(([status, count]) => { %>
              <div class="stat-row"><span><%= status %></span><strong><%= count %></strong></div>
            <% }) %>
            <% if ((callbacks || []).length === 0) { %><p class="empty">No chain confirmation callbacks yet.</p><% } %>
          </div>
        </article>

        <article class="panel">
          <div class="panel-title"><h2>Recent Callbacks</h2></div>
          <% const recentCallbackRows = filteredCallbacks || callbacks; %><% if (recentCallbackRows.length === 0) { %><p class="empty">No callback events yet.</p><% } %><% recentCallbackRows.slice(0, 6).forEach((callback) => { %>
            <div class="item">
              <strong><%= callback.sourceService %> / <%= callback.status %></strong>
              <span>block <%= callback.blockHeight || '-' %> / proof <%= callback.proofId || '-' %></span>
              <code><%= callback.targetUrl || 'mock://delivered' %></code>
            </div>
          <% }) %>
        </article>
      </section>

      <section class="grid">
        <article class="panel">
          <div class="panel-title"><h2>Proofs By Service</h2></div>
          <% const serviceRows = Object.entries(proofStats.byService || {}); %>
          <% if (serviceRows.length === 0) { %><p class="empty">No service proofs yet.</p><% } %>
          <div class="stat-list">
            <% serviceRows.forEach(([serviceName, count]) => { %>
              <div class="stat-row"><span><%= serviceName %></span><strong><%= count %></strong></div>
            <% }) %>
          </div>
        </article>

        <article class="panel">
          <div class="panel-title"><h2>Backup / Chunk Status</h2></div>
          <div class="stat-list">
            <% Object.entries(backupStats.byStatus || {}).forEach(([status, count]) => { %>
              <div class="stat-row"><span>backup <%= status %></span><strong><%= count %></strong></div>
            <% }) %>
            <% Object.entries(backupStats.chunkByStatus || {}).forEach(([status, count]) => { %>
              <div class="stat-row"><span>chunk <%= status %></span><strong><%= count %></strong></div>
            <% }) %>
            <% if (backupIndexes.length === 0 && distributedChunks.length === 0) { %>
              <p class="empty">No backup index or chunk records yet.</p>
            <% } %>
          </div>
        </article>
      </section>

      <section class="panel">
        <div class="panel-title"><h2>Node Participants</h2></div>
        <div class="table-wrap">
          <table>
            <thead>
              <tr><th>Node</th><th>User</th><th>Role</th><th>Status</th><th>Pledge</th><th>Reward</th><th>Proof</th><th>Heartbeat</th></tr>
            </thead>
            <tbody>
              <% nodes.forEach((node) => { %>
                <tr>
                  <td><strong><%= node.deviceName || node.serviceName %></strong><br><code><%= node.nodeId %></code></td>
                  <td><%= node.userId || node.userIdHash || '-' %></td>
                  <td><%= node.role %></td>
                  <td><%= node.status %></td>
                  <td><%= node.lockedPoint || 0 %>P</td>
                  <td><%= node.rewardPoint || 0 %>P</td>
                  <td><%= node.proofSuccessRate || 0 %>%</td>
                  <td><%= node.lastHeartbeatAt || '-' %></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      </section>

      <section class="panel">
        <div class="panel-title"><h2>Backup Indexes</h2></div>
        <div class="table-wrap">
          <table>
            <thead>
              <tr><th>Backup</th><th>Source</th><th>Original</th><th>Chunks</th><th>Status</th><th>Merkle Root</th><th>Updated</th></tr>
            </thead>
            <tbody>
              <% if (backupIndexes.length === 0) { %>
                <tr><td colspan="7" class="muted">No backup index records yet.</td></tr>
              <% } %>
              <% backupIndexes.slice(0, 12).forEach((backup) => { %>
                <tr>
                  <td><code><%= backup.backupId %></code></td>
                  <td><%= backup.sourceType %><br><code><%= backup.sourceId || '-' %></code></td>
                  <td><%= backup.originalFileName || '-' %><br><%= backup.originalSize || 0 %> bytes</td>
                  <td><%= backup.requiredChunks || 0 %> / <%= backup.totalChunks || 0 %></td>
                  <td><%= backup.status %></td>
                  <td><code><%= backup.merkleRoot || '-' %></code></td>
                  <td><%= backup.updatedAt || backup.createdAt %></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      </section>

      <section class="grid">
        <article class="panel">
          <div class="panel-title"><h2>Recent Distributed Chunks</h2></div>
          <% if (distributedChunks.length === 0) { %><p class="empty">No chunk records yet.</p><% } %>
          <% distributedChunks.slice(0, 8).forEach((chunk) => { %>
            <div class="item">
              <strong><%= chunk.status %> / index <%= chunk.chunkIndex %></strong>
              <span>node <%= chunk.nodeId || '-' %> / backup <%= chunk.backupId || '-' %></span>
              <code><%= chunk.chunkHash || chunk.chunkId %></code>
            </div>
          <% }) %>
        </article>

        <article class="panel">
          <div class="panel-title"><h2>Recent Transactions</h2></div>
          <% const recentTransactionRows = filteredTransactions || transactions; %><% if (recentTransactionRows.length === 0) { %><p class="empty">No mock chain transactions yet.</p><% } %>
          <% recentTransactionRows.slice(0, 8).forEach((tx) => { %>
            <div class="item">
              <strong><%= tx.actionType %></strong>
              <span><%= tx.status %> / block <%= tx.blockHeight %></span>
              <code><%= tx.txHash %></code>
            </div>
          <% }) %>
        </article>
      </section>

      <section class="panel">
        <div class="panel-title"><h2>Recent Proofs</h2></div>
        <% const recentProofRows = filteredProofs || proofs; %><% if (recentProofRows.length === 0) { %><p class="empty">No proof ledger entries yet.</p><% } %>
        <% recentProofRows.slice(0, 6).forEach((proof) => { %>
          <div class="item">
            <strong><%= proof.proofType %></strong>
            <span><%= proof.sourceService %> / <%= proof.actorId %> / <%= proof.status %></span>
            <code><%= proof.id %></code>
          </div>
        <% }) %>
      </section>
    </main>
  </body>
</html>
