<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("")

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

  async function login(form) {
    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 authData = await pb.collection('users').authWithPassword(data.email, data.password);
      console.log(authData)
      console.log(pb.authStore.token);
      window.location.href = "/"
    } catch (err) {
      error = err.toString()
      console.log("Failed to log");
    }
  }

</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(); login(e)}}>
    <Input name="email" placeholder="email" type="email" />
    <Input name="password" placeholder="password" type="password" />
    {#if error != ""}
      <span class="bg-red-200 text-sm rounded-md p-2">{error}</span>
    {/if}
    <Button>Connexion</Button>
  </form>
</div>
