{% extends "_layout.html" %}
{% block title %}Sign in — unifi-api admin{% endblock %}
{% block content %}
<article style="max-width: 32rem; margin: 4rem auto;">
  <header>
    <h2>Sign in</h2>
    <p>Paste your admin API key — the <code>unifi_live_…</code> string emitted by the server on first boot.</p>
  </header>
  <form id="login-form" method="post" action="/admin/login">
    <label for="key">Admin API key</label>
    <input type="password" id="key" name="key" autocomplete="off" required />
    <p id="login-error" class="error" hidden></p>
    <button type="submit">Sign in</button>
  </form>
  <footer style="font-size: 0.85em; opacity: 0.75; margin-top: 1rem;">
    <p style="margin: 0;">Lost it? Retrieve from the container:</p>
    <pre style="margin: 0.25rem 0; padding: 0.5rem; overflow-x: auto;"><code>docker compose -f docker/docker-compose-api.yml exec \
  unifi-api-server cat /var/lib/unifi-api/bootstrap-admin-key</code></pre>
    <p style="margin: 0.5rem 0 0 0;">This is the admin API key, <strong>not</strong> the <code>UNIFI_API_DB_KEY</code> encryption key.</p>
  </footer>
</article>

{% if bootstrap_key %}
<script>
  // Server-rendered bootstrap: persist the validated key and redirect.
  localStorage.setItem('admin_bearer_key', {{ bootstrap_key | tojson }});
  window.location.href = '/admin/';
</script>
{% endif %}

{% if clear_storage %}
<script>
  localStorage.removeItem('admin_bearer_key');
</script>
{% endif %}

<script>
  // Validate the key against /v1/health/ready (admin-scoped) before letting the form submit.
  document.getElementById('login-form').addEventListener('submit', async function (ev) {
    if ({{ 'true' if bootstrap_key else 'false' }}) return;  // already-bootstrapped page
    ev.preventDefault();
    const key = document.getElementById('key').value;
    const errEl = document.getElementById('login-error');
    errEl.hidden = true;
    try {
      const resp = await fetch('/v1/health/ready', { headers: { 'Authorization': 'Bearer ' + key } });
      if (!resp.ok) throw new Error('rejected');
    } catch (_) {
      errEl.textContent = 'Invalid key. Try again.';
      errEl.hidden = false;
      return;
    }
    // Key passed admin-scoped probe — submit so server can render the bootstrap script.
    ev.target.submit();
  });
</script>
{% endblock %}
