<script>
  import Api from "./api.ts";

  let error;
  let password = "";
  let username = Api.getUsername();

  const states = {
    username: 1,
    password: 2
  };

  let state = states.username;

  let salt;

  export let setLoading;
  export let next;

  async function buttonClick() {
    setLoading(true);
    if (state === states.username) {
      let res = await Api.setUsername(username);
      if (res.error) {
        error = res.error;
      } else {
        state = states.password;
        error = undefined;
      }
    } else if (state === states.password) {
      let res = await Api.setPassword(password);
      if (res.error) {
        error = res.error;
      } else {
        error = undefined;
        next();
      }
    }

    setLoading(false);
  }
</script>

<style>
  .error {
    color: var(--error);
    padding: 4px;
  }

  .wide-button {
    width: 100%;
    margin: 0;
  }
</style>

{#if state === states.username}
  <h3>Enter your Username or your E-Mail Address</h3>
  <div class="floating group">
    <input
      type="text"
      autocomplete="username"
      autofocus
      bind:value={username} />
    <span class="highlight" />
    <span class="bar" />
    <label>Username or E-Mail</label>
    <div class="error" style={!error ? 'display: none;' : ''}>{error}</div>
  </div>
{:else}
  <h3>Enter password for {username}</h3>
  <div class="floating group">
    <input
      type="password"
      autocomplete="password"
      autofocus
      bind:value={password} />
    <span class="highlight" />
    <span class="bar" />
    <label>Password</label>
    <div class="error" style={!error ? 'display: none;' : ''}>{error}</div>
  </div>
{/if}

<button class="btn btn-primary wide-button" on:click={buttonClick}>Next</button>
