<script lang="ts">
  import { DEFAULT_CONFIG, loadConfig } from "../config.ts";
  import createDebug from "debug";
  import "../css/themes/catppuccin-mocha.scss";
  import "../css/style.scss";
  import { parseJwt } from "../jwt.ts";
  import HeartIcon from "../icons/HeartIcon.svelte";
  import Popup from "../components/ui/Popup.svelte";
  import Button from "../components/ui/Button.svelte";
  import TextInput from "../components/ui/TextInput.svelte";
  import PasswordInput from "../components/ui/PasswordInput.svelte";

  let config = DEFAULT_CONFIG;
  // Top-level await. Sets the default config, and overwrites it when the new config is avail. Thanks reactivity!
  (async () => {
    config = await loadConfig();
  })();

  const logger = createDebug("main");
  logger(
    `Hello, world! StarKingdoms ${APP_VERSION} (${COMMIT_HASH}) at your service!`,
  );
  logger("Current view: Login.svelte");

  if (window.localStorage.getItem("stk-token") != null) {
    let token = window.localStorage.getItem("stk-token")!;
    let jwt = parseJwt(token);
    if (jwt !== undefined) {
      window.location.href = "/";
    }
  }

  let username = "";
  let password = "";

  let error: string | null = null;

  async function login() {
    try {
      let resp = await fetch(`${config.backplane}/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      });

      let body = await resp.json();

      if (!resp.ok) {
        let r_error = body.errors[0];

        if (r_error.code === "ERR_UNAUTHORIZED") {
          error = "Invalid username or password";
        } else {
          error = JSON.stringify(body);
        }

        return;
      }

      window.localStorage.setItem("stk-token", body.token);
      window.location.href = "/";
    } catch (e: any) {
      error = e.toString();
    }
  }
</script>

<Popup title="Login" centered style="max-width: 300px;" id="title-popup">
  <form id="join-fm" class="form" on:submit|preventDefault={login}>
    <label for="username" class="label">Username</label>
    <TextInput
      style="width: 100%; max-width: 100%;"
      bind:value={username}
      id="username"
      required
      autocomplete="off" />

    <label for="password" class="label">Password</label>
    <PasswordInput
      style="width: 100%; max-width: 100%;"
      bind:value={password}
      id="password"
      required
      autocomplete="off" />

    <Button style="width: 100%; max-width: 100%;">Login!</Button>

    {#if error !== null}
      <span class="account-info" style="color: var(--error)">
        {error}
      </span>
    {/if}

    <span class="account-info">
      Don't have an account? <a href="/signup/">Create one!</a>
      Changed your mind?
      <a href="/">Back to the launchpad</a>
    </span>
  </form>
</Popup>

<span class="footer-left">
  StarKingdoms Client {APP_VERSION} ({COMMIT_HASH})
</span>
<span class="footer-right">
  Made with <HeartIcon class="footer-icon" /> by the StarKingdoms team
</span>
