<script lang="ts">
  import { createRoom } from "../../../requests/room.request";
  import { getContext } from "svelte";
  import { goto } from "$app/navigation";
  import InputWithLabel from "../../../components/forms/InputWithLabel.svelte";

  let name = "";
  let pseudo = "";
  const { isAuth } = getContext("auth");
  let loading = false;
  const { error } = getContext("notif");
</script>

<div class="container">
  <div class="form">
    <h1>Créer une salle</h1>
    <InputWithLabel label="Nom de la salle" bind:value={name} />
    {#if !$isAuth}
      <InputWithLabel label="Votre pseudo" bind:value={pseudo} />
    {/if}
    <button
      class="primary-btn"
      on:click={() => {

        loading = true
		createRoom({ name }, !$isAuth ? pseudo : null).then((r) => {

            if(!$isAuth){
                sessionStorage.setItem('reconnect', r.member)
            }
			      goto(`/room/${r.room}`);
            loading= false
		}).catch((e) => {
      error("Erreur", "Une erreur est survenue lors de la création de la salle")
      loading= false

    });
	}}
    >
      {#if loading}
        <span class="spinner"></span>
      {:else}
        Créer
      {/if}

    </button>
  </div>
</div>

<style lang="scss">
  h1 {
    font-size: 3em;
    margin-top: 20px;
  }

  .form {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
    width: max-content;
  }

  .container {
    display: flex;
    justify-content: center;
  }

  .spinner {
    width: 15px;
    height: 15px;
    border-width: 2px !important;
  }
</style>
