<script setup lang="ts">
import { useErrorStore } from '@/stores/errors'
import { ref } from 'vue'
import { usePlayerAuthStore } from '@/stores/player-auth'
import router from '@/router'

const apiHost = import.meta.env.VITE_CONJUREOS_HOST

const errorStore = useErrorStore()

const isLoginIn = ref(false)
const signup = (form: HTMLFormElement) => {
  const formData = new FormData(form)
  isLoginIn.value = true
  const myHeaders = new Headers()
  myHeaders.append('API-Version', "1")
  fetch(apiHost + 'signup', {
    method: 'POST',
    body: formData,
    headers: myHeaders
  })
    .then((response) => {
      if (response.status !== 200)
        return response.text().then(error => {
            throw new Error(error)
          }
        )
      return response.text()
    })
    .then((result) => {
      isLoginIn.value = false
      console.log(result)
      usePlayerAuthStore().set(JSON.parse(result))
      router.push('/')
    })
    .catch((error) => {
      isLoginIn.value = false
      errorStore.unshift(error)
    })
}

</script>

<template>
  <article>
    <h1>Sign up</h1>
    <form ref="signupForm" enctype="multipart/form-data" @submit.prevent="signup($refs.signupForm as HTMLFormElement)">
      <label for="username">Username</label>
      <input required type="text"
             class="border border-primary rounded-lg px-3 py-2 bg-transparent focus:outline-none focus:border-accent"
             name="username" id="username" />
      <label for="password">Password</label>
      <input required type="password"
             class="border border-primary rounded-lg px-3 py-2 bg-transparent focus:outline-none focus:border-accent"
             name="password" id="password" />
      <button
        class="bg-transparent text-primary font-semibold hover:text-white py-2 px-4 border border-gray-500 hover:border-transparent rounded"
        type="submit">
        Signup
      </button>
    </form>
  </article>
</template>

<style scoped>
form {
  padding: 1rem 0;
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

input {
  outline: none !important;
  outline-offset: 0 !important;
  --tw-ring-color: --vt-c-silver !important;
}

label {
  margin-bottom: -1.5rem;
}
</style>