<script setup>
import { ref, onMounted } from 'vue'
import IconLogo from './icons/IconLogo.vue';

const user = ref('')
const pass = ref('')

defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

async function login(ev) {
  ev.preventDefault()
  const api_url = '/api/auth'
  const payload = { username: user.value, password: pass.value }
  const fetch_options = {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: {
      'Content-Type': 'application/json'
    }
  }

  let resp = await fetch(api_url, fetch_options)
  if (resp.ok) {
    emit('update:modelValue', await resp.json())
    window.location.hash = "/"
  } else {
    user.value = ''
    pass.value = ''
  }
}

onMounted(async () => {
  let resp = await fetch("/api/user")
  if (resp.ok) {
    emit('update:modelValue', await resp.json())
    window.location.hash = "/"
  }
})
</script>

<template>
  <main class="form-signin w-100 m-auto position-absolute top-50 start-50 translate-middle">
    <form onsubmit="event.preventDefault();">
      <IconLogo />
      <h1 class="h3 mb-3 fw-normal">Please sign in</h1>

      <div class="form-floating">
        <input type="email" v-model="user" class="form-control" id="floatingInput" placeholder="username">
        <label for="floatingInput">Username</label>
      </div>
      <div class="form-floating">
        <input type="password" v-model="pass" class="form-control" id="floatingPassword" placeholder="Password">
        <label for="floatingPassword">Password</label>
      </div>
      <div class="form-floating mb-3">
        <a href="#/signup">Sign up</a>
      </div>

      <button type="submit" @click="login" class="btn btn-primary w-100 py-2">Sign in</button>

      <p class="mt-5 mb-3 text-body-secondary">&copy; 2023 Lucas Schumacher</p>
    </form>
  </main>
</template>

<style scoped>
.form-signin {
  max-width: 330px;
  padding: 1rem;
}

.form-signin .form-floating:focus-within {
  z-index: 2;
}

.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</style>
