<script>
  import PocketBase from 'pocketbase';
  import Input from '$lib/components/base/Input.svelte';
  import Button from '$lib/components/base/Button.svelte';
  import { onMount } from 'svelte';

  let pb

  let error = $state("")
  let validation = $state("")

  onMount(() => {
    pb = new PocketBase(window.location.origin)
  })

  async function signup(form) {
    error = ""
    validation = ""
    const formData = new FormData(form.target)
    const data = {};
    for (let field of formData) {
      const [key, value] = field;
      data[key] = value;
    }
    console.log(data)
    try {
      const record = await pb.collection('users').create({
        "password": data.password,
        "passwordConfirm": data.confirm_password,
        "email": data.email,
        "name": data.username,
        "emailVisibility": false
      })

      await pb.collection('users').requestVerification(data.email);

      validation = "Email de vérification envoyé à " + data.email
    } catch (err) {
      error = err.toString()
      console.log("Failed to create account");
    }
  }

</script>

<div class="flex flex-col items-center mt-32 h-full p-8">
  <form class="flex flex-col gap-4 max-w-lg w-full" onsubmit={(e) => {e.preventDefault(); signup(e)}}>
    <Input name="email" placeholder="Email" type="email" />
    <Input name="username" placeholder="Nom d'utilisateur·rice" type="text" />
    <Input name="password" placeholder="Mot de passe" type="password" />
    <Input name="confirm_password" placeholder="Confirmation du mot de passe" type="password" />
    {#if error != ""}
      <span class="bg-red-200 text-sm rounded-md p-2">{error}</span>
    {/if}
    {#if validation != ""}
      <span class="bg-green-200 text-sm rounded-md p-2">{validation}</span>
    {/if}
    <Button>Inscription</Button>
  </form>
</div>
