<template>
  <div>
    <video-background
      src="/video/bg-video.mp4"
      style="height: 100vh;"
      poster="/images/poster.png"
    >
      <div class="container-fluid overflow-auto">
        <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" style="height: 90%">
              <div class="col-12 my-auto">
                <div class="text-center pt-1 ">
                  <h2 class="fw-bolder display-6 text-center">
                    {{ t('Welcome, Tester!') }}
                  </h2>
                  <span class="fs-5 pt-1 text-muted">{{ t('Thank you for using and improving Mindboost') }}</span>
                </div>
                <div class="row pt-2">
                  <div class="col-12">
                    <form method="POST" class=" pb-5 " @submit.prevent="submitRegister()">
                      <div class="row pt-3 justify-content-center">
                        <div class="col-12 col-sm-8 col-md-8 col-lg-6">
                          <label class="form-label">{{ t('Name') }}</label>
                          <input v-model="form.email" type="input" placeholder="e.g. your name, a tag, date or what ever you like.." class="form-control">
                          <div v-if="errors.email" class="invalid-feedback d-block">
                            {{ t('Please add first a name') }}
                          </div>
                          <div v-if="auth_error" class="invalid-feedback d-block">
                            {{ t('Something is wrong, please try again!') }}
                          </div>
                        </div>
                      </div>
                      <div class="row justify-content-center pt-3">
                        <div class="col-12 col-sm-8 col-md-8 col-lg-6">
                          <label class="form-label">{{ t('Comments') }}</label>
                          <input v-model="form.password" type="input" :placeholder="t('How did you discover Mindboost?')" class="form-control">
                        </div>
                      </div>
                      <div class="row justify-content-center pb-5">
                        <div class="col-12 col-sm-8 col-md-8 col-lg-6 pt-4 text-center">
                          <button type="submit" class=" login-btn col-12">
                            {{ t('Go') }} <div v-if="loading" class="spinner-border spinner-border-sm" role="status">
                              <span class="sr-only">{{ t('Loading...') }}</span>
                            </div>
                          </button>

                          <h5 class="text-center pt-3">
                            {{ t("Want to have an Account?") }} <NuxtLink class="signup-link" :to="localePath('/auth/signup')">
                              {{ t("Sign Up") }}
                            </NuxtLink>
                          </h5>
                        </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: 'TestLogin',
  setup () {
    const { t } = useI18n()
    const localePath = useLocalePath()

    return {
      t,
      localePath
    }
  },
  data () {
    return {
      loading: false,
      form: {
        email: '',
        password: ''
      },
      auth_error: false,
      backgroundImagePath,
      errors: []
    }
  },
  computed: {
    ...mapState(useUserStore, ['is_login', 'user', 'token']),
    translate (tag) {
      const { t } = useI18n()
      return t(tag)
    }
  },
  mounted () {

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

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

    // if (this.is_login){
    //   this.$router.push('/onboarding');
    // }
  },
  methods: {
    ...mapActions(useUserStore, ['login', 'logout']),
    formatToValidEmail (input) {
      // eslint-disable-next-line no-useless-escape
      let email = input.replace(/[^a-zA-Z0-9\._-]/g, '') // Remove invalid characters
      if (!/@/.test(email)) {
        email += '@betatester.mindboost.team' // Append a default domain if no '@'
      } else if (email.split('@')[1] === '') {
        email += '@betatester.mindboost.team' // Append "example.com" if there is no domain part
      }
      return email
    },
    submitRegister () {
      this.loading = true
      const email = this.formatToValidEmail(this.form.email)
      this.$axios.post('/api/register', {
        first_name: this.form.email,
        surname: this.form.password || 'no comments',
        email,
        password: email
      }).then(({ data }) => {
        this.loading = false
        this.$toast.success('Signup successfully....')
        this.login(data.user, data.authorisation.token)
        this.$router.push(this.localePath('/onboarding'))
      }).catch((error) => {
        this.loading = false
        if (error.response.status === 422) {
          this.errors = error.response.data.errors
          this.$toast.error(error.response.data.message)
        }
      })
    },
    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 Successfully....')

          //
          // 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)
          }
          if (error.response.status === 500) {
            this.auth_error = true
            this.$toast.error('Es ist etwas schiefgelaufen. Versuche es später erneut')
          }
          if (error.response.status === 401) {
            this.auth_error = true
            this.$toast.error('Email or password is incorrect.')
          }
          if (error.response.status === 422) {
            this.errors = error.response.data.errors
          }
        }
      })
    }

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