<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 WarningIcon from "../icons/WarningIcon.svelte";
  import Popup from "../components/ui/Popup.svelte";
  import Button from "../components/ui/Button.svelte";
  import TextInput from "../components/ui/TextInput.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: <index>");

  let is_logged_in = false;
  let token_username = undefined;

  if (window.localStorage.getItem("stk-token") != null) {
    let token = window.localStorage.getItem("stk-token")!;
    let token_parsed: any = parseJwt(token);
    if (token_parsed !== undefined) {
      is_logged_in = true;
      token_username = token_parsed.username;
    }
  }

  const is_development = window.localStorage.getItem("stk-mode") === "debug";

  let nonprod_warning: HTMLSpanElement;

  let server = "";
  let username = "";

  function playGame() {
    window.location.href = `/play/?srv=${server}&username=${username}`;
  }

  function updateNonprodWarning() {
    if (
      config.servers[server] !== undefined &&
      !config.servers[server].isProduction
    ) {
      nonprod_warning.classList.remove("hidden");
    } else {
      nonprod_warning.classList.add("hidden");
    }
  }
</script>

<Popup title="StarKingdoms" centered style="max-width: 300px;" id="title-popup">
  <h2>Join Game</h2>

  <form id="join-fm" class="form" on:submit|preventDefault={playGame}>
    <label for="username" class="label">Username</label>
    <TextInput
      style="width: 100%; max-width: 100%;"
      bind:value={username}
      id="username"
      required
      autocomplete="off" />

    <label class="label" for="select">Server</label>
    <select
      bind:value={server}
      on:change={updateNonprodWarning}
      id="select"
      class="select"
      autocomplete="off">
      {#each Object.entries(config.servers) as [server_id, server]}
        {#if server.isDevelopment && !is_development}
          <!-- Ignore. Dev server and we arent dev -->
        {:else}
          <option value={server_id}>{server.name}</option>
        {/if}
      {/each}
    </select>

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

    <span bind:this={nonprod_warning} class="server-danger hidden">
      <WarningIcon class="server-danger-icon" />
      Here be dragons! You have a
      <b>prerelease server</b>
      selected. Expect bugs, and save data on this server may be wiped at any time.
    </span>

    <span id="account-info" class="account-info">
      {#if is_logged_in}
        Logged in as {token_username}! Saves will be stored in your browser
        during the alpha, but will be stored on the server soon!
        <a
          href="#"
          on:click={() => {
            window.localStorage.removeItem("stk-token");
            window.location.reload();
          }}>
          Logout
        </a>
      {:else}
        You are not logged in. Save data will be stored in your browser cache. <a
          href="/login/">
          Log in
        </a>
        to save your data on the server and sync it between devices.
      {/if}
    </span>
  </form>
</Popup>

<span style="position: absolute; right: 0.5rem; top: 0.5rem; background-color: var(--bg-secondary-1);">
    <a href="/shipeditor/" style="color: var(--text)">
        <Button>
        Ship Editor
        </Button>
    </a>
</span>

<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>
