<template>
  <div class="content-wrapper">
    <h1 class="main-title">NEW QUEST</h1>
    <form @submit.prevent="loginFunc">
      <div class="content-elements">
        <div class="login-form">
            <div class="form-field">
              <label for="username">Username</label>
              <input id="username" v-model="username" type="text" name="username" required autofocus />
            </div>
            <div class="form-field">
              <label for="password">Password</label>
              <input id="password" v-model="password" type="password" name="password" required />
            </div>
        </div>
        <div class="row-buttons">
          <button class="button btn-cyan" type="submit"><span>LOGIN</span></button>
          <button class="button btn-cyan" type="button" @click.prevent="registerFunc"><span>REGISTER</span></button>
          <button class="button btn-cyan"><span>CREDITS</span></button>
        </div>
      </div>
    </form>
  </div>
  <audio ref="bgm" id="bgm" src="/assets/music/bgm.mp3" loop autoplay></audio>
  <img draggable="false" src="/assets/bglogin.png" id="bg-img" alt="New Quest login background" />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { login, register } from '@/services/authentication'
import { useNotificationStore } from '@/stores/notifications'
import ZoneEditor from '@/components/utilities/zoneEditor/ZoneEditor.vue'
import Modal from '@/components/utilities/Modal.vue'

const bgm = ref('bgm')
if (bgm.value.paused) {
  window.addEventListener('click', () => bgm.value.play())
  window.addEventListener('keydown', () => bgm.value.play())
}

const notifications = useNotificationStore()
const username = ref('')
const password = ref('')

async function loginFunc() {
  // check if username and password are valid
  if (username.value === '' || password.value === '') {
    notifications.addNotification({ message: 'Please enter a valid username and password' })
    return
  }

  // send login event to server
  const response = await login(username.value, password.value)

  if (response.success === undefined) {
    notifications.addNotification({ message: response.error })
  }
}

async function registerFunc() {
  // check if username and password are valid
  if (username.value === '' || password.value === '') {
    notifications.addNotification({ message: 'Please enter a valid username and password' })
    return
  }

  // send register event to server
  const response = await register(username.value, password.value)

  if (response.success === undefined) {
    notifications.addNotification({ message: response.error })
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/scss/login';
</style>
