<template>
  <div class="login-box__container-outer">
    <form class="login-box__container-inner" @submit.prevent="login">
      <input v-model="authCode" v-focus class="login-box__authinput" type="text" size="6" maxlength="6"
        placeholder="Code" />
      <Button type="submit">Go!</Button>
      <div v-if="errorMessage" class="login-box__error">{{ errorMessage }}</div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from '#app'
import { ref, Ref } from 'vue'
import useAuth from '@/composables/useAuth';

const { authenticate, isAuthenticated } = useAuth()
const router = useRouter()

const vFocus = { mounted: (el: HTMLElement) => el.focus() }

const authCode: Ref<string> = ref('')
const errorMessage: Ref<string> = ref('')

if (await isAuthenticated()) {
  router.push('/play')
}

const login = (): void => {
  errorMessage.value = ''

  authenticate(authCode.value).then(() => {
    router.push('/play')
  }).catch(() => {
    errorMessage.value = 'login failed'
  })
}
</script>

<style lang="scss">
@import '~/assets/css/components';

.login-box {
  &__container-outer {
    display: flex;
    width: 240px;
  }

  &__container-inner {
    margin: 0 0 0 auto;
  }

  &__authinput {
    display: inline;
    position: relative;
    height: 36px;
    margin: 0 16px;
    background: transparent;
    border: none;
    border-bottom: $box-primary-border;
    color: $text-primary-color;
    font-family: $secondary-font;
    font-weight: 800;
    font-size: 24px;
    outline: none;
  }

  &__error {
    position: absolute;
    width: 240px;
    text-align: center;
    margin: 8px;
    color: $text-error-color;
  }
}
</style>