<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">
  <form class="form" on:submit={()=>{


        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

    });

  }}>
    <h1>Créer une salle</h1>
    <InputWithLabel label="Nom de la salle" bind:value={name} minlength="3" maxlength="20" required/>
    {#if !$isAuth}
      <InputWithLabel label="Votre pseudo" bind:value={pseudo} minlength="4" maxlength="15" required/>
    {/if}
    <button
      class="primary-btn"

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

    </button>
  </form>
</div>
<svelte:head>
  <title>Créer une salle</title>
</svelte:head>
<style lang="scss">
  h1 {
    font-size: 3em;
    margin-top: 20px;
  }

  .form {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
    width: min(100%, 666px);
    padding: 7px 20px;
  }

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

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