<template>
  <form @submit.prevent="submit" class="relative px-6 py-[70px]">
    <div class="flex flex-col gap-5 p-2 mb-8 relative">
      <div class="w-full grid gap-3 relative">
        <input class="input-field xs:min-w-[350px] min-w-64" id="username-login" v-model="username" type="text" name="username" placeholder="Username" required autofocus />
        <div class="relative">
          <input class="input-field xs:min-w-[350px] min-w-64" id="password-login" v-model="password" :type="showPassword ? 'text' : 'password'" name="password" placeholder="Password" required />
          <button type="button" @click.prevent="showPassword = !showPassword" :class="{ 'eye-open': showPassword }" class="bg-[url('/assets/icons/eye.svg')] p-0 absolute right-3 w-5 h-4 top-1/2 -translate-y-1/2 bg-no-repeat bg-center"></button>
        </div>
        <span v-if="formError" class="text-red-200 text-xs absolute top-full mt-1">{{ formError }}</span>
      </div>
      <button @click.stop="() => emit('openResetPasswordModal')" type="button" class="inline-flex self-end p-0 text-cyan-300 text-base">Forgot password?</button>
      <button class="btn-cyan px-0 xs:w-full" type="submit">Play now</button>

      <!-- Divider shape -->
      <div class="absolute w-40 h-0.5 -bottom-8 left-1/2 -translate-x-1/2 flex justify-between">
        <div class="w-0.5 h-full bg-gray-300"></div>
        <div class="w-36 h-full bg-gray-300"></div>
        <div class="w-0.5 h-full bg-gray-300"></div>
      </div>
    </div>
    <div class="pt-8">
      <p class="m-0 text-center">Don't have an account? <button class="text-cyan-300 text-base p-0" @click.prevent="() => emit('switchToRegister')">Sign up</button></p>
    </div>
  </form>
</template>

<script setup lang="ts">
import { socketManager } from '@/managers/SocketManager'
import { login } from '@/services/authenticationService'
import { useGameStore } from '@/stores/gameStore'
import { useCookies } from '@vueuse/integrations/useCookies'
import { onMounted, ref } from 'vue'

const emit = defineEmits(['openResetPasswordModal', 'switchToRegister'])

const gameStore = useGameStore()
const username = ref('')
const password = ref('')
const formError = ref('')
const showPassword = ref(false)

async function submit() {
  // check if username and password are valid
  if (username.value === '' || password.value === '') {
    formError.value = '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) {
    formError.value = response.error
    return
  }
  socketManager.setToken(response.token)
  gameStore.initConnection()
  return true // Indicate success
}
</script>
