<%
// Deterministic pastel color per recipient email, so the same mailbox always
// gets the same background - makes scanning a mixed list of mailboxes faster
// than reading the address text each time. Fixed lightness works in both
// light/dark mode since this is a small self-contained pill, not tied to the
// page's own background.
function emailColor(email) {
  let hash = 0;
  for (let i = 0; i < email.length; i += 1) hash = (hash * 31 + email.charCodeAt(i)) % 360;
  return `hsl(${Math.abs(hash)}, 65%, 88%)`;
}

function jamFormat(iso) {
  if (!iso) return '-';
  // toLocaleTimeString('id-ID') uses "." as the separator (12.24.20) - build
  // it manually so it's always colon-separated regardless of locale.
  const parts = new Date(iso).toLocaleTimeString('en-GB', { timeZone: 'Asia/Jakarta', hour12: false }).split(':');
  return `Jam ${parts.join(':')}`;
}
%>
<div class="row">
  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">OTP Terbaru</h3>
        <div class="card-tools">
          <button class="btn btn-sm btn-outline-secondary" onclick="location.reload()">
            <i class="fas fa-sync-alt mr-1"></i> Refresh
          </button>
        </div>
      </div>
      <div class="card-body p-0">
        <ul class="list-group list-group-flush">
          <% if (!messages.length) { %>
            <li class="list-group-item text-muted">Belum ada OTP yang terdeteksi di mailbox mana pun.</li>
          <% } %>
          <% messages.forEach(function (msg) { %>
            <li class="list-group-item">
              <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div class="d-flex align-items-center flex-wrap" style="gap:.5rem">
                  <a href="/otp/<%= encodeURIComponent(msg.email) %>" class="badge" style="background-color:<%= emailColor(msg.email) %>;color:#222;font-weight:600">
                    Akun: <%= msg.email %>
                  </a>
                  <span class="otp-code" style="font-size:1.3rem;font-weight:700;letter-spacing:2px"><%= msg.otp_code %></span>
                  <button class="btn btn-sm btn-link btn-copy-otp p-0" data-code="<%= msg.otp_code %>" title="Salin kode">
                    <i class="fas fa-copy"></i>
                  </button>
                </div>
                <span class="badge badge-secondary otp-countdown" data-expires="<%= msg.expires_at %>">-</span>
              </div>
              <div class="small text-muted"><%= msg.subject %> &middot; dari <%= msg.sender %></div>
              <div class="small text-muted"><%= jamFormat(msg.received_at) %></div>
            </li>
          <% }); %>
        </ul>
      </div>
    </div>
  </div>
</div>

<script src="/js/otp.js?v=<%= assetVersion %>"></script>
