<h1>创建账号</h1>
<form method="post" id="mainForm">
  <p class="error" id="error"></p>

  <fieldset>
    <p>请设置未来登录本服务器时使用的凭据。</p>
    <ol>
      <li>
        <label for="email">邮箱：</label>
        <input id="email" type="email" name="email" autofocus>
      </li>
      <li>
        <label for="password">密码：</label>
        <input id="password" type="password" name="password">
      </li>
      <li>
        <label for="confirmPassword">确认密码：</label>
        <input id="confirmPassword" type="password" name="confirmPassword">
      </li>
    </ol>
  </fieldset>

  <p class="actions">
    <button type="submit" name="submit" disabled>注册</button>
    <button type="button" id="login-link">返回</button>
  </p>
</form>


<script>
  let passwordCreateUrl;
  let oidcLocation;

  (async() => {
    let controls = await fetchControls('<%= idpIndex %>');

    setRedirectClick('login-link', controls.html.password.login);

    addPostListener(async() => {
      validatePasswordConfirmation('password');

      // 缓存账号创建信息，避免新增密码时失败
      if (!passwordCreateUrl) {
        const res = await fetch(controls.account.create, {method: 'POST'});
        const json = await res.json();
        // 仅在 OIDC 交互时会返回跳转地址
        oidcLocation = json.location;

        // 携带 Cookie 再次获取最新控制信息
        controls = await fetchControls('<%= idpIndex %>');
        passwordCreateUrl = controls.password.create;
      }

      await postJsonForm(passwordCreateUrl);

      // 若存在 OIDC 交互，需要继续推进流程
      if (oidcLocation) {
        await fetch(oidcLocation);
      }

      // 无论是否存在交互，完成后都跳转到账户页面
      location.href = controls.html.account.account;
    });
  })();
</script>
