<template>
  <div class="relative max-lg:h-dvh flex flex-row-reverse">
    <ResetPassword :isModalOpen="resetPasswordForm" />
    <div class="lg:bg-gradient-to-l bg-gradient-to-b from-gray-900 to-transparent w-full lg:w-1/2 h-[35dvh] lg:h-dvh absolute left-0 max-lg:bottom-0 lg:top-0 z-10"></div>
    <div class="bg-[url('/assets/login/login-bg.png')] w-full lg:w-1/2 h-[35dvh] lg:h-dvh absolute left-0 max-lg:bottom-0 lg:top-0 bg-no-repeat bg-cover bg-center"></div>
    <div class="bg-gray-900 z-20 w-full lg:w-1/2 h-[65dvh] lg:h-dvh relative">
      <div class="h-dvh flex items-center lg:justify-center flex-col px-8 max-lg:pt-20">
        <img src="/assets/login/sq-logo-v1.svg" class="mb-10" />
        <div class="relative">
          <img src="/assets/ui-elements/ui-box-outer.svg" class="absolute w-full h-full" />
          <img src="/assets/ui-elements/ui-box-inner.svg" class="absolute left-2 top-2 w-[calc(100%_-_16px)] h-[calc(100%_-_16px)] max-lg:hidden" />

          <!-- Login Form -->
          <form v-show="switchForm === 'login'" @submit.prevent="loginFunc" class="relative px-6 py-11">
            <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-4 h-3 top-1/2 -translate-y-1/2 bg-no-repeat"></button>
                </div>
                <span v-if="loginError" class="text-red-200 text-xs absolute top-full mt-1">{{ loginError }}</span>
              </div>
              <button @click.stop="resetPasswordForm = !resetPasswordForm" 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="switchForm = 'register'">Sign up</button></p>
            </div>
          </form>

          <!-- Register Form -->
          <form v-show="switchForm === 'register'" @submit.prevent="registerFunc" class="relative px-6 py-11">
            <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-register" v-model="username" type="text" name="username" placeholder="Username" required autofocus />
                <input class="input-field xs:min-w-[350px] min-w-64" id="email-register" v-model="email" type="email" name="email" placeholder="Email" required />
                <div class="relative">
                  <input class="input-field xs:min-w-[350px] min-w-64" id="password-register" 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-4 h-3 top-1/2 -translate-y-1/2 bg-no-repeat"></button>
                </div>
                <span v-if="loginError" class="text-red-200 text-xs absolute top-full mt-1">{{ loginError }}</span>
              </div>
              <button class="btn-cyan xs:w-full" type="submit">Register 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">Already have an account? <button class="text-cyan-300 text-base p-0" @click.prevent="switchForm = 'login'">Log in</button></p>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { login, register } from '@/services/authentication'
import { useGameStore } from '@/stores/gameStore'
import { useCookies } from '@vueuse/integrations/useCookies'
import ResetPassword from '@/components/utilities/ResetPassword.vue'

const props = defineProps(['isModalOpen'])
const resetPasswordForm = ref(props.isModalOpen)

const gameStore = useGameStore()
const username = ref('')
const password = ref('')
const email = ref('')
const switchForm = ref('login')
const loginError = ref('')
const showPassword = ref(false)

// automatic login because of development
onMounted(async () => {
  const token = useCookies().get('token')
  if (token) {
    gameStore.setToken(token)
    gameStore.initConnection()
  }
})

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

async function registerFunc() {
  // check if username and password are valid
  if (username.value === '' || email.value === '' || password.value === '') {
    loginError.value = 'Please enter a valid username, email, and password'
    return
  }

  if (email.value === '') {
    loginError.value = 'Please enter an email'
    return
  }

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

  if (response.success === undefined) {
    loginError.value = response.error
    return
  }

  const loginSuccess = await loginFunc()
  if (!loginSuccess) {
    loginError.value = 'Login after registration failed. Please try logging in manually.'
    return
  }
}
</script>
