<template>
  <div>
    <video-background
      src="/video/bg-video.mp4"
      poster="/images/poster.png"
      style="height: 100vh;"
    >
      <div class="container-fluid">
        <div class="row ">
          <div class="col-12 col-lg-4 bg-img d-none d-lg-block" style="background-image: url('/images/login.svg');background-size: cover;height: 100vh;" />
          <div class="col-12 col-lg-8 pt-4 px-3 px-sm-5 px-md-5 pb-5">
            <div class="row">
              <div class="col-12 py-3 text-center">
                <img src="/images/logo.svg" height="35" class="img " alt="Mindboost Logo">
              </div>
            </div>
            <div class="row mt-lg-0 mt-4" style="height: 90%">
              <div class="col-12 my-auto">
                <div class="text-center pt-4 pt-md-2 col-12 col-md-8 col-xl-8 mx-auto">
                  <h1 class="fw-bolder h3" style="color: #585C5E;">
                    {{ t('Log in Header') }}
                  </h1>
                  <h2 class="text-muted h5 pt-2">
                    {{ t('Log in') }}
                  </h2>
                </div>
                <div class="row pt-2">
                  <div class="col-12 col-md-8 col-xl-8 mx-auto">
                    <form method="POST" @submit.prevent="loginNow">
                      <div class="row pt-4">
                        <div class="col-12">
                          <label class="form-label">{{ t('Email') }}</label>
                          <input v-model="form.email" type="email" autocomplete="email" class="form-control">
                          <div v-if="errors.email" class="invalid-feedback d-block">
                            {{ errors.email[0] }}
                          </div>
                          <div v-if="auth_error" class="invalid-feedback d-block">
                            {{ t(auth_error_message) }}
                          </div>
                        </div>
                      </div>
                      <div class="row pt-3">
                        <div class="col">
                          <label class="form-label">{{ t('Password') }}</label>
                          <input
                            v-model="form.password"
                            type="password"
                            name="password"
                            autocomplete="current-password"
                            class="form-control"
                          >
                          <span class="float-end pt-2">
                            <router-link :to="localePath('/auth/forgot')" class="forgot-link" href="#">{{ t('Forgot Password?') }}</router-link>
                          </span>
                        </div>
                      </div>
                      <div class="row pt-4">
                        <div class="col">
                          <button type="submit" style="min-width:fit-content" class="login-btn col-4">
                            {{ t('Sign in') }} <div v-if="loading" class="spinner-border spinner-border-sm" role="status">
                              <span class="sr-only">{{ t('Loading...') }}</span>
                            </div>
                          </button>
                          <p class="pt-3">
                            {{ t('No account?') }} <NuxtLink class="signup-link" :to="localePath('/auth/signup')">
                              {{ t("Sign up now") }}
                            </NuxtLink>
                          </p>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </video-background>
  </div>
</template>
<script>
import { mapState, mapActions } from 'pinia'
import backgroundImagePath from '~/assets/image/login4.png'
import { useUserStore } from '@/stores/user'
// import { useBufferStore } from '~/stores/buffer'
export default {
  name: 'Login',
  setup () {
    const { t } = useI18n()
    const localePath = useLocalePath()

    return {
      t,
      localePath
    }
  },
  data () {
    return {
      loading: false,
      form: {
        email: '',
        password: ''
      },
      auth_error: false,
      auth_error_message: '',
      backgroundImagePath,
      errors: []
    }
  },
  computed: {
    ...mapState(useUserStore, ['is_login', 'user', 'token']),
    translate (tag) {
      return this.t(tag)
    }
  },
  mounted () {
    if (this.$route.query.verified === '1') {
      this.$toast.success('Deine E-Mail wurde erfolgreich verifiziert. Bitte melde dich an.')
    }
    // useNuxtApp().$logger.log({ nuxtApp })

    // useNuxtApp().$logger.log({ db })

    // if (this.is_login){
    //   this.$router.push('/onboarding');
    // }
  },
  methods: {
    ...mapActions(useUserStore, ['login', 'logout']),
    loginNow () {
      this.errors = []
      this.auth_error = false
      this.loading = true

      this.$axios.post('/api/login', this.form).then(({ data }) => {
        this.loading = false

        if (data.status === 'success') {
          this.$axios.head.Authorization = 'bearer ' + data.authorisation.token
          this.login(data.user, data.authorisation.token)
          this.$toast.success('Login successful!')
          //
          // If a user already did the onboarding, then the soundscape will be defined, so we can jump
          // directly to the selected soundscape and start play.
          //
          let soundscape = 'Lagoon'
          if (data.user.settings) { // if the user logged in first time no settings available, so push to onboarding
            soundscape = data.user.settings.soundscape
            if (soundscape !== '') {
            // const soundscape = user.user.settings.soundscape
              let url
              switch (soundscape) {
                case 'Lagoon':
                  url = '/'
                  break
                case 'Meadow':
                  url = '/'
                  break
                case 'Tropics':
                  url = '/'
                  break
                case 'Forest':
                  url = '/'
                  break
                default:
                  url = '/'
                  break
              }
              this.$router.push(this.localePath(url))
            }
          } else {
            this.$router.push(this.localePath('/onboarding'))
          }
        } else {
          this.$toast.error('Email or password is incorrect.')
        }
      }).catch((error) => {
        if (error.message === 'user is not defined') {
          this.loading = false
        } else {
          this.loading = false
          if ((error.code === 'ERR_NETWORK' || error.code === 'NS_ERROR_DOM_BAD_URI') && this.user !== null && this.token !== '') {
            this.$toast.warn(this.translate('Offline mode, please go online soon.'))
            this.login(this.user, this.token)
          }
          this.auth_error = true

          if (error.response.status === 500) {
            this.auth_error_message = 'Es ist etwas schiefgelaufen. Versuche es später erneut'
          }
          if (error.response.status === 401) {
            this.auth_error_message = 'Email oder Passwort ist falsch.'
          }
          if (error.response.status === 403) {
            this.auth_error_message = 'Bitte bestätige zuerst deine E-Mail-Adresse.'
          }
          if (error.response.status === 422) {
            this.errors = error.response.data.errors
            this.auth_error = false
          }
        }
      })
    }

  }
}
</script>
<style>
.videobg-content{
  overflow: auto !important;
}
</style>
~/stores/audio
