<script>
  import { api } from "../lib/api.js";
  import Icon from "../lib/Icon.svelte";

  let { onpaired } = $props();
  let code = $state("");
  let submitting = $state(false);
  let error = $state("");

  function input(event) {
    code = event.currentTarget.value.replace(/\D/g, "").slice(0, 8);
    error = "";
  }

  async function submit() {
    if (code.length !== 8 || submitting) return;
    submitting = true;
    error = "";
    try {
      await api("/api/auth/pair", {
        method: "POST",
        body: JSON.stringify({ code })
      });
      onpaired();
    } catch (cause) {
      error = cause.message || "配对失败，请重新生成配对码后再试";
    } finally {
      submitting = false;
    }
  }
</script>

<main class="pairing-screen">
  <section class="pairing-card">
    <div class="pairing-brand"><span class="brand-mark"><Icon name="bot" size={22} /></span><strong>PicoBot</strong></div>
    <div class="pairing-icon"><Icon name="lock" size={24} /></div>
    <h1>配对此浏览器</h1>
    <p>这是一个新浏览器。请在运行 Gateway 的设备上生成一次性配对码，然后在下方输入。</p>
    <code class="pairing-command">picobot pair</code>
    <form onsubmit={(event) => { event.preventDefault(); submit(); }}>
      <label for="pairing-code">8 位配对码</label>
      <input
        id="pairing-code"
        value={code}
        oninput={input}
        inputmode="numeric"
        autocomplete="one-time-code"
        placeholder="00000000"
        maxlength="8"
      />
      {#if error}<div class="pairing-error" role="alert">{error}</div>{/if}
      <button class="primary" type="submit" disabled={code.length !== 8 || submitting}>
        {submitting ? "正在验证…" : "配对并进入"}
      </button>
    </form>
    <small>配对码 5 分钟内有效且只能使用一次。设备凭据将以 HttpOnly Cookie 保存。</small>
  </section>
</main>
