<template>
  <pn-page-template>
    <template #title>
      {{$t('agreements__title')}}
    </template>

    <div class="flex column w100 q-py-md q-px-lg q-gutter-y-sm text-caption">
      <div class="text-body1">
        <div v-if="route.query.type === 'update'">{{ $t('agreements__description_update') }}</div>
        <div>{{ $t('agreements__description') }}</div>
      </div>
      <agreement-block v-model="agreement"/>
    </div>

    <template #card-actions>
      <div class="column no-wrap items-center w100">
        <q-btn
          color="primary"
          no-caps rounded
          :disable="agreement.length !== 2"
          @click="onSubmit"
          class="fix-disabled-btn w100"
          >
          {{$t('agreements__btn_agree')}}
        </q-btn>

        <q-btn
          flat
          color="negative"
          no-caps rounded
          style="opacity: 0.6"
          @click="onDecline"
          class="q-mt-md w100"
          >
          <div class="flex column items-center">
            {{ $t('agreements__btn_decline') }}
            {{ $t('agreements__btn_decline_description') }}
          </div>
        </q-btn>
      </div>
    </template>

  </pn-page-template>
</template>

<script setup lang="ts">
  import { ref, inject, onMounted, onUnmounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useAuthStore } from 'stores/auth'
  import agreementBlock from 'components/agreementBlock.vue'
  import type { WebApp } from '@twa-dev/types'
  const tg = inject('tg') as WebApp

  function onDecline () {
    tg.close()
  }

  const route = useRoute()

  const authStore = useAuthStore()
  const router = useRouter()
  const submitAccept = ref(false)

  async function onSubmit () {

    sessionStorage.removeItem('agreement')
    submitAccept.value = true
    
    if (!route.query.type) {
      await authStore.logout()
      await router.push({ name: 'login' })
      return
    }

    if (route.query.type === 'register') { // if register with email - agreement inside agreement-block
      await authStore.registerWithTelegram(tg.initData)
      await authStore.loginWithTelegram(tg.initData)
      await router.push({ name: 'projects' })
    }

    if (route.query.type === 'update') {
      await authStore.termsAccepted()
      await router.push({ name: 'projects' })
    }
  }

  const agreement = ref<('terms'| 'consent')[]>([])

  onMounted(() => {
     const a = sessionStorage.getItem('agreement')
     if (a) agreement.value = JSON.parse(a)
  })
  onUnmounted(() => {
    if (!submitAccept.value) sessionStorage.setItem('agreement', JSON.stringify(agreement.value))
  })

</script>

<style>
</style>
