<!doctype html>
<html lang="<%= lang === 'zh' ? 'zh-CN' : lang %>">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <title><%= t('title') %></title>
    <link rel="stylesheet" href="/css/admin.css?v=evm-wallet-20260718-i18n1">
    <style>
      .evm-wallet-shell { max-width: 980px; }
      .evm-status-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
      .evm-status-grid div { border: 1px solid var(--wallet-line, #334155); padding: 14px; min-width: 0; }
      .evm-status-grid span { display: block; color: var(--wallet-muted, #94a3b8); font-size: 13px; }
      .wallet-native .evm-status-grid strong { display: block; margin-top: 8px; color: #f4f7fb !important; overflow-wrap: anywhere; }
      .evm-address { display: block; padding: 14px; margin: 14px 0; overflow-wrap: anywhere; }
      .evm-recovery { border-color: #b7791f; }
      .evm-recovery code { display: block; margin: 8px 0 16px; padding: 12px; overflow-wrap: anywhere; white-space: normal; }
      .evm-actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: end; }
      .evm-actions label { flex: 1 1 220px; }
      .wallet-native .evm-status-grid .evm-lock { color: #fbbf24 !important; }
      .evm-language { display: flex; flex-wrap: wrap; gap: 6px; justify-content: flex-end; }
      .evm-language .nav-button { min-width: 42px; padding: 8px 10px; text-align: center; }
      .evm-language .active { background: #2563eb; border-color: #3b82f6; color: #fff; }
      .wallet-flow-grid { display: grid; grid-template-columns: minmax(240px, .8fr) minmax(0, 1.2fr); gap: 24px; }
      .wallet-flow-grid > section { min-width: 0; }
      .wallet-flow-grid > section + section { border-left: 1px solid var(--wallet-line, #334155); padding-left: 24px; }
      .receive-qr { display: block; width: 190px; max-width: 100%; margin: 16px auto; background: #fff; padding: 10px; }
      .wallet-balance { font-size: 28px; color: #f4f7fb; margin: 8px 0 14px; overflow-wrap: anywhere; }
      .wallet-check { display: flex !important; align-items: flex-start; gap: 9px; margin: 12px 0; }
      .wallet-check input { flex: 0 0 auto; width: 18px; height: 18px; margin-top: 2px; }
      .wallet-coin-list { display: grid; gap: 0; }
      .wallet-coin-row { display: grid; grid-template-columns: 58px minmax(0, 1fr) minmax(140px, auto); gap: 14px; align-items: center; padding: 14px 0; border-top: 1px solid #3c4656; }
      .wallet-coin-row:first-child { border-top: 0; }
      .wallet-coin-symbol { width: 58px; height: 58px; object-fit: contain; }
      .wallet-coin-name strong, .wallet-coin-balance strong { display: block; color: #f4f7fb; font-size: 19px; }
      .wallet-coin-name span, .wallet-coin-balance span { display: block; margin-top: 5px; color: var(--wallet-muted, #94a3b8); font-size: 13px; }
      .wallet-coin-balance { text-align: right; overflow-wrap: anywhere; }
      .wallet-coin-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }
      .wallet-coin-actions button { width: auto; min-width: 64px; padding: 8px 12px; }
      .wallet-command-bar { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin: 20px 0; }
      .wallet-command { display: grid; justify-items: center; gap: 8px; padding: 0; border: 0; background: transparent; color: #f4f7fb; cursor: pointer; font: inherit; }
      .wallet-command-icon { display: grid; place-items: center; width: 72px; height: 64px; border: 1px solid #3c414a; border-radius: 8px; background: #292b30; color: #f4f7fb; font-size: 34px; line-height: 1; transition: transform .15s ease, background .15s ease; }
      .wallet-command:hover .wallet-command-icon, .wallet-command:focus-visible .wallet-command-icon { transform: translateY(-2px); background: #343840; }
      .wallet-command.primary .wallet-command-icon { border-color: #34d399; background: #3bed8a; color: #07130c; }
      .wallet-command-label { font-weight: 800; }
      .wallet-dialog { position: fixed; inset: 0; z-index: 1200; display: grid; place-items: center; padding: 14px; background: rgba(3, 7, 14, .86); backdrop-filter: blur(3px); }
      .wallet-dialog[hidden] { display: none !important; }
      .wallet-dialog-frame { width: min(760px, 100%); max-height: min(86dvh, 900px); overflow: hidden; border: 1px solid #3c4656; border-radius: 8px; background: #202328; color: #f4f7fb; box-shadow: 0 28px 80px rgba(0, 0, 0, .58); }
      .wallet-dialog-head { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 18px 20px; border-bottom: 1px solid #3c4656; background: #202328; }
      .wallet-dialog-head h2 { margin: 0; }
      .wallet-dialog-close { display: grid; place-items: center; width: 42px; height: 42px; padding: 0; border: 1px solid #48515f; border-radius: 50%; background: #2b2f36; color: #f4f7fb; font-size: 26px; cursor: pointer; }
      .wallet-dialog-body { max-height: calc(min(86dvh, 900px) - 79px); padding: 4px 20px 22px; overflow-y: auto; overscroll-behavior: contain; }
      body.wallet-modal-open { overflow: hidden; }
      .wallet-dialog-section { padding: 20px 0; border-top: 1px solid #3c4656; }
      .wallet-dialog-section:first-child { border-top: 0; }
      .tx-list { display: grid; gap: 0; }
      .tx-row { display: grid; grid-template-columns: 90px minmax(0, 1fr) 120px; gap: 14px; padding: 14px 0; border-top: 1px solid var(--wallet-line, #334155); align-items: start; }
      .tx-row[hidden] { display: none; }
      .tx-row:first-child { border-top: 0; }
      .tx-row code { overflow-wrap: anywhere; white-space: normal; }
      .tx-row > strong, .tx-amount strong { color: #f4f7fb !important; }
      .tx-meta { color: var(--wallet-muted, #94a3b8); font-size: 13px; line-height: 1.6; }
      .tx-amount { text-align: right; color: #f4f7fb; }
      .tx-asset { display: inline-block; color: #38f28b; font-size: 12px; letter-spacing: 0; }
      .wallet-history-links { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
      .wallet-history-links a { color: #66e8b5; font-weight: 800; }
      .wallet-history-filter { display: flex; gap: 6px; margin: 0 0 14px; padding-bottom: 4px; overflow-x: auto; scrollbar-width: thin; }
      .wallet-history-filter button { flex: 0 0 auto; min-height: 38px; padding: 8px 14px; border: 1px solid #46536a; border-radius: 6px; background: #171c25; color: #cbd5e1; font-weight: 800; cursor: pointer; }
      .wallet-history-filter button[aria-pressed="true"] { border-color: #38f28b; background: #164936; color: #fff; }
      .wallet-transfer-overlay { position: fixed; inset: 0; z-index: 1000; display: grid; place-items: center; padding: 20px; background: rgba(3, 8, 18, .82); }
      .wallet-transfer-overlay[hidden] { display: none; }
      .wallet-transfer-progress { width: min(420px, 100%); padding: 26px; border: 1px solid #3b82f6; border-radius: 8px; background: #101827; box-shadow: 0 20px 60px rgba(0, 0, 0, .45); text-align: center; }
      .wallet-transfer-progress h2 { margin: 14px 0 8px; color: #f8fafc; }
      .wallet-transfer-spinner { width: 42px; height: 42px; margin: 0 auto; border: 4px solid #334155; border-top-color: #38bdf8; border-radius: 50%; animation: wallet-spin .8s linear infinite; }
      .wallet-toast { position: fixed; top: 20px; right: 20px; z-index: 1100; width: min(440px, calc(100vw - 40px)); padding: 18px 48px 18px 18px; border: 1px solid #22c55e; border-radius: 8px; background: #10251c; color: #dcfce7; box-shadow: 0 16px 42px rgba(0, 0, 0, .42); overflow-wrap: anywhere; }
      .wallet-toast.error { border-color: #ef4444; background: #2b1418; color: #fee2e2; }
      .wallet-toast strong { display: block; margin-bottom: 6px; font-size: 18px; }
      .wallet-toast p { margin: 0; line-height: 1.5; }
      .wallet-toast-close { position: absolute; top: 8px; right: 8px; width: 34px; height: 34px; padding: 0; border: 0; background: transparent; color: inherit; font-size: 24px; line-height: 1; cursor: pointer; }
      .js-transfer-form[aria-busy="true"] { opacity: .72; }
      @keyframes wallet-spin { to { transform: rotate(360deg); } }
      @media (max-width: 720px) {
        .evm-status-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        .evm-language { justify-content: flex-start; }
        .wallet-flow-grid { grid-template-columns: 1fr; }
        .wallet-flow-grid > section + section { border-left: 0; border-top: 1px solid var(--wallet-line, #334155); padding: 20px 0 0; }
        .wallet-command-bar { gap: 6px; }
        .wallet-command-icon { width: 60px; height: 56px; font-size: 29px; }
        .wallet-command-label { font-size: 14px; }
        .wallet-coin-row { grid-template-columns: 52px minmax(0, 1fr); }
        .wallet-coin-symbol { width: 52px; height: 52px; }
        .wallet-coin-balance { grid-column: 2; text-align: left; }
        .tx-row { grid-template-columns: 72px minmax(0, 1fr); }
        .tx-amount { grid-column: 2; text-align: left; }
      }
    </style>
  </head>
  <body class="wallet-screen">
    <main class="shell explorer-shell wallet-app wallet-native evm-wallet-shell">
      <header class="topbar wallet-topbar">
        <div>
          <p class="eyebrow">PLAIS EVM CANDIDATE</p>
          <h1><%= t('title') %></h1>
          <p class="muted"><%= walletUser.displayName || walletUser.userId %></p>
        </div>
        <div class="top-actions">
          <div class="evm-language" aria-label="Language">
            <% languages.forEach(function(code) { %>
              <a class="nav-button subtle <%= code === lang ? 'active' : '' %>" href="<%= langUrl(code) %>"><%= code.toUpperCase() %></a>
            <% }) %>
          </div>
          <% if (walletUser.isSuperAdmin) { %><a class="nav-button" href="/wallet/evm/admin?lang=<%= lang %>"><%= t('operatorWallet') %></a><% } %>
          <a class="nav-button subtle" href="/explorer?lang=<%= lang %>">Explorer</a>
        </div>
      </header>

      <% if (notice && transferResult) { %><aside class="wallet-toast" id="walletResultToast" role="status" aria-live="polite"><button class="wallet-toast-close" type="button" aria-label="<%= t('close') %>" onclick="this.parentElement.remove()">&times;</button><strong><%= t('transferCompleteTitle') %></strong><p><%= notice %></p></aside><% } else if (notice) { %><section class="panel wallet-success"><%= notice %></section><% } %>
      <% if (error && transferResult) { %><aside class="wallet-toast error" id="walletResultToast" role="alert"><button class="wallet-toast-close" type="button" aria-label="<%= t('close') %>" onclick="this.parentElement.remove()">&times;</button><strong><%= t('transferFailedTitle') %></strong><p><%= error %></p></aside><% } else if (error) { %><section class="panel wallet-alert wallet-alert-error"><%= error %></section><% } %>

      <section class="panel">
        <div class="panel-title"><h2><%= t('candidateStatus') %></h2><span><%= network.online ? 'ONLINE' : 'OFFLINE' %></span></div>
        <div class="evm-status-grid">
          <div><span><%= t('network') %></span><strong><%= network.networkName %></strong></div>
          <div><span>Chain ID</span><strong><%= network.chainId || network.configuredChainId %></strong></div>
          <div><span><%= t('latestBlock') %></span><strong><%= network.blockNumber === null ? '-' : network.blockNumber %></strong></div>
          <div><span><%= t('externalTransfer') %></span><strong class="evm-lock"><%= config.externalTransfersEnabled ? 'OPEN' : 'LOCKED' %></strong></div>
        </div>
      </section>

      <% if (!wallet) { %>
        <section class="panel">
          <div class="panel-title"><h2><%= t('createTitle') %></h2><span>secp256k1</span></div>
          <p class="muted"><%= t('createDescription') %></p>
          <form class="wallet-form" method="post" action="/wallet/evm/create?lang=<%= lang %>">
            <input type="hidden" name="csrfToken" value="<%= csrfToken('create') %>">
            <label><%= t('walletName') %><input name="label" maxlength="100" placeholder="PLAIS EVM Wallet"></label>
            <label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" placeholder="<%= t('pinPlaceholder') %>" required></label>
            <label><%= t('pinConfirm') %><input name="pinConfirm" type="password" inputmode="numeric" minlength="6" maxlength="12" placeholder="<%= t('reenter') %>" required></label>
            <button type="submit"><%= t('createWallet') %></button>
          </form>
        </section>
      <% } else { %>
        <section class="panel">
          <div class="panel-title"><h2><%= wallet.label %></h2><span><%= wallet.status %></span></div>
          <code class="address-code evm-address" id="evmAddress"><%= wallet.address %></code>
          <div class="wallet-actions">
            <button class="nav-button" type="button" onclick="copyText('evmAddress', this)"><%= t('copyAddress') %></button>
          </div>
          <div class="evm-status-grid">
            <div><span><%= t('balance') %></span><strong id="walletLiveBalance"><%= account ? account.balance : '0' %> PLAIS</strong></div>
            <div><span><%= t('protocol') %></span><strong><%= wallet.protocol %></strong></div>
            <div><span>Chain ID</span><strong><%= wallet.chainId %></strong></div>
            <div><span><%= t('created') %></span><strong><%= new Date(wallet.createdAt).toLocaleString(localeTag) %></strong></div>
            <div><span><%= t('keyStorage') %></span><strong><%= t('pinEncrypted') %></strong></div>
          </div>
        </section>

        <section class="panel">
          <div class="panel-title"><h2><%= ({ ko: '코인 목록', en: 'Coins', zh: '代币列表', ja: 'コイン一覧' })[lang] || 'Coins' %></h2><span>4</span></div>
          <div class="wallet-coin-list">
            <div class="wallet-coin-row">
              <img class="wallet-coin-symbol" src="/images/plais-symbol.png" alt="PLAIS symbol">
              <div class="wallet-coin-name"><strong>PLAIS</strong><span><%= network.networkName %></span></div>
              <div class="wallet-coin-balance"><strong id="walletCoinListBalance"><%= account ? account.balance : '0' %> PLAIS</strong><span><%= t('balance') %></span></div>
            </div>
            <div class="wallet-coin-row">
              <img class="wallet-coin-symbol" src="/images/bnb-symbol.svg" alt="BNB symbol">
              <div class="wallet-coin-name"><strong>BNB</strong><span>BNB Smart Chain</span></div>
              <div class="wallet-coin-balance"><strong id="walletBnbBalance"><%= multiChain.bsc.bnbBalance %> BNB</strong><span>Native coin · network fee</span><div class="wallet-coin-actions"><button class="nav-button subtle" type="button" onclick="openWalletDialog('bnbReceiveDialog')"><%= t('receive') %></button><button class="nav-button" type="button" onclick="openWalletDialog('bnbSendDialog')"><%= t('send') %></button></div></div>
            </div>
            <div class="wallet-coin-row">
              <img class="wallet-coin-symbol" src="/images/babydoge-symbol.png" alt="Baby Doge Coin symbol">
              <div class="wallet-coin-name"><strong>BABYDOGE</strong><span>BNB Smart Chain</span></div>
              <div class="wallet-coin-balance"><strong id="walletBabyDogeBalance"><%= multiChain.bsc.babyDogeBalance %> BABYDOGE</strong><span>Network fee: BNB</span><div class="wallet-coin-actions"><button class="nav-button subtle" type="button" onclick="openWalletDialog('babyDogeReceiveDialog')"><%= t('receive') %></button><button class="nav-button" type="button" onclick="openWalletDialog('babyDogeSendDialog')"><%= t('send') %></button></div></div>
            </div>
            <div class="wallet-coin-row">
              <img class="wallet-coin-symbol" src="/images/trx-symbol.png" alt="TRX symbol">
              <div class="wallet-coin-name"><strong>TRX</strong><span>TRON Mainnet</span></div>
              <div class="wallet-coin-balance"><strong id="walletTrxBalance"><%= multiChain.tron.balance %> TRX</strong><span><%= multiChain.tron.activated ? 'Active' : 'Not activated' %></span><div class="wallet-coin-actions"><button class="nav-button subtle" type="button" onclick="openWalletDialog('trxReceiveDialog')"><%= t('receive') %></button><button class="nav-button" type="button" onclick="openWalletDialog('trxSendDialog')"><%= t('send') %></button></div></div>
            </div>
          </div>
        </section>

        <div class="wallet-dialog" id="bnbReceiveDialog" role="dialog" aria-modal="true" hidden style="display:none"><div class="wallet-dialog-frame"><div class="wallet-dialog-head"><h2>BNB <%= t('receive') %></h2><button class="wallet-dialog-close" type="button" onclick="closeWalletDialog('bnbReceiveDialog')">&times;</button></div><div class="wallet-dialog-body"><section class="wallet-dialog-section"><p class="muted">BNB Smart Chain native BNB only</p><% if (receiveQr) { %><img class="receive-qr" src="<%= receiveQr %>" alt="BNB receive QR"><% } %><code class="address-code evm-address" id="bnbReceiveAddress"><%= wallet.address %></code><button class="nav-button" type="button" onclick="copyText('bnbReceiveAddress', this)"><%= t('copyAddress') %></button></section></div></div></div>
        <div class="wallet-dialog" id="bnbSendDialog" role="dialog" aria-modal="true" hidden style="display:none"><div class="wallet-dialog-frame"><div class="wallet-dialog-head"><h2>BNB <%= t('send') %></h2><button class="wallet-dialog-close" type="button" onclick="closeWalletDialog('bnbSendDialog')">&times;</button></div><div class="wallet-dialog-body"><section class="wallet-dialog-section"><p class="muted">The network fee is paid separately from the BNB amount.</p><form class="wallet-form js-transfer-form" data-asset="BNB" data-minimum="<%= multiChain.config.bsc.minimumTransferAmount %>" method="post" action="/wallet/evm/send/bnb?lang=<%= lang %>"><input type="hidden" name="csrfToken" value="<%= csrfToken('send-bnb') %>"><label><%= t('recipientAddress') %><input name="to" placeholder="0x..." required></label><label><%= t('amount') %><input name="amount" type="number" min="<%= multiChain.config.bsc.minimumTransferAmount %>" step="0.000001" inputmode="decimal" required></label><label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" required></label><label class="wallet-check"><input name="confirmed" type="checkbox" value="1" required><span><%= t('confirmRecipient') %> <%= t('sendWarning') %></span></label><button type="submit"><%= t('sendFunds') %></button></form></section></div></div></div>
        <div class="wallet-dialog" id="babyDogeReceiveDialog" role="dialog" aria-modal="true" hidden style="display:none"><div class="wallet-dialog-frame"><div class="wallet-dialog-head"><h2>BABYDOGE <%= t('receive') %></h2><button class="wallet-dialog-close" type="button" onclick="closeWalletDialog('babyDogeReceiveDialog')">&times;</button></div><div class="wallet-dialog-body"><section class="wallet-dialog-section"><p class="muted">BNB Smart Chain (BEP-20) BABYDOGE only</p><% if (receiveQr) { %><img class="receive-qr" src="<%= receiveQr %>" alt="BABYDOGE receive QR"><% } %><code class="address-code evm-address" id="babyDogeReceiveAddress"><%= wallet.address %></code><button class="nav-button" type="button" onclick="copyText('babyDogeReceiveAddress', this)"><%= t('copyAddress') %></button></section></div></div></div>
        <div class="wallet-dialog" id="babyDogeSendDialog" role="dialog" aria-modal="true" hidden style="display:none"><div class="wallet-dialog-frame"><div class="wallet-dialog-head"><h2>BABYDOGE <%= t('send') %></h2><button class="wallet-dialog-close" type="button" onclick="closeWalletDialog('babyDogeSendDialog')">&times;</button></div><div class="wallet-dialog-body"><section class="wallet-dialog-section"><p class="muted">BNB network fee balance: <%= multiChain.bsc.bnbBalance %> BNB</p><form class="wallet-form js-transfer-form" data-asset="BABYDOGE" data-minimum="<%= multiChain.config.babyDoge.minimumTransferAmount %>" method="post" action="/wallet/evm/send/babydoge?lang=<%= lang %>"><input type="hidden" name="csrfToken" value="<%= csrfToken('send-babydoge') %>"><label><%= t('recipientAddress') %><input name="to" placeholder="0x..." required></label><label><%= t('amount') %><input name="amount" type="number" min="<%= multiChain.config.babyDoge.minimumTransferAmount %>" step="0.000000001" inputmode="decimal" required></label><label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" required></label><label class="wallet-check"><input name="confirmed" type="checkbox" value="1" required><span><%= t('confirmRecipient') %> <%= t('sendWarning') %></span></label><button type="submit"><%= t('sendFunds') %></button></form></section></div></div></div>
        <div class="wallet-dialog" id="trxReceiveDialog" role="dialog" aria-modal="true" hidden style="display:none"><div class="wallet-dialog-frame"><div class="wallet-dialog-head"><h2>TRX <%= t('receive') %></h2><button class="wallet-dialog-close" type="button" onclick="closeWalletDialog('trxReceiveDialog')">&times;</button></div><div class="wallet-dialog-body"><section class="wallet-dialog-section"><p class="muted">TRON Mainnet native TRX only</p><% if (tronReceiveQr) { %><img class="receive-qr" src="<%= tronReceiveQr %>" alt="TRX receive QR"><% } %><code class="address-code evm-address" id="trxReceiveAddress"><%= multiChain.tron.address %></code><button class="nav-button" type="button" onclick="copyText('trxReceiveAddress', this)"><%= t('copyAddress') %></button></section></div></div></div>
        <div class="wallet-dialog" id="trxSendDialog" role="dialog" aria-modal="true" hidden style="display:none"><div class="wallet-dialog-frame"><div class="wallet-dialog-head"><h2>TRX <%= t('send') %></h2><button class="wallet-dialog-close" type="button" onclick="closeWalletDialog('trxSendDialog')">&times;</button></div><div class="wallet-dialog-body"><section class="wallet-dialog-section"><form class="wallet-form js-transfer-form" data-asset="TRX" data-minimum="<%= multiChain.config.tron.minimumTransferAmount %>" method="post" action="/wallet/evm/send/trx?lang=<%= lang %>"><input type="hidden" name="csrfToken" value="<%= csrfToken('send-trx') %>"><label><%= t('recipientAddress') %><input name="to" placeholder="T..." required></label><label><%= t('amount') %><input name="amount" type="number" min="<%= multiChain.config.tron.minimumTransferAmount %>" step="0.000001" inputmode="decimal" required></label><label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" required></label><label class="wallet-check"><input name="confirmed" type="checkbox" value="1" required><span><%= t('confirmRecipient') %> <%= t('sendWarning') %></span></label><button type="submit"><%= t('sendFunds') %></button></form></section></div></div></div>

        <nav class="wallet-command-bar" aria-label="Wallet actions">
          <button class="wallet-command" type="button" onclick="openWalletDialog('walletReceiveDialog')"><span class="wallet-command-icon" aria-hidden="true">&darr;</span><span class="wallet-command-label"><%= t('receive') %></span></button>
          <button class="wallet-command primary" type="button" onclick="openWalletDialog('walletSendDialog')"><span class="wallet-command-icon" aria-hidden="true">&uarr;</span><span class="wallet-command-label"><%= t('send') %></span></button>
          <button class="wallet-command" type="button" onclick="openWalletDialog('walletHistoryDialog')"><span class="wallet-command-icon" aria-hidden="true">&#8635;</span><span class="wallet-command-label"><%= ({ ko: '내역', en: 'History', zh: '记录', ja: '履歴' })[lang] || 'History' %></span></button>
          <button class="wallet-command" type="button" onclick="openWalletDialog('walletSecurityDialog')"><span class="wallet-command-icon" aria-hidden="true">&#10003;</span><span class="wallet-command-label"><%= ({ ko: '보안', en: 'Security', zh: '安全', ja: 'セキュリティ' })[lang] || 'Security' %></span></button>
        </nav>

        <div class="wallet-dialog" id="walletReceiveDialog" role="dialog" aria-modal="true" aria-labelledby="walletReceiveTitle" hidden style="display:none">
          <div class="wallet-dialog-frame">
            <div class="wallet-dialog-head">
              <h2 id="walletReceiveTitle"><%= t('receive') %></h2>
              <button class="wallet-dialog-close" type="button" aria-label="<%= t('close') %>" onclick="closeWalletDialog('walletReceiveDialog')">&times;</button>
            </div>
            <div class="wallet-dialog-body">
            <section class="wallet-dialog-section">
              <div class="panel-title"><h2><%= t('receive') %></h2><span>PLAIS</span></div>
              <p class="muted"><%= t('receiveDescription') %></p>
              <% if (receiveQr) { %><img class="receive-qr" src="<%= receiveQr %>" alt="<%= t('receiveQrAlt') %>"><% } %>
              <code class="address-code evm-address" id="receiveAddress"><%= wallet.address %></code>
              <button class="nav-button" type="button" onclick="copyText('receiveAddress', this)"><%= t('copyAddress') %></button>
            </section>
            </div>
          </div>
        </div>

        <div class="wallet-dialog" id="walletSendDialog" role="dialog" aria-modal="true" aria-labelledby="walletSendTitle" hidden style="display:none">
          <div class="wallet-dialog-frame">
            <div class="wallet-dialog-head">
              <h2 id="walletSendTitle"><%= t('send') %></h2>
              <button class="wallet-dialog-close" type="button" aria-label="<%= t('close') %>" onclick="closeWalletDialog('walletSendDialog')">&times;</button>
            </div>
            <div class="wallet-dialog-body">
            <section class="wallet-dialog-section">
              <div class="panel-title"><h2><%= t('send') %></h2><span><%= config.externalTransfersEnabled ? 'OPEN' : 'LOCKED' %></span></div>
              <p class="muted"><%= t('sendDescription') %></p>
              <p class="wallet-balance"><%= account ? account.balance : '0' %> PLAIS</p>
              <form class="wallet-form js-transfer-form" method="post" action="/wallet/evm/send?lang=<%= lang %>">
                <input type="hidden" name="csrfToken" value="<%= csrfToken('send') %>">
                <label><%= t('recipientAddress') %><input name="to" autocomplete="off" placeholder="0x..." required></label>
                <label><%= t('amount') %><input name="amount" type="number" min="<%= config.minimumTransferAmount %>" step="<%= config.minimumTransferAmount %>" inputmode="decimal" placeholder="1.000000" required></label>
                <p class="muted js-amount-preview" aria-live="polite"><%= lang === 'ko' ? '최소 전송 단위' : 'Minimum transfer' %>: <strong><%= config.minimumTransferAmount %> PLAIS</strong></p>
                <label><%= t('memo') %> (<%= t('optional') %>)<input name="memo" maxlength="200"></label>
                <label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" required></label>
                <p class="muted"><%= t('estimatedFee') %>: <strong><%= account && account.estimatedFee ? account.estimatedFee : '-' %> PLAIS</strong></p>
                <label class="wallet-check"><input name="confirmed" type="checkbox" value="1" required><span><%= t('confirmRecipient') %> <%= t('sendWarning') %></span></label>
                <button type="submit" <%= config.externalTransfersEnabled ? '' : 'disabled' %>><%= t('sendFunds') %></button>
              </form>
            </section>
            </div>
          </div>
        </div>

        <div class="wallet-dialog" id="walletHistoryDialog" role="dialog" aria-modal="true" aria-labelledby="walletHistoryTitle" hidden style="display:none">
          <div class="wallet-dialog-frame">
          <div class="wallet-dialog-head">
            <h2 id="walletHistoryTitle"><%= t('transactionHistory') %></h2>
            <button class="wallet-dialog-close" type="button" aria-label="<%= t('close') %>" onclick="closeWalletDialog('walletHistoryDialog')">&times;</button>
          </div>
          <div class="wallet-dialog-body">
          <div class="panel-title"><span></span><a class="nav-button subtle" href="/wallet/evm?personal=<%= walletUser.isSuperAdmin ? '1' : '0' %>&amp;lang=<%= lang %>"><%= t('refresh') %></a></div>
          <div class="wallet-history-filter" data-history-target="walletLiveTransactions" data-empty-target="walletHistoryEmpty" data-active-asset="ALL" aria-label="Coin history filter">
            <button type="button" data-asset-filter="ALL" aria-pressed="true"><%= ({ ko: '전체', en: 'All', zh: '全部', ja: 'すべて' })[lang] || 'All' %></button>
            <button type="button" data-asset-filter="PLAIS" aria-pressed="false">PLAIS</button>
            <button type="button" data-asset-filter="BNB" aria-pressed="false">BNB</button>
            <button type="button" data-asset-filter="BABYDOGE" aria-pressed="false">BABYDOGE</button>
            <button type="button" data-asset-filter="TRX" aria-pressed="false">TRX</button>
          </div>
          <p class="muted" id="walletHistoryEmpty" <%= walletTransactions.length ? 'hidden' : '' %>><%= t('noTransactions') %></p>
          <div class="tx-list" id="walletLiveTransactions">
            <% walletTransactions.forEach(function(tx) { const outgoing = tx.direction === 'out'; %>
              <div class="tx-row" data-wallet-asset="<%= tx.asset %>">
                <strong><span class="tx-asset"><%= tx.asset %></span><br><%= outgoing ? t('sent') : t('received') %></strong>
                <div>
                  <code><%= tx.hash %></code>
                  <div class="tx-meta"><%= outgoing ? tx.to : tx.from %><br><%= new Date(tx.createdAt).toLocaleString(localeTag) %> · <%= t(tx.status === 'confirmed' ? 'confirmed' : (tx.status === 'failed' ? 'failedStatus' : 'pending')) %><% if (tx.blockNumber) { %> · <%= t('block') %> <%= tx.blockNumber %><% } %></div>
                  <a href="<%= tx.explorerUrl %><%= tx.asset === 'PLAIS' ? '?lang=' + lang : '' %>" <%- tx.asset === 'PLAIS' ? '' : 'target="_blank" rel="noopener noreferrer"' %>><%= t('openExplorer') %></a>
                </div>
                <div class="tx-amount"><strong><%= outgoing ? '-' : '+' %><%= tx.amount %> <%= tx.asset %></strong><% if (tx.fee) { %><div class="tx-meta"><%= t('fee') %> <%= tx.fee %> <%= tx.asset === 'TRX' ? 'TRX' : (tx.asset === 'PLAIS' ? 'PLAIS' : 'BNB') %></div><% } %></div>
              </div>
            <% }) %>
          </div>
          <% if (multiChain && multiChain.transactions) { %><div class="wallet-history-links"><a href="<%= multiChain.transactions.bscAddressUrl %>" target="_blank" rel="noopener noreferrer">BSC <%= t('openExplorer') %></a><a href="<%= multiChain.transactions.tronAddressUrl %>" target="_blank" rel="noopener noreferrer">TRON <%= t('openExplorer') %></a></div><% } %>
          </div>
          </div>
        </div>

        <div class="wallet-dialog" id="walletSecurityDialog" role="dialog" aria-modal="true" aria-labelledby="walletSecurityTitle" hidden style="display:none">
          <div class="wallet-dialog-frame">
          <div class="wallet-dialog-head">
            <h2 id="walletSecurityTitle"><%= t('recoveryCheck') %></h2>
            <button class="wallet-dialog-close" type="button" aria-label="<%= t('close') %>" onclick="closeWalletDialog('walletSecurityDialog')">&times;</button>
          </div>
          <div class="wallet-dialog-body">
        <section class="wallet-dialog-section">
          <div class="panel-title"><h2><%= t('signatureTitle') %></h2><span><%= t('localVerification') %></span></div>
          <form class="wallet-form compact evm-actions" method="post" action="/wallet/evm/verify-signature?lang=<%= lang %>">
            <input type="hidden" name="csrfToken" value="<%= csrfToken('verify') %>">
            <label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" required></label>
            <button type="submit"><%= t('verifySignature') %></button>
          </form>
          <% if (signatureCheck) { %>
            <p class="wallet-success"><%= t('verificationResult') %>: <strong><%= signatureCheck.verified ? t('valid') : t('failed') %></strong></p>
            <code class="evm-address"><%= signatureCheck.signature %></code>
          <% } %>
        </section>

        <section class="wallet-dialog-section">
          <div class="panel-title"><h2><%= t('recoveryCheck') %></h2><span><%= t('pinRequired') %></span></div>
          <form class="wallet-form compact evm-actions" method="post" action="/wallet/evm/recovery/export?lang=<%= lang %>">
            <input type="hidden" name="csrfToken" value="<%= csrfToken('recovery') %>">
            <label><%= t('securityPin') %><input name="pin" type="password" inputmode="numeric" minlength="6" maxlength="12" required></label>
            <button type="submit"><%= t('openRecovery') %></button>
          </form>
        </section>

        <% if (recovery) { %>
        <section class="wallet-dialog-section evm-recovery">
          <div class="panel-title"><h2><%= t('recoveryInfo') %></h2><span><%= t('hiddenOnClose') %></span></div>
          <p class="wallet-alert-error"><%= t('recoveryWarning') %></p>
          <span><%= t('mnemonic') %></span>
          <code id="evmMnemonic"><%= recovery.mnemonic %></code>
          <button class="nav-button subtle" type="button" onclick="copyText('evmMnemonic', this)"><%= t('copyMnemonic') %></button>
          <span><%= t('privateKey') %></span>
          <code id="evmPrivateKey"><%= recovery.privateKey %></code>
          <button class="nav-button subtle" type="button" onclick="copyText('evmPrivateKey', this)"><%= t('copyPrivateKey') %></button>
        </section>
        <% } %>
          </div>
          </div>
        </div>
      <% } %>
    </main>
    <div class="wallet-transfer-overlay" id="walletTransferOverlay" role="status" aria-live="assertive" aria-busy="true" hidden>
      <div class="wallet-transfer-progress">
        <div class="wallet-transfer-spinner" aria-hidden="true"></div>
        <h2><%= t('sending') %></h2>
        <p class="muted"><%= t('sendingDescription') %></p>
      </div>
    </div>
    <script>
      const copiedText = <%- JSON.stringify(t('copied')) %>;
      function openWalletDialog(id) {
        const dialog = document.getElementById(id);
        if (!dialog) return;
        dialog.style.removeProperty('display');
        dialog.hidden = false;
        document.body.classList.add('wallet-modal-open');
        const closeButton = dialog.querySelector('.wallet-dialog-close');
        if (closeButton) closeButton.focus();
      }
      function closeWalletDialog(id) {
        const dialog = document.getElementById(id);
        if (!dialog) return;
        dialog.hidden = true;
        dialog.style.display = 'none';
        if (!document.querySelector('.wallet-dialog:not([hidden])')) {
          document.body.classList.remove('wallet-modal-open');
        }
      }
      function scrollWalletPanel(id) {
        const target = document.getElementById(id);
        if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
      function applyWalletHistoryFilter(group, asset) {
        if (!group) return;
        const target = document.getElementById(group.dataset.historyTarget);
        if (!target) return;
        let visible = 0;
        target.querySelectorAll('[data-wallet-asset]').forEach(function(row) {
          const show = asset === 'ALL' || row.dataset.walletAsset === asset;
          row.hidden = !show;
          if (show) visible += 1;
        });
        group.dataset.activeAsset = asset;
        group.querySelectorAll('[data-asset-filter]').forEach(function(button) {
          button.setAttribute('aria-pressed', button.dataset.assetFilter === asset ? 'true' : 'false');
        });
        const empty = document.getElementById(group.dataset.emptyTarget);
        if (empty) empty.hidden = visible !== 0;
      }
      document.querySelectorAll('.wallet-history-filter').forEach(function(group) {
        group.addEventListener('click', function(event) {
          const button = event.target.closest('[data-asset-filter]');
          if (button) applyWalletHistoryFilter(group, button.dataset.assetFilter);
        });
        applyWalletHistoryFilter(group, group.dataset.activeAsset || 'ALL');
      });
      document.querySelectorAll('.wallet-dialog').forEach(function(dialog) {
        dialog.addEventListener('click', function(event) {
          if (event.target === dialog) closeWalletDialog(dialog.id);
        });
      });
      document.addEventListener('keydown', function(event) {
        if (event.key !== 'Escape') return;
        const dialog = document.querySelector('.wallet-dialog:not([hidden])');
        if (dialog) closeWalletDialog(dialog.id);
      });
      function copyText(id, button) {
        const value = document.getElementById(id).textContent.trim();
        navigator.clipboard.writeText(value).then(function() {
          const previous = button.textContent;
          button.textContent = copiedText;
          setTimeout(function() { button.textContent = previous; }, 1200);
        });
      }
      document.querySelectorAll('.js-transfer-form').forEach(function(form) {
        const transferAsset = form.dataset.asset || 'PLAIS';
        const minimumAmount = form.dataset.minimum || <%- JSON.stringify(config.minimumTransferAmount) %>;
        const amountInput = form.querySelector('input[name="amount"]');
        const amountPreview = form.querySelector('.js-amount-preview strong');
        if (amountInput && amountPreview) {
          amountInput.addEventListener('input', function() {
            amountPreview.textContent = (amountInput.value || minimumAmount) + ' ' + transferAsset;
          });
        }
        form.addEventListener('submit', function(event) {
          if (form.dataset.submitting === '1') {
            event.preventDefault();
            return;
          }
          const amount = amountInput ? amountInput.value : '';
          const confirmText = <%- JSON.stringify(lang === 'ko' ? '전송 수량을 다시 확인하세요.\n\n' : 'Confirm the transfer amount.\n\n') %> + amount + ' ' + transferAsset;
          if (!window.confirm(confirmText)) {
            event.preventDefault();
            return;
          }
          form.dataset.submitting = '1';
          form.setAttribute('aria-busy', 'true');
          const submitButton = form.querySelector('button[type="submit"]');
          if (submitButton) {
            submitButton.disabled = true;
            submitButton.textContent = <%- JSON.stringify(t('sending')) %>;
          }
          document.getElementById('walletTransferOverlay').hidden = false;
        });
      });
      <% if (signatureCheck || recovery) { %>
      openWalletDialog('walletSecurityDialog');
      <% } %>
      const resultToast = document.getElementById('walletResultToast');
      if (resultToast && !resultToast.classList.contains('error')) {
        setTimeout(function() { resultToast.remove(); }, 10000);
      }
      const resultUrl = new URL(window.location.href);
      if (resultUrl.searchParams.has('sent') || resultUrl.searchParams.has('errorCode')) {
        resultUrl.searchParams.delete('sent');
        resultUrl.searchParams.delete('errorCode');
        window.history.replaceState({}, '', resultUrl.pathname + (resultUrl.search ? resultUrl.search : ''));
      }
      if (document.getElementById('walletLiveBalance')) {
        setInterval(async function() {
          if (document.hidden || document.querySelector('.js-transfer-form[aria-busy="true"]')) return;
          try {
            const response = await fetch(window.location.href, { credentials: 'same-origin', cache: 'no-store' });
            if (!response.ok) return;
            const nextDocument = new DOMParser().parseFromString(await response.text(), 'text/html');
            const nextBalance = nextDocument.getElementById('walletLiveBalance');
            const nextCoinBalance = nextDocument.getElementById('walletCoinListBalance');
            const nextBabyDogeBalance = nextDocument.getElementById('walletBabyDogeBalance');
            const nextBnbBalance = nextDocument.getElementById('walletBnbBalance');
            const nextTrxBalance = nextDocument.getElementById('walletTrxBalance');
            const nextTransactions = nextDocument.getElementById('walletLiveTransactions');
            if (nextBalance) document.getElementById('walletLiveBalance').textContent = nextBalance.textContent;
            if (nextCoinBalance) document.getElementById('walletCoinListBalance').textContent = nextCoinBalance.textContent;
            if (nextBabyDogeBalance) document.getElementById('walletBabyDogeBalance').textContent = nextBabyDogeBalance.textContent;
            if (nextBnbBalance) document.getElementById('walletBnbBalance').textContent = nextBnbBalance.textContent;
            if (nextTrxBalance) document.getElementById('walletTrxBalance').textContent = nextTrxBalance.textContent;
            if (nextTransactions) {
              document.getElementById('walletLiveTransactions').innerHTML = nextTransactions.innerHTML;
              const historyFilter = document.querySelector('[data-history-target="walletLiveTransactions"]');
              applyWalletHistoryFilter(historyFilter, historyFilter ? historyFilter.dataset.activeAsset : 'ALL');
            }
          } catch (error) {
            // A temporary refresh failure must not interrupt wallet use.
          }
        }, 10000);
      }
    </script>
  </body>
</html>
